BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

marketplace.test.js 10.0 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 } 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("midpoint trade price rounds half units deterministically", () =>
42{
43 assert.equal(midpointTradePrice(100, 80), 90);
44 assert.equal(midpointTradePrice(101, 80), 91);
45 assert.equal(midpointTradePrice(80, 100), 90);
46});
47
48test("listing fee is 3% of notional rounded up", () =>
49{
50 assert.equal(marketOrderListingFee(100, 1), 3);
51 assert.equal(marketOrderListingFee(10, 1), 1);
52 assert.equal(marketOrderListingFee(8, 2), 1);
53 assert.equal(marketOrderListingFee(0, 5), 0);
54});
55
56test("market funds spend whole coin cheques and return change", () =>
57{
58 const slots = emptySlots();
59 slots[0] = {
60 itemId: ItemId.filledCheque,
61 quantity: 1,
62 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
63 };
64 const paid = takeMarketFunds(slots, 25);
65 assert.equal(paid.ok, true);
66 assert.equal(paid.change, 15);
67 assert.equal(paid.redeemedCheques.length, 1);
68 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
69});
70
71test("written cheque sell listing locks quantity to reserved goods", () =>
72{
73 const listing = resolveMarketSellListing({
74 itemId: ItemId.filledCheque,
75 quantity: 1,
76 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
77 });
78 assert.equal(listing.isCheque, true);
79 assert.equal(listing.itemId, ItemId.apple);
80 assert.equal(listing.quantity, 7);
81 assert.equal(listing.quantityLocked, true);
82});
83
84function placePlaza (worldDb)
85{
86 const data = createEmptyChunkData();
87 data.open = true;
88 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
89 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
90 worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
91}
92
93test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
94{
95 const harness = makeSimulation({ workerCount: 1 });
96 try
97 {
98 placePlaza(harness.worldDb);
99 harness.simulation.reloadWorld();
100
101 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
102 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
103 const sellerBag = addCoinsToSlots(emptySlots(), 5);
104 assert.equal(sellerBag.ok, true);
105 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
106 harness.stateDb.saveBag(seller.character_id, {
107 inventory: sellerBag.slots,
108 equipment: emptyEquipment(),
109 vault: [],
110 vaultReserved: []
111 });
112 const buyerBag = addCoinsToSlots(emptySlots(), 100);
113 assert.equal(buyerBag.ok, true);
114 harness.stateDb.saveBag(buyer.character_id, {
115 inventory: buyerBag.slots,
116 equipment: emptyEquipment(),
117 vault: [],
118 vaultReserved: []
119 });
120
121 const sellerId = harness.simulation.spawnCharacter(1, seller);
122 const buyerId = harness.simulation.spawnCharacter(2, buyer);
123 harness.simulation.step();
124
125 harness.simulation.enqueue(1, {
126 type: "place-market-sell",
127 characterId: seller.character_id,
128 slotIndex: 1,
129 quantity: 2,
130 minUnitPrice: 8
131 });
132 const sellResult = harness.simulation.step();
133 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
134 assert.ok(sellResult.events.some((event) => event.type === "market-open"));
135
136 harness.simulation.enqueue(2, {
137 type: "place-market-buy",
138 characterId: buyer.character_id,
139 itemId: ItemId.apple,
140 quantity: 2,
141 maxUnitPrice: 12
142 });
143 const buyResult = harness.simulation.step();
144 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
145 const trade = buyResult.events.find((event) => event.type === "market-trade");
146 assert.ok(trade, JSON.stringify(buyResult.events));
147 assert.equal(trade.unitPrice, 10);
148 assert.equal(trade.quantity, 2);
149
150 const buyerBagNow = harness.simulation.bagOf(buyerId);
151 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
152
153 // Coins go to bank; letter goes to the online seller's inventory.
154 for (let i = 0; i < 500; i++)
155 {
156 harness.advance(1000);
157 harness.simulation.step();
158 const sellerVault = harness.stateDb.getBag(seller.character_id);
159 const sellerBag = harness.simulation.bagOf(sellerId);
160 const coins = countCoinsInSlots(sellerVault.vault ?? []);
161 const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
162 ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
163 if (coins >= 20 && letter)
164 {
165 assert.match(letter.instance.body, /sold|filled|proceeds/i);
166 assert.doesNotMatch(letter.instance.body, /Signed,/);
167 assert.equal(letter.instance.authorOrganization, "Central Exchange");
168 assert.ok(letter.instance.authorDisplayName);
169 assert.equal(letter.origins?.[0]?.origin?.verb, "Written");
170 assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName);
171 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
172 return;
173 }
174 }
175 assert.fail("Seller did not receive coins in vault and letter");
176 }
177 finally
178 { harness.close(); }
179});
180
181test("orders older than one month auto-cancel and return escrow to bank", () =>
182{
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 placePlaza(harness.worldDb);
187 harness.simulation.reloadWorld();
188
189 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
190 const bag = addCoinsToSlots(emptySlots(), 50);
191 assert.equal(bag.ok, true);
192 harness.stateDb.saveBag(character.character_id, {
193 inventory: bag.slots,
194 equipment: emptyEquipment(),
195 vault: [],
196 vaultReserved: []
197 });
198 harness.simulation.spawnCharacter(1, character);
199 harness.simulation.step();
200
201 harness.simulation.enqueue(1, {
202 type: "place-market-buy",
203 characterId: character.character_id,
204 itemId: ItemId.apple,
205 quantity: 1,
206 maxUnitPrice: 10
207 });
208 const placed = harness.simulation.step();
209 assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
210 const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
211 assert.equal(open.length, 1);
212
213 const order = open[0];
214 harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
215 .run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);
216
217 const expired = harness.simulation.market.step(Date.now());
218 assert.ok(expired.some((event) => event.type === "market-order-expired"));
219 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);
220
221 for (let i = 0; i < 500; i++)
222 {
223 harness.advance(1000);
224 harness.simulation.step();
225 const vault = harness.stateDb.getBag(character.character_id);
226 const bag = harness.simulation.bagOf(1);
227 const coins = countCoinsInSlots(vault.vault ?? []);
228 const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
229 ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
230 if (coins >= 10 && letter)
231 {
232 assert.match(letter.instance.body, /one month/i);
233 assert.doesNotMatch(letter.instance.body, /Signed,/);
234 assert.equal(letter.instance.authorOrganization, "Central Exchange");
235 return;
236 }
237 }
238 assert.fail("Expired order did not return escrow letter");
239 }
240 finally
241 { harness.close(); }
242});
243
244test("exchange letter instance carries Central Exchange signature fields", () =>
245{
246 const body = soldLetterBody({
247 itemName: "Apple",
248 quantity: 1,
249 unitPrice: 5,
250 clerkName: "Bobby Pennies"
251 });
252 assert.doesNotMatch(body, /Signed,/);
253 assert.doesNotMatch(body, /Bobby Pennies/);
254 assert.doesNotMatch(body, /Central Exchange/);
255 assert.match(body, /filled at 5 coins/);
256 assert.equal(
257 formatLetterSignature({
258 authorDisplayName: "Bobby Pennies",
259 authorOrganization: CENTRAL_EXCHANGE_ORG
260 }),
261 "Signed:\nBobby Pennies\nCentral Exchange"
262 );
263 assert.equal(
264 formatLetterSignature({ authorDisplayName: "The Bank" }),
265 "Signed:\nThe Bank"
266 );
267});
268
269test("written origin labels match letter author", () =>
270{
271 assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
272 assert.equal(CraftOriginVerb.written, "Written");
273});