BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

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