BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

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