BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

marketplace.test.js 13.7 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 { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
14import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
15import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
17
18test("blank cheques cannot be listed on the marketplace", () =>
19{
20 const stack = { itemId: ItemId.blankCheque, quantity: 1 };
21 assert.equal(canSellOnMarketplace(stack), false);
22 assert.throws(
23 () => assertMarketplaceSellable(stack),
24 (err) => err.message === "Blank cheques cannot be sold on the marketplace."
25 );
26});
27
28test("written cheques can be listed on the marketplace", () =>
29{
30 const stack = {
31 itemId: ItemId.filledCheque,
32 quantity: 1,
33 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
34 };
35 assert.equal(canSellOnMarketplace(stack), true);
36 assert.doesNotThrow(() => assertMarketplaceSellable(stack));
37});
38
39test("normal items are marketplace sellable by default", () =>
40{
41 assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
42});
43
44test("fully charged tinderbox can list on CE; worn cannot", () =>
45{
46 const fresh = {
47 itemId: CraftingItemId.tinderbox,
48 quantity: 1,
49 instance: tinderboxItemInstance(6)
50 };
51 const worn = {
52 itemId: CraftingItemId.tinderbox,
53 quantity: 1,
54 instance: tinderboxItemInstance(1)
55 };
56 assert.equal(canSellOnMarketplace(fresh), true);
57 assert.equal(canSellOnMarketplace(worn), false);
58 assert.throws(
59 () => assertMarketplaceSellable(worn),
60 (err) => /partially used/i.test(err.message)
61 );
62});
63
64test("full potions and dyes can list on CE; sipped or used cannot", () =>
65{
66 const fullPotion = {
67 itemId: ItemId.potion,
68 quantity: 1,
69 instance: potionItemInstance({
70 potionKey: "lesserHealthTonic",
71 displayName: "Lesser health tonic",
72 color: { r: 0.95, g: 0.38, b: 0.32 },
73 fillLevel: 4,
74 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
75 effectKey: "health-regen"
76 })
77 };
78 const sipped = {
79 ...fullPotion,
80 instance: { ...fullPotion.instance, fillLevel: 3 }
81 };
82 const fullDye = {
83 itemId: ItemId.dye,
84 quantity: 1,
85 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 4)
86 };
87 const usedDye = {
88 itemId: ItemId.dye,
89 quantity: 1,
90 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 2)
91 };
92 const unstableFull = {
93 itemId: ItemId.potion,
94 quantity: 1,
95 instance: potionItemInstance({
96 potionKey: "unstable:glow",
97 unstable: true,
98 displayName: "Unstable draught",
99 color: { r: 0.95, g: 0.9, b: 0.45 },
100 fillLevel: 3,
101 effectKey: "glow",
102 effect: { type: "glow", lightRadiusTiles: 2, durationMs: 10_000 }
103 })
104 };
105 const unstableSipped = {
106 ...unstableFull,
107 instance: { ...unstableFull.instance, fillLevel: 2 }
108 };
109 assert.equal(canSellOnMarketplace(fullPotion), true);
110 assert.equal(canSellOnMarketplace(sipped), false);
111 assert.equal(canSellOnMarketplace(fullDye), true);
112 assert.equal(canSellOnMarketplace(usedDye), false);
113 assert.equal(canSellOnMarketplace(unstableFull), true);
114 assert.equal(canSellOnMarketplace(unstableSipped), false);
115});
116
117test("letters cannot be listed on the marketplace", () =>
118{
119 const own = {
120 itemId: ItemId.letter,
121 quantity: 1,
122 instance: {
123 kind: "letter",
124 letterId: "x",
125 authorCharacterId: 1,
126 authorDisplayName: "Ada",
127 body: "Hi",
128 opened: true
129 }
130 };
131 const received = {
132 ...own,
133 instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }
134 };
135 assert.equal(canSellOnMarketplace(own, 1), false);
136 assert.equal(canSellOnMarketplace(received, 1), false);
137 assert.throws(
138 () => assertMarketplaceSellable(own, 1),
139 (err) => /letters cannot be sold on the marketplace/i.test(err.message)
140 );
141});
142
143test("midpoint trade price rounds half units deterministically", () =>
144{
145 assert.equal(midpointTradePrice(100, 80), 90);
146 assert.equal(midpointTradePrice(101, 80), 91);
147 assert.equal(midpointTradePrice(80, 100), 90);
148});
149
150test("listing fee is 3% of notional rounded up", () =>
151{
152 assert.equal(marketOrderListingFee(100, 1), 3);
153 assert.equal(marketOrderListingFee(10, 1), 1);
154 assert.equal(marketOrderListingFee(8, 2), 1);
155 assert.equal(marketOrderListingFee(0, 5), 0);
156});
157
158test("cancel and expiry letters use side-specific escrow copy", () =>
159{
160 const buyCancel = orderCancelledLetterBody({
161 side: "buy",
162 itemName: "Flower",
163 quantity: 1,
164 escrowLabel: "coins",
165 clerkName: "Ada Ledger"
166 });
167 assert.match(buyCancel, /buy order for 1× Flower was cancelled/);
168 assert.match(buyCancel, /coins have been returned/);
169 assert.doesNotMatch(buyCancel, /coins has been returned/);
170
171 const sellCancel = orderCancelledLetterBody({
172 side: "sell",
173 itemName: "Apple",
174 quantity: 2,
175 escrowLabel: "Apple",
176 clerkName: "Ada Ledger"
177 });
178 assert.match(sellCancel, /sell order for 2× Apple was cancelled/);
179 assert.match(sellCancel, /listed goods have been returned/);
180
181 const buyExpired = orderExpiredLetterBody({
182 side: "buy",
183 itemName: "Flower",
184 quantity: 1,
185 escrowLabel: "coins",
186 clerkName: "Ada Ledger"
187 });
188 assert.match(buyExpired, /coins have been returned/);
189});
190
191test("market funds spend whole coin cheques and return change", () =>
192{
193 const slots = emptySlots();
194 slots[0] = {
195 itemId: ItemId.filledCheque,
196 quantity: 1,
197 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
198 };
199 const paid = takeMarketFunds(slots, 25);
200 assert.equal(paid.ok, true);
201 assert.equal(paid.change, 15);
202 assert.equal(paid.redeemedCheques.length, 1);
203 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
204});
205
206test("written cheque sell listing locks quantity to reserved goods", () =>
207{
208 const listing = resolveMarketSellListing({
209 itemId: ItemId.filledCheque,
210 quantity: 1,
211 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
212 });
213 assert.equal(listing.isCheque, true);
214 assert.equal(listing.itemId, ItemId.apple);
215 assert.equal(listing.quantity, 7);
216 assert.equal(listing.quantityLocked, true);
217});
218
219function placePlaza (worldDb)
220{
221 const data = createEmptyChunkData();
222 data.open = true;
223 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
224 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
225 worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
226}
227
228test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
229{
230 const harness = makeSimulation({ workerCount: 1 });
231 try
232 {
233 placePlaza(harness.worldDb);
234 harness.simulation.reloadWorld();
235
236 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
237 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
238 const sellerBag = addCoinsToSlots(emptySlots(), 5);
239 assert.equal(sellerBag.ok, true);
240 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
241 harness.stateDb.saveBag(seller.character_id, {
242 inventory: sellerBag.slots,
243 equipment: emptyEquipment(),
244 vault: [],
245 vaultReserved: []
246 });
247 const buyerBag = addCoinsToSlots(emptySlots(), 100);
248 assert.equal(buyerBag.ok, true);
249 harness.stateDb.saveBag(buyer.character_id, {
250 inventory: buyerBag.slots,
251 equipment: emptyEquipment(),
252 vault: [],
253 vaultReserved: []
254 });
255
256 const sellerId = harness.simulation.spawnCharacter(1, seller);
257 const buyerId = harness.simulation.spawnCharacter(2, buyer);
258 harness.simulation.step();
259
260 harness.simulation.enqueue(1, {
261 type: "place-market-sell",
262 characterId: seller.character_id,
263 slotIndex: 1,
264 quantity: 2,
265 minUnitPrice: 8
266 });
267 const sellResult = harness.simulation.step();
268 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
269 assert.ok(sellResult.events.some((event) => event.type === "market-open"));
270
271 harness.simulation.enqueue(2, {
272 type: "place-market-buy",
273 characterId: buyer.character_id,
274 itemId: ItemId.apple,
275 quantity: 2,
276 maxUnitPrice: 12
277 });
278 const buyResult = harness.simulation.step();
279 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
280 const trade = buyResult.events.find((event) => event.type === "market-trade");
281 assert.ok(trade, JSON.stringify(buyResult.events));
282 assert.equal(trade.unitPrice, 10);
283 assert.equal(trade.quantity, 2);
284
285 const buyerBagNow = harness.simulation.bagOf(buyerId);
286 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
287
288 // Coins go to bank; letter goes to the online seller's inventory.
289 for (let i = 0; i < 500; i++)
290 {
291 harness.advance(1000);
292 harness.simulation.step();
293 const sellerVault = harness.stateDb.getBag(seller.character_id);
294 const sellerBag = harness.simulation.bagOf(sellerId);
295 const coins = countCoinsInSlots(sellerVault.vault ?? []);
296 const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
297 ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
298 if (coins >= 20 && letter)
299 {
300 assert.match(letter.instance.body, /sold|filled|proceeds/i);
301 assert.doesNotMatch(letter.instance.body, /Signed,/);
302 assert.equal(letter.instance.authorOrganization, "Central Exchange");
303 assert.ok(letter.instance.authorDisplayName);
304 assert.equal(letter.origins?.[0]?.origin?.verb, "Written");
305 assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName);
306 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
307 return;
308 }
309 }
310 assert.fail("Seller did not receive coins in vault and letter");
311 }
312 finally
313 { harness.close(); }
314});
315
316test("orders older than one month auto-cancel and return escrow to bank", () =>
317{
318 const harness = makeSimulation({ workerCount: 1 });
319 try
320 {
321 placePlaza(harness.worldDb);
322 harness.simulation.reloadWorld();
323
324 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
325 const bag = addCoinsToSlots(emptySlots(), 50);
326 assert.equal(bag.ok, true);
327 harness.stateDb.saveBag(character.character_id, {
328 inventory: bag.slots,
329 equipment: emptyEquipment(),
330 vault: [],
331 vaultReserved: []
332 });
333 harness.simulation.spawnCharacter(1, character);
334 harness.simulation.step();
335
336 harness.simulation.enqueue(1, {
337 type: "place-market-buy",
338 characterId: character.character_id,
339 itemId: ItemId.apple,
340 quantity: 1,
341 maxUnitPrice: 10
342 });
343 const placed = harness.simulation.step();
344 assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
345 const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
346 assert.equal(open.length, 1);
347
348 const order = open[0];
349 harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
350 .run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);
351
352 const expired = harness.simulation.market.step(Date.now());
353 assert.ok(expired.some((event) => event.type === "market-order-expired"));
354 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);
355
356 for (let i = 0; i < 500; i++)
357 {
358 harness.advance(1000);
359 harness.simulation.step();
360 const vault = harness.stateDb.getBag(character.character_id);
361 const bag = harness.simulation.bagOf(1);
362 const coins = countCoinsInSlots(vault.vault ?? []);
363 const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
364 ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
365 if (coins >= 10 && letter)
366 {
367 assert.match(letter.instance.body, /one month/i);
368 assert.doesNotMatch(letter.instance.body, /Signed,/);
369 assert.equal(letter.instance.authorOrganization, "Central Exchange");
370 return;
371 }
372 }
373 assert.fail("Expired order did not return escrow letter");
374 }
375 finally
376 { harness.close(); }
377});
378
379test("exchange letter instance carries Central Exchange signature fields", () =>
380{
381 const body = soldLetterBody({
382 itemName: "Apple",
383 quantity: 1,
384 unitPrice: 5,
385 clerkName: "Bobby Pennies"
386 });
387 assert.doesNotMatch(body, /Signed,/);
388 assert.doesNotMatch(body, /Bobby Pennies/);
389 assert.doesNotMatch(body, /Central Exchange/);
390 assert.match(body, /filled at 5 coins/);
391 assert.equal(
392 formatLetterSignature({
393 authorDisplayName: "Bobby Pennies",
394 authorOrganization: CENTRAL_EXCHANGE_ORG
395 }),
396 "Signed:\nBobby Pennies\nCentral Exchange"
397 );
398 assert.equal(
399 formatLetterSignature({ authorDisplayName: "The Bank" }),
400 "Signed:\nThe Bank"
401 );
402});
403
404test("written origin labels match letter author", () =>
405{
406 assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
407 assert.equal(CraftOriginVerb.written, "Written");
408});