BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

marketplace.test.js 24.0 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 potionListingKey
19} from "../../shared/market/listingKey.js";
20import { alchemyPotionDefinition } from "../../shared/definitions/alchemy.js";
21import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
22import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
24import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
25
26test("blank cheques cannot be listed on the marketplace", () =>
27{
28 const stack = { itemId: ItemId.blankCheque, quantity: 1 };
29 assert.equal(canSellOnMarketplace(stack), false);
30 assert.throws(
31 () => assertMarketplaceSellable(stack),
32 (err) => err.message === "Blank cheques cannot be sold on the marketplace."
33 );
34});
35
36test("written cheques can be listed on the marketplace", () =>
37{
38 const stack = {
39 itemId: ItemId.filledCheque,
40 quantity: 1,
41 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
42 };
43 assert.equal(canSellOnMarketplace(stack), true);
44 assert.doesNotThrow(() => assertMarketplaceSellable(stack));
45});
46
47test("normal items are marketplace sellable by default", () =>
48{
49 assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
50});
51
52test("fully charged tinderbox can list on CE; worn cannot", () =>
53{
54 const fresh = {
55 itemId: CraftingItemId.tinderbox,
56 quantity: 1,
57 instance: tinderboxItemInstance(6)
58 };
59 const worn = {
60 itemId: CraftingItemId.tinderbox,
61 quantity: 1,
62 instance: tinderboxItemInstance(1)
63 };
64 assert.equal(canSellOnMarketplace(fresh), true);
65 assert.equal(canSellOnMarketplace(worn), false);
66 assert.throws(
67 () => assertMarketplaceSellable(worn),
68 (err) => /partially used/i.test(err.message)
69 );
70});
71
72test("full potions and dyes can list on CE; sipped or used cannot", () =>
73{
74 const fullPotion = {
75 itemId: ItemId.potion,
76 quantity: 1,
77 instance: potionItemInstance({
78 potionKey: "lesserHealthTonic",
79 displayName: "Lesser health tonic",
80 color: { r: 0.95, g: 0.38, b: 0.32 },
81 fillLevel: 4,
82 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
83 effectKey: "health-regen"
84 })
85 };
86 const sipped = {
87 ...fullPotion,
88 instance: { ...fullPotion.instance, fillLevel: 3 }
89 };
90 const fullDye = {
91 itemId: ItemId.dye,
92 quantity: 1,
93 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 4)
94 };
95 const usedDye = {
96 itemId: ItemId.dye,
97 quantity: 1,
98 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 2)
99 };
100 const unstableFull = {
101 itemId: ItemId.potion,
102 quantity: 1,
103 instance: potionItemInstance({
104 potionKey: "unstable:glow",
105 unstable: true,
106 displayName: "Unstable draught",
107 color: { r: 0.95, g: 0.9, b: 0.45 },
108 fillLevel: 3,
109 effectKey: "glow",
110 effect: { type: "glow", lightRadiusTiles: 2, durationMs: 10_000 }
111 })
112 };
113 const unstableSipped = {
114 ...unstableFull,
115 instance: { ...unstableFull.instance, fillLevel: 2 }
116 };
117 assert.equal(canSellOnMarketplace(fullPotion), true);
118 assert.equal(canSellOnMarketplace(sipped), false);
119 assert.equal(canSellOnMarketplace(fullDye), true);
120 assert.equal(canSellOnMarketplace(usedDye), false);
121 assert.equal(canSellOnMarketplace(unstableFull), true);
122 assert.equal(canSellOnMarketplace(unstableSipped), false);
123});
124
125test("letters cannot be listed on the marketplace", () =>
126{
127 const own = {
128 itemId: ItemId.letter,
129 quantity: 1,
130 instance: {
131 kind: "letter",
132 letterId: "x",
133 authorCharacterId: 1,
134 authorDisplayName: "Ada",
135 body: "Hi",
136 opened: true
137 }
138 };
139 const received = {
140 ...own,
141 instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }
142 };
143 assert.equal(canSellOnMarketplace(own, 1), false);
144 assert.equal(canSellOnMarketplace(received, 1), false);
145 assert.throws(
146 () => assertMarketplaceSellable(own, 1),
147 (err) => /letters cannot be sold on the marketplace/i.test(err.message)
148 );
149});
150
151test("midpoint trade price rounds half units deterministically", () =>
152{
153 assert.equal(midpointTradePrice(100, 80), 90);
154 assert.equal(midpointTradePrice(101, 80), 91);
155 assert.equal(midpointTradePrice(80, 100), 90);
156});
157
158test("listing fee is 3% of notional rounded up", () =>
159{
160 assert.equal(marketOrderListingFee(100, 1), 3);
161 assert.equal(marketOrderListingFee(10, 1), 1);
162 assert.equal(marketOrderListingFee(8, 2), 1);
163 assert.equal(marketOrderListingFee(0, 5), 0);
164});
165
166test("cancel and expiry letters use side-specific escrow copy", () =>
167{
168 const buyCancel = orderCancelledLetterBody({
169 side: "buy",
170 itemName: "Flower",
171 quantity: 1,
172 escrowLabel: "coins",
173 clerkName: "Ada Ledger"
174 });
175 assert.match(buyCancel, /buy order for 1× Flower was cancelled/);
176 assert.match(buyCancel, /coins have been returned/);
177 assert.doesNotMatch(buyCancel, /coins has been returned/);
178
179 const sellCancel = orderCancelledLetterBody({
180 side: "sell",
181 itemName: "Apple",
182 quantity: 2,
183 escrowLabel: "Apple",
184 clerkName: "Ada Ledger"
185 });
186 assert.match(sellCancel, /sell order for 2× Apple was cancelled/);
187 assert.match(sellCancel, /listed goods have been returned/);
188
189 const buyExpired = orderExpiredLetterBody({
190 side: "buy",
191 itemName: "Flower",
192 quantity: 1,
193 escrowLabel: "coins",
194 clerkName: "Ada Ledger"
195 });
196 assert.match(buyExpired, /coins have been returned/);
197});
198
199test("market funds spend whole coin cheques and return change", () =>
200{
201 const slots = emptySlots();
202 slots[0] = {
203 itemId: ItemId.filledCheque,
204 quantity: 1,
205 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
206 };
207 const paid = takeMarketFunds(slots, 25);
208 assert.equal(paid.ok, true);
209 assert.equal(paid.change, 15);
210 assert.equal(paid.redeemedCheques.length, 1);
211 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
212});
213
214test("written cheque sell listing locks quantity to reserved goods", () =>
215{
216 const listing = resolveMarketSellListing({
217 itemId: ItemId.filledCheque,
218 quantity: 1,
219 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
220 });
221 assert.equal(listing.isCheque, true);
222 assert.equal(listing.itemId, ItemId.apple);
223 assert.equal(listing.quantity, 7);
224 assert.equal(listing.quantityLocked, true);
225});
226
227function placePlaza (worldDb)
228{
229 const data = createEmptyChunkData();
230 data.open = true;
231 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
232 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
233 worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
234}
235
236function recipePaperStack (potionKey, displayName)
237{
238 return {
239 itemId: ItemId.recipePaper,
240 quantity: 1,
241 instance: {
242 kind: "recipe-paper",
243 recipeId: `test-${potionKey}`,
244 potionKey,
245 displayName: displayName ?? recipePaperDisplayName(potionKey)
246 }
247 };
248}
249
250test("market catalog lists each alchemy recipe paper separately", () =>
251{
252 const catalog = buildMarketCatalogEntries({
253 lastSaleFor: () => null,
254 undiscountedMarketCoins: (itemId) => (itemId === ItemId.recipePaper ? 5 : 10),
255 now: Date.now(),
256 lerpDurationMs: 0,
257 settings: {}
258 });
259 const recipes = catalog.filter((entry) => entry.itemId === ItemId.recipePaper);
260 assert.ok(recipes.length > 1);
261 assert.ok(recipes.some((entry) => entry.listingKey === recipeListingKey("lesserHealthTonic")));
262 assert.ok(recipes.some((entry) => entry.displayName.toLowerCase().includes("lesser health tonic")));
263 assert.equal(recipes.some((entry) => !entry.listingKey), false);
264});
265
266test("market catalog lists each drinkable potion brew separately", () =>
267{
268 const catalog = buildMarketCatalogEntries({
269 lastSaleFor: () => null,
270 undiscountedMarketCoins: (itemId) => (itemId === ItemId.potion ? 7 : 10),
271 now: Date.now(),
272 lerpDurationMs: 0,
273 settings: {}
274 });
275 const potions = catalog.filter((entry) => entry.itemId === ItemId.potion);
276 assert.ok(potions.length > 1);
277 assert.ok(potions.some((entry) => entry.listingKey === potionListingKey("lesserHealthTonic")));
278 assert.ok(potions.some((entry) => entry.displayName === "Lesser health tonic"));
279 assert.equal(potions.some((entry) => !entry.listingKey), false);
280 assert.equal(potions.some((entry) => entry.displayName === "Potion"), false);
281 assert.equal(
282 potions.some((entry) => entry.listingKey === potionListingKey("tanningBrew")),
283 false,
284 "solid tanning brew output stays its own item id"
285 );
286});
287
288test("recipe paper sell listings carry listing keys", () =>
289{
290 const stack = recipePaperStack("lesserHealthTonic");
291 const listing = resolveMarketSellListing(stack);
292 assert.ok(listing);
293 assert.equal(listing.listingKey, recipeListingKey("lesserHealthTonic"));
294 assert.match(listing.displayName.toLowerCase(), /lesser health tonic recipe/);
295 assert.equal(listing.quantityLocked, true);
296});
297
298test("potion sell listings carry brew listing keys", () =>
299{
300 const potion = alchemyPotionDefinition("lesserHealthTonic");
301 const stack = {
302 itemId: ItemId.potion,
303 quantity: 3,
304 instance: potionItemInstance({
305 potionKey: potion.potionKey,
306 displayName: potion.displayName,
307 color: potion.color,
308 fillLevel: potion.fillLevel,
309 effect: potion.effect,
310 effectKey: potion.effect?.type
311 })
312 };
313 const listing = resolveMarketSellListing(stack);
314 assert.ok(listing);
315 assert.equal(listing.listingKey, potionListingKey("lesserHealthTonic"));
316 assert.equal(listing.displayName, "Lesser health tonic");
317 assert.equal(listing.quantityLocked, false);
318});
319
320test("recipe paper buy and sell orders only match the same recipe", () =>
321{
322 const lesserBuy = {
323 itemId: ItemId.recipePaper,
324 listingKey: recipeListingKey("lesserHealthTonic")
325 };
326 const lesserSell = {
327 itemId: ItemId.recipePaper,
328 listingKey: recipeListingKey("lesserHealthTonic"),
329 escrowStack: recipePaperStack("lesserHealthTonic")
330 };
331 const claritySell = {
332 itemId: ItemId.recipePaper,
333 listingKey: recipeListingKey("clarityPotion"),
334 escrowStack: recipePaperStack("clarityPotion")
335 };
336 assert.equal(marketOrdersCompatible(lesserBuy, lesserSell), true);
337 assert.equal(marketOrdersCompatible(lesserBuy, claritySell), false);
338});
339
340test("matching recipe paper buy and sell orders trade the specific recipe", () =>
341{
342 const harness = makeSimulation({ workerCount: 1 });
343 try
344 {
345 placePlaza(harness.worldDb);
346 harness.simulation.reloadWorld();
347
348 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Scribe", lastName: "One" });
349 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });
350 const sellerBag = addCoinsToSlots(emptySlots(), 5);
351 assert.equal(sellerBag.ok, true);
352 sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
353 harness.stateDb.saveBag(seller.character_id, {
354 inventory: sellerBag.slots,
355 equipment: emptyEquipment(),
356 vault: [],
357 vaultReserved: []
358 });
359 const buyerBag = addCoinsToSlots(emptySlots(), 100);
360 assert.equal(buyerBag.ok, true);
361 harness.stateDb.saveBag(buyer.character_id, {
362 inventory: buyerBag.slots,
363 equipment: emptyEquipment(),
364 vault: [],
365 vaultReserved: []
366 });
367
368 harness.simulation.spawnCharacter(1, seller);
369 harness.simulation.spawnCharacter(2, buyer);
370 harness.simulation.step();
371
372 harness.simulation.enqueue(1, {
373 type: "place-market-sell",
374 characterId: seller.character_id,
375 slotIndex: 1,
376 quantity: 1,
377 minUnitPrice: 8
378 });
379 const sellResult = harness.simulation.step();
380 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
381
382 harness.simulation.enqueue(2, {
383 type: "place-market-buy",
384 characterId: buyer.character_id,
385 itemId: ItemId.recipePaper,
386 listingKey: recipeListingKey("lesserHealthTonic"),
387 quantity: 1,
388 maxUnitPrice: 12
389 });
390 const buyResult = harness.simulation.step();
391 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
392 const trade = buyResult.events.find((event) => event.type === "market-trade");
393 assert.ok(trade, JSON.stringify(buyResult.events));
394 assert.equal(trade.quantity, 1);
395
396 const buyerBagNow = harness.simulation.bagOf(2);
397 const recipe = (buyerBagNow.inventory ?? []).find((slot) => slot?.itemId === ItemId.recipePaper);
398 assert.ok(recipe);
399 assert.equal(recipe.instance?.potionKey, "lesserHealthTonic");
400 }
401 finally
402 { harness.close(); }
403});
404
405test("matching potion buy and sell orders trade the specific brew", () =>
406{
407 const harness = makeSimulation({ workerCount: 1 });
408 try
409 {
410 placePlaza(harness.worldDb);
411 harness.simulation.reloadWorld();
412
413 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Alchem", lastName: "One" });
414 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });
415 const potion = alchemyPotionDefinition("lesserHealthTonic");
416 const sellerBag = addCoinsToSlots(emptySlots(), 5);
417 assert.equal(sellerBag.ok, true);
418 sellerBag.slots[1] = {
419 itemId: ItemId.potion,
420 quantity: 2,
421 instance: potionItemInstance({
422 potionKey: potion.potionKey,
423 displayName: potion.displayName,
424 color: potion.color,
425 fillLevel: potion.fillLevel,
426 effect: potion.effect,
427 effectKey: potion.effect?.type
428 })
429 };
430 harness.stateDb.saveBag(seller.character_id, {
431 inventory: sellerBag.slots,
432 equipment: emptyEquipment(),
433 vault: [],
434 vaultReserved: []
435 });
436 const buyerBag = addCoinsToSlots(emptySlots(), 100);
437 assert.equal(buyerBag.ok, true);
438 harness.stateDb.saveBag(buyer.character_id, {
439 inventory: buyerBag.slots,
440 equipment: emptyEquipment(),
441 vault: [],
442 vaultReserved: []
443 });
444
445 harness.simulation.spawnCharacter(1, seller);
446 harness.simulation.spawnCharacter(2, buyer);
447 harness.simulation.step();
448
449 harness.simulation.enqueue(1, {
450 type: "place-market-sell",
451 characterId: seller.character_id,
452 slotIndex: 1,
453 quantity: 2,
454 minUnitPrice: 8
455 });
456 const sellResult = harness.simulation.step();
457 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
458
459 harness.simulation.enqueue(2, {
460 type: "place-market-buy",
461 characterId: buyer.character_id,
462 itemId: ItemId.potion,
463 listingKey: potionListingKey("lesserHealthTonic"),
464 quantity: 2,
465 maxUnitPrice: 12
466 });
467 const buyResult = harness.simulation.step();
468 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
469 const trade = buyResult.events.find((event) => event.type === "market-trade");
470 assert.ok(trade, JSON.stringify(buyResult.events));
471 assert.equal(trade.quantity, 2);
472
473 const buyerBagNow = harness.simulation.bagOf(2);
474 const brew = (buyerBagNow.inventory ?? []).find((slot) =>
475 slot?.itemId === ItemId.potion && slot.instance?.potionKey === "lesserHealthTonic"
476 );
477 assert.ok(brew);
478 assert.equal(brew.quantity, 2);
479 }
480 finally
481 { harness.close(); }
482});
483
484test("recipe paper buy orders for a different recipe do not match", () =>
485{
486 const harness = makeSimulation({ workerCount: 1 });
487 try
488 {
489 placePlaza(harness.worldDb);
490 harness.simulation.reloadWorld();
491
492 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
493 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
494 const sellerBag = addCoinsToSlots(emptySlots(), 5);
495 assert.equal(sellerBag.ok, true);
496 sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
497 harness.stateDb.saveBag(seller.character_id, {
498 inventory: sellerBag.slots,
499 equipment: emptyEquipment(),
500 vault: [],
501 vaultReserved: []
502 });
503 const buyerBag = addCoinsToSlots(emptySlots(), 100);
504 assert.equal(buyerBag.ok, true);
505 harness.stateDb.saveBag(buyer.character_id, {
506 inventory: buyerBag.slots,
507 equipment: emptyEquipment(),
508 vault: [],
509 vaultReserved: []
510 });
511
512 harness.simulation.spawnCharacter(1, seller);
513 harness.simulation.spawnCharacter(2, buyer);
514 harness.simulation.step();
515
516 harness.simulation.enqueue(1, {
517 type: "place-market-sell",
518 characterId: seller.character_id,
519 slotIndex: 1,
520 quantity: 1,
521 minUnitPrice: 8
522 });
523 harness.simulation.step();
524
525 harness.simulation.enqueue(2, {
526 type: "place-market-buy",
527 characterId: buyer.character_id,
528 itemId: ItemId.recipePaper,
529 listingKey: recipeListingKey("clarityPotion"),
530 quantity: 1,
531 maxUnitPrice: 12
532 });
533 const buyResult = harness.simulation.step();
534 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
535 assert.equal(buyResult.events.some((event) => event.type === "market-trade"), false);
536 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(seller.character_id).length, 1);
537 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(buyer.character_id).length, 1);
538 }
539 finally
540 { harness.close(); }
541});
542
543test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
544{
545 const harness = makeSimulation({ workerCount: 1 });
546 try
547 {
548 placePlaza(harness.worldDb);
549 harness.simulation.reloadWorld();
550
551 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
552 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
553 const sellerBag = addCoinsToSlots(emptySlots(), 5);
554 assert.equal(sellerBag.ok, true);
555 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
556 harness.stateDb.saveBag(seller.character_id, {
557 inventory: sellerBag.slots,
558 equipment: emptyEquipment(),
559 vault: [],
560 vaultReserved: []
561 });
562 const buyerBag = addCoinsToSlots(emptySlots(), 100);
563 assert.equal(buyerBag.ok, true);
564 harness.stateDb.saveBag(buyer.character_id, {
565 inventory: buyerBag.slots,
566 equipment: emptyEquipment(),
567 vault: [],
568 vaultReserved: []
569 });
570
571 const sellerId = harness.simulation.spawnCharacter(1, seller);
572 const buyerId = harness.simulation.spawnCharacter(2, buyer);
573 harness.simulation.step();
574
575 harness.simulation.enqueue(1, {
576 type: "place-market-sell",
577 characterId: seller.character_id,
578 slotIndex: 1,
579 quantity: 2,
580 minUnitPrice: 8
581 });
582 const sellResult = harness.simulation.step();
583 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
584 assert.ok(sellResult.events.some((event) => event.type === "market-open"));
585
586 harness.simulation.enqueue(2, {
587 type: "place-market-buy",
588 characterId: buyer.character_id,
589 itemId: ItemId.apple,
590 quantity: 2,
591 maxUnitPrice: 12
592 });
593 const buyResult = harness.simulation.step();
594 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
595 const trade = buyResult.events.find((event) => event.type === "market-trade");
596 assert.ok(trade, JSON.stringify(buyResult.events));
597 assert.equal(trade.unitPrice, 10);
598 assert.equal(trade.quantity, 2);
599
600 const buyerBagNow = harness.simulation.bagOf(buyerId);
601 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
602
603 // Coins go to bank; letter goes to the online seller's inventory.
604 for (let i = 0; i < 500; i++)
605 {
606 harness.advance(1000);
607 harness.simulation.step();
608 const sellerVault = harness.stateDb.getBag(seller.character_id);
609 const sellerBag = harness.simulation.bagOf(sellerId);
610 const coins = countCoinsInSlots(sellerVault.vault ?? []);
611 const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
612 ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
613 if (coins >= 20 && letter)
614 {
615 assert.match(letter.instance.body, /sold|filled|proceeds/i);
616 assert.doesNotMatch(letter.instance.body, /Signed,/);
617 assert.equal(letter.instance.authorOrganization, "Central Exchange");
618 assert.ok(letter.instance.authorDisplayName);
619 assert.equal(letter.origins?.[0]?.origin?.verb, "Written");
620 assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName);
621 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
622 return;
623 }
624 }
625 assert.fail("Seller did not receive coins in vault and letter");
626 }
627 finally
628 { harness.close(); }
629});
630
631test("orders older than one month auto-cancel and return escrow to bank", () =>
632{
633 const harness = makeSimulation({ workerCount: 1 });
634 try
635 {
636 placePlaza(harness.worldDb);
637 harness.simulation.reloadWorld();
638
639 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
640 const bag = addCoinsToSlots(emptySlots(), 50);
641 assert.equal(bag.ok, true);
642 harness.stateDb.saveBag(character.character_id, {
643 inventory: bag.slots,
644 equipment: emptyEquipment(),
645 vault: [],
646 vaultReserved: []
647 });
648 harness.simulation.spawnCharacter(1, character);
649 harness.simulation.step();
650
651 harness.simulation.enqueue(1, {
652 type: "place-market-buy",
653 characterId: character.character_id,
654 itemId: ItemId.apple,
655 quantity: 1,
656 maxUnitPrice: 10
657 });
658 const placed = harness.simulation.step();
659 assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
660 const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
661 assert.equal(open.length, 1);
662
663 const order = open[0];
664 harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
665 .run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);
666
667 const expired = harness.simulation.market.step(Date.now());
668 assert.ok(expired.some((event) => event.type === "market-order-expired"));
669 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);
670
671 for (let i = 0; i < 500; i++)
672 {
673 harness.advance(1000);
674 harness.simulation.step();
675 const vault = harness.stateDb.getBag(character.character_id);
676 const bag = harness.simulation.bagOf(1);
677 const coins = countCoinsInSlots(vault.vault ?? []);
678 const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
679 ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
680 if (coins >= 10 && letter)
681 {
682 assert.match(letter.instance.body, /one month/i);
683 assert.doesNotMatch(letter.instance.body, /Signed,/);
684 assert.equal(letter.instance.authorOrganization, "Central Exchange");
685 return;
686 }
687 }
688 assert.fail("Expired order did not return escrow letter");
689 }
690 finally
691 { harness.close(); }
692});
693
694test("exchange letter instance carries Central Exchange signature fields", () =>
695{
696 const body = soldLetterBody({
697 itemName: "Apple",
698 quantity: 1,
699 unitPrice: 5,
700 clerkName: "Bobby Pennies"
701 });
702 assert.doesNotMatch(body, /Signed,/);
703 assert.doesNotMatch(body, /Bobby Pennies/);
704 assert.doesNotMatch(body, /Central Exchange/);
705 assert.match(body, /filled at 5 coins/);
706 assert.equal(
707 formatLetterSignature({
708 authorDisplayName: "Bobby Pennies",
709 authorOrganization: CENTRAL_EXCHANGE_ORG
710 }),
711 "Signed:\nBobby Pennies\nCentral Exchange"
712 );
713 assert.equal(
714 formatLetterSignature({ authorDisplayName: "The Bank" }),
715 "Signed:\nThe Bank"
716 );
717});
718
719test("written origin labels match letter author", () =>
720{
721 assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
722 assert.equal(CraftOriginVerb.written, "Written");
723});