BlueGit

timfa questward

Files

questward / server / tests / shop.test.js

shop.test.js

shop.test.js 42.5 KiB Download Raw
1import test from "node:test";
2import assert from "node:assert/strict";
3import
4 {
5 shopUnitPrice,
6 undiscountedMarketValue,
7 undiscountedMarketCoins,
8 marketValueAsCoins,
9 canSellInNpcShop,
10 canPlayerSellToNpc,
11 shopBuyFromPlayerPrice,
12 shopBoughtResalePrice,
13 shopChequeAdminFee,
14 resolveShopSellQuote,
15 shopRestockDayKey,
16 lerp
17 } from "../../shared/shop/pricing.js";
18import { ItemId, listAllItemPickerEntries } from "../../shared/definitions/items.js";
19import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
20import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
21import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
22import { Component } from "../src/ecs/components.js";
23import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
24import { ItemOriginKind } from "../../shared/items/origin.js";
25import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
26import { ensureShopRestocked, boughtStockKey } from "../src/shop/service.js";
27import { BlockType } from "../../shared/definitions/tiles.js";
28import { GatherOriginVerb, gatherOrigin } from "../../shared/items/origin.js";
29import { dyeItemInstance, DEFAULT_DYE_FILL, FlowerColorId } from "../../shared/definitions/dyes.js";
30
31function boughtQty (shop, itemId)
32{
33 const raw = shop?.boughtStock?.[itemId];
34 if (raw == null)
35 { return 0; }
36 if (typeof raw === "number")
37 { return raw | 0; }
38 return raw.quantity | 0 || 0;
39}
40
41test("listAllItemPickerEntries includes paper and bronze gather tools", () =>
42{
43 const ids = new Set(listAllItemPickerEntries().map((entry) => entry.itemId));
44 assert.ok(ids.has(ItemId.paper));
45 assert.ok(ids.has(CraftingItemId.bronzeAxe));
46 assert.ok(ids.has(CraftingItemId.bronzePickaxe));
47 assert.equal(canSellInNpcShop(ItemId.paper), false);
48 assert.equal(canSellInNpcShop(CraftingItemId.bronzeAxe), false);
49});
50
51test("buy paper from a shopkeeper with explicit catalog", () =>
52{
53 const harness = makeSimulation({ workerCount: 1 });
54 try
55 {
56 const data = createEmptyChunkData();
57 data.open = true;
58 data.spawners = [{
59 localX: 9,
60 localY: 8,
61 config: {
62 mobTypeId: MobId.humanoid,
63 maxAlive: 1,
64 spawnRangeTiles: 1,
65 maxWanderRangeTiles: 1,
66 sex: "male",
67 displayName: "Stationer",
68 sells: [{ itemId: ItemId.paper, quantity: 0 }],
69 hiddenDiscount: 1,
70 equipment: { chest: ItemId.clothShirt }
71 }
72 }];
73 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
74 harness.simulation.reloadWorld();
75
76 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
77 const funded = addCoinsToSlots(emptySlots(), 20);
78 assert.equal(funded.ok, true);
79 harness.stateDb.saveBag(character.character_id, {
80 inventory: funded.slots,
81 equipment: emptyEquipment(),
82 vault: [],
83 vaultReserved: []
84 });
85 const playerId = harness.simulation.spawnCharacter(1, character);
86 harness.simulation.step();
87 harness.advance(50);
88 harness.simulation.step();
89
90 const record = harness.simulation.entityRecord(playerId);
91 const worker = harness.simulation.workers[record.workerId];
92 let npcId = null;
93 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
94 {
95 if (entity.creature.mobTypeId === MobId.humanoid)
96 {
97 npcId = entity.entityId;
98 break;
99 }
100 }
101 assert.ok(npcId, "expected a humanoid shopkeeper");
102
103 const npcHandle = worker.world.ecs.handleOf(npcId);
104 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
105 const playerHandle = worker.world.ecs.handleOf(playerId);
106 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
107 playerPos.tileX = npcPos.tileX;
108 playerPos.tileY = npcPos.tileY;
109
110 harness.simulation.enqueue(1, {
111 type: "interact",
112 characterId: character.character_id,
113 targetEntityId: npcId
114 });
115 const open = harness.simulation.step();
116 const shopOpen = open.events.find((event) => event.type === "shop-open");
117 assert.ok(shopOpen, JSON.stringify(open.events));
118 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.paper));
119
120 harness.simulation.enqueue(1, {
121 type: "buy-from-shop",
122 characterId: character.character_id,
123 npcEntityId: npcId,
124 itemId: ItemId.paper,
125 quantity: 1,
126 listingId: `stock:${ItemId.paper}`
127 });
128 const buy = harness.simulation.step();
129 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
130 const bag = harness.simulation.bagOf(playerId);
131 const paper = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.paper);
132 assert.ok(paper, JSON.stringify(bag.inventory));
133 }
134 finally
135 { harness.close(); }
136});
137
138test("shop prices fall back to seedValue and apply hidden discount", () =>
139{
140 assert.equal(undiscountedMarketValue(ItemId.copperOre), 5);
141 assert.equal(undiscountedMarketValue(ItemId.tinOre), 5);
142 assert.equal(undiscountedMarketValue(ItemId.pineLog), 5);
143 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 5);
144 assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 3);
145 assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre), 3);
146 assert.equal(shopBoughtResalePrice(ItemId.copperOre), 6);
147 assert.equal(lerp(10, 20, 0.5), 15);
148 assert.equal(canSellInNpcShop(ItemId.copperOre), true);
149 assert.equal(canSellInNpcShop(ItemId.tinOre), true);
150 assert.equal(canSellInNpcShop(ItemId.stick), false);
151 assert.equal(canPlayerSellToNpc({ itemId: ItemId.copperOre, quantity: 1 }), true);
152 assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);
153 assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);
154 assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);
155 assert.equal(canPlayerSellToNpc({
156 itemId: ItemId.recipePaper,
157 quantity: 1,
158 instance: { kind: "recipe-paper", recipeId: "lesser-health-tonic" }
159 }), false);
160 assert.equal(canPlayerSellToNpc({
161 itemId: ItemId.filledCheque,
162 quantity: 1,
163 instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 3 }
164 }), true);
165 assert.equal(shopChequeAdminFee(100), 5);
166 assert.equal(shopChequeAdminFee(10), 1);
167 assert.equal(shopChequeAdminFee(1), 1);
168 const chequeQuote = resolveShopSellQuote({
169 itemId: ItemId.filledCheque,
170 quantity: 1,
171 instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 2 }
172 });
173 assert.equal(chequeQuote.baseTotal, shopBuyFromPlayerPrice(ItemId.copperOre) * 2);
174 assert.equal(chequeQuote.adminFee, shopChequeAdminFee(chequeQuote.baseTotal));
175 assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);
176});
177
178test("charge-worn tools scale merchant buy and resale prices by remaining uses", () =>
179{
180 const full = {
181 itemId: CraftingItemId.tinderbox,
182 quantity: 1,
183 instance: tinderboxItemInstance(6)
184 };
185 const worn = {
186 itemId: CraftingItemId.tinderbox,
187 quantity: 1,
188 instance: tinderboxItemInstance(1)
189 };
190 const fullBuy = shopBuyFromPlayerPrice(CraftingItemId.tinderbox, { stack: full });
191 const wornBuy = shopBuyFromPlayerPrice(CraftingItemId.tinderbox, { stack: worn });
192 assert.equal(fullBuy, shopBuyFromPlayerPrice(CraftingItemId.tinderbox));
193 assert.equal(wornBuy, marketValueAsCoins(
194 undiscountedMarketValue(CraftingItemId.tinderbox) * 0.5 * (1 / 6)
195 ));
196 const fullResale = shopBoughtResalePrice(CraftingItemId.tinderbox, { stack: full });
197 const wornResale = shopBoughtResalePrice(CraftingItemId.tinderbox, { stack: worn });
198 assert.equal(fullResale, shopBoughtResalePrice(CraftingItemId.tinderbox));
199 assert.equal(wornResale, marketValueAsCoins(
200 undiscountedMarketValue(CraftingItemId.tinderbox) * 1.2 * (1 / 6)
201 ));
202 const quote = resolveShopSellQuote(worn);
203 assert.equal(quote.unitPrice, wornBuy);
204});
205
206test("market value display and shop use ceil fractional lerps", () =>
207{
208 const now = 1_000_000;
209 const lastSale = {
210 lastTradePrice: 10,
211 lastTradeAt: now - 500,
212 priceFrom: 5
213 };
214 // Halfway from 5 → 10 over 1000ms → 7.5 internally.
215 const raw = undiscountedMarketValue(ItemId.copperOre, lastSale, now, 1000);
216 assert.equal(raw, 7.5);
217 assert.equal(marketValueAsCoins(raw), 8);
218 assert.equal(undiscountedMarketCoins(ItemId.copperOre, lastSale, now, 1000), 8);
219 assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 4);
220 assert.equal(shopBoughtResalePrice(ItemId.copperOre, { lastSale, now, lerpDurationMs: 1000 }), 9);
221 assert.equal(shopUnitPrice(ItemId.copperOre, {
222 lastSale,
223 now,
224 lerpDurationMs: 1000,
225 hiddenDiscount: 1
226 }), 8);
227});
228
229test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>
230{
231 assert.equal(isHumanoidMob(MobId.humanoid), true);
232 const config = normalizeSpawnerConfig({
233 mobTypeId: MobId.humanoid,
234 sex: "female",
235 displayName: "Ore trader",
236 equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },
237 sells: [
238 { itemId: ItemId.copperOre, quantity: 10 },
239 { itemId: ItemId.tinOre, quantity: 0 },
240 ItemId.copperOre
241 ],
242 buysItems: true,
243 hiddenDiscount: 0.85
244 }, "shop-1");
245 assert.equal(config.sex, "female");
246 assert.equal(config.displayName, "Ore trader");
247 assert.equal(config.equipment.chest, ItemId.clothShirt);
248 assert.deepEqual(config.sells, [
249 { itemId: ItemId.copperOre, quantity: 10 },
250 { itemId: ItemId.tinOre, quantity: 0 }
251 ]);
252 assert.equal(config.buysItems, true);
253 assert.equal(config.hiddenDiscount, 0.85);
254 assert.equal(config.maxAlive, 1);
255});
256
257test("shopkeeper with buysItems accepts paper from the player", () =>
258{
259 const harness = makeSimulation({ workerCount: 1 });
260 try
261 {
262 const data = createEmptyChunkData();
263 data.open = true;
264 data.spawners = [{
265 localX: 9,
266 localY: 8,
267 config: {
268 mobTypeId: MobId.humanoid,
269 maxAlive: 1,
270 spawnRangeTiles: 0,
271 maxWanderRangeTiles: 0,
272 displayName: "Stationer",
273 buysItems: true
274 }
275 }];
276 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
277 harness.simulation.reloadWorld();
278
279 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
280 const slots = emptySlots(INVENTORY_SLOTS);
281 slots[0] = { itemId: ItemId.paper, quantity: 3 };
282 harness.stateDb.saveBag(character.character_id, {
283 inventory: slots,
284 equipment: emptyEquipment(),
285 vault: [],
286 vaultReserved: []
287 });
288 const playerId = harness.simulation.spawnCharacter(1, character);
289 harness.simulation.step();
290 harness.advance(50);
291 harness.simulation.step();
292
293 const record = harness.simulation.entityRecord(playerId);
294 const worker = harness.simulation.workers[record.workerId];
295 let npcId = null;
296 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
297 {
298 if (entity.creature.mobTypeId === MobId.humanoid)
299 {
300 npcId = entity.entityId;
301 break;
302 }
303 }
304 assert.ok(npcId);
305 const npcHandle = worker.world.ecs.handleOf(npcId);
306 const shop = worker.world.ecs.get(npcHandle, Component.shop);
307 assert.equal(shop.buysItems, true);
308 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
309 const playerHandle = worker.world.ecs.handleOf(playerId);
310 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
311 playerPos.tileX = npcPos.tileX;
312 playerPos.tileY = npcPos.tileY;
313
314 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
315 harness.simulation.enqueue(1, {
316 type: "sell-to-shop",
317 characterId: character.character_id,
318 npcEntityId: npcId,
319 slotIndex: 0,
320 quantity: 1
321 });
322 const sold = harness.simulation.step();
323 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
324 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
325 assert.equal(inv.slots[0]?.quantity, 2);
326 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.paper));
327 }
328 finally
329 { harness.close(); }
330});
331
332test("humanoid spawner equipment can store clothing dye color", () =>
333{
334 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
335 const config = normalizeSpawnerConfig({
336 mobTypeId: MobId.humanoid,
337 equipment: {
338 chest: { itemId: ItemId.clothShirt, dyeColor },
339 weapon: ItemId.stick
340 }
341 }, "shop-dye");
342 assert.deepEqual(config.equipment.chest, {
343 itemId: ItemId.clothShirt,
344 dyeColor
345 });
346 assert.equal(config.equipment.weapon, ItemId.stick);
347});
348
349test("buy copper ore from a spawned shopkeeper", () =>
350{
351 const harness = makeSimulation({ workerCount: 1 });
352 try
353 {
354 const data = createEmptyChunkData();
355 data.open = true;
356 data.spawners = [{
357 localX: 9,
358 localY: 8,
359 config: {
360 mobTypeId: MobId.humanoid,
361 maxAlive: 1,
362 spawnRangeTiles: 1,
363 maxWanderRangeTiles: 1,
364 sex: "male",
365 displayName: "Ore trader",
366 sells: [
367 { itemId: ItemId.copperOre, quantity: 0 },
368 { itemId: ItemId.tinOre, quantity: 0 }
369 ],
370 hiddenDiscount: 1,
371 equipment: { chest: ItemId.clothShirt }
372 }
373 }];
374 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
375 harness.simulation.reloadWorld();
376
377 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
378 const funded = addCoinsToSlots(emptySlots(), 50);
379 assert.equal(funded.ok, true);
380 harness.stateDb.saveBag(character.character_id, {
381 inventory: funded.slots,
382 equipment: emptyEquipment(),
383 vault: [],
384 vaultReserved: []
385 });
386 const playerId = harness.simulation.spawnCharacter(1, character);
387 harness.simulation.step();
388 harness.advance(50);
389 harness.simulation.step();
390
391 const record = harness.simulation.entityRecord(playerId);
392 const worker = harness.simulation.workers[record.workerId];
393 let npcId = null;
394 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
395 {
396 if (entity.creature.mobTypeId === MobId.humanoid)
397 {
398 npcId = entity.entityId;
399 break;
400 }
401 }
402 assert.ok(npcId, "expected a humanoid shopkeeper");
403
404 const npcHandle = worker.world.ecs.handleOf(npcId);
405 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
406 const playerHandle = worker.world.ecs.handleOf(playerId);
407 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
408 playerPos.tileX = npcPos.tileX;
409 playerPos.tileY = npcPos.tileY;
410
411 harness.simulation.enqueue(1, {
412 type: "interact",
413 characterId: character.character_id,
414 targetEntityId: npcId
415 });
416 const open = harness.simulation.step();
417 const shopOpen = open.events.find((event) => event.type === "shop-open");
418 assert.ok(shopOpen, JSON.stringify(open.events));
419 assert.ok(shopOpen.stock.some((row) => row.itemId === ItemId.copperOre));
420
421 harness.simulation.enqueue(1, {
422 type: "buy-from-shop",
423 characterId: character.character_id,
424 npcEntityId: npcId,
425 itemId: ItemId.copperOre,
426 quantity: 1,
427 listingId: `stock:${ItemId.copperOre}`
428 });
429 const buy = harness.simulation.step();
430 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
431 const bag = harness.simulation.bagOf(playerId);
432 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
433 assert.ok(ore, JSON.stringify(bag.inventory));
434 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.shop);
435 assert.equal(ore.origins?.[0]?.origin?.displayName, "Ore trader");
436 }
437 finally
438 { harness.close(); }
439});
440
441test("limited shop stock depletes and restocks on a new day", () =>
442{
443 const shop = {
444 catalog: [{ itemId: ItemId.copperOre, quantity: 2 }],
445 buysItems: false,
446 hiddenDiscount: 1,
447 remaining: Object.create(null),
448 boughtStock: Object.create(null),
449 restockDay: null
450 };
451 const dayA = new Date(2026, 7, 25, 12, 0, 0, 0).getTime();
452 ensureShopRestocked(shop, dayA);
453 assert.equal(shop.restockDay, shopRestockDayKey(dayA));
454 assert.equal(shop.remaining[ItemId.copperOre], 2);
455 shop.remaining[ItemId.copperOre] = 0;
456 shop.boughtStock[ItemId.tinOre] = 3;
457 ensureShopRestocked(shop, dayA);
458 assert.equal(shop.remaining[ItemId.copperOre], 0);
459 assert.equal(shop.boughtStock[ItemId.tinOre], 3);
460 const dayB = new Date(2026, 7, 26, 0, 0, 1, 0).getTime();
461 ensureShopRestocked(shop, dayB);
462 assert.equal(shop.remaining[ItemId.copperOre], 2);
463 assert.equal(shop.boughtStock[ItemId.tinOre], undefined);
464});
465
466test("shop overflow goes to bank vault when inventory is full", () =>
467{
468 const harness = makeSimulation({ workerCount: 1 });
469 try
470 {
471 const data = createEmptyChunkData();
472 data.open = true;
473 data.spawners = [{
474 localX: 9,
475 localY: 8,
476 config: {
477 mobTypeId: MobId.humanoid,
478 maxAlive: 1,
479 spawnRangeTiles: 0,
480 maxWanderRangeTiles: 0,
481 displayName: "Ore trader",
482 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
483 hiddenDiscount: 1
484 }
485 }];
486 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
487 harness.simulation.reloadWorld();
488
489 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
490 const slots = emptySlots();
491 const funded = addCoinsToSlots(slots, 50);
492 assert.equal(funded.ok, true);
493 for (let i = 0; i < funded.slots.length; i++)
494 {
495 if (!funded.slots[i])
496 { funded.slots[i] = { itemId: ItemId.stick, quantity: 1 }; }
497 }
498 harness.stateDb.saveBag(character.character_id, {
499 inventory: funded.slots,
500 equipment: emptyEquipment(),
501 vault: [],
502 vaultReserved: []
503 });
504 const playerId = harness.simulation.spawnCharacter(1, character);
505 harness.simulation.step();
506 harness.advance(50);
507 harness.simulation.step();
508
509 const record = harness.simulation.entityRecord(playerId);
510 const worker = harness.simulation.workers[record.workerId];
511 let npcId = null;
512 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
513 {
514 if (entity.creature.mobTypeId === MobId.humanoid)
515 {
516 npcId = entity.entityId;
517 break;
518 }
519 }
520 assert.ok(npcId);
521 const npcHandle = worker.world.ecs.handleOf(npcId);
522 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
523 const playerHandle = worker.world.ecs.handleOf(playerId);
524 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
525 playerPos.tileX = npcPos.tileX;
526 playerPos.tileY = npcPos.tileY;
527
528 harness.simulation.enqueue(1, {
529 type: "buy-from-shop",
530 characterId: character.character_id,
531 npcEntityId: npcId,
532 itemId: ItemId.copperOre,
533 quantity: 1,
534 listingId: `stock:${ItemId.copperOre}`
535 });
536 const buy = harness.simulation.step();
537 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
538 const bag = harness.simulation.bagOf(playerId);
539 assert.equal((bag.inventory ?? []).some((slot) => slot?.itemId === ItemId.copperOre), false);
540 assert.ok((bag.vault ?? []).some((slot) => slot?.itemId === ItemId.copperOre));
541 }
542 finally
543 { harness.close(); }
544});
545
546test("buysItems refills limited catalog then stores extras for 120% resale", () =>
547{
548 const harness = makeSimulation({ workerCount: 1 });
549 try
550 {
551 const data = createEmptyChunkData();
552 data.open = true;
553 data.spawners = [{
554 localX: 9,
555 localY: 8,
556 config: {
557 mobTypeId: MobId.humanoid,
558 maxAlive: 1,
559 spawnRangeTiles: 0,
560 maxWanderRangeTiles: 0,
561 displayName: "Buyer",
562 sells: [{ itemId: ItemId.copperOre, quantity: 2 }],
563 buysItems: true,
564 hiddenDiscount: 1
565 }
566 }];
567 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
568 harness.simulation.reloadWorld();
569
570 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
571 harness.stateDb.saveBag(character.character_id, {
572 inventory: emptySlots(INVENTORY_SLOTS),
573 equipment: emptyEquipment(),
574 vault: [],
575 vaultReserved: []
576 });
577 const playerId = harness.simulation.spawnCharacter(1, character);
578 harness.simulation.step();
579 harness.advance(50);
580 harness.simulation.step();
581
582 const record = harness.simulation.entityRecord(playerId);
583 const worker = harness.simulation.workers[record.workerId];
584 let npcId = null;
585 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
586 {
587 if (entity.creature.mobTypeId === MobId.humanoid)
588 {
589 npcId = entity.entityId;
590 break;
591 }
592 }
593 assert.ok(npcId);
594 const npcHandle = worker.world.ecs.handleOf(npcId);
595 const shop = worker.world.ecs.get(npcHandle, Component.shop);
596 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
597 const playerHandle = worker.world.ecs.handleOf(playerId);
598 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
599 playerPos.tileX = npcPos.tileX;
600 playerPos.tileY = npcPos.tileY;
601
602 // Fund coins and buy out limited stock first.
603 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
604 const funded = addCoinsToSlots(inv.slots, 50);
605 assert.equal(funded.ok, true);
606 inv.slots = funded.slots;
607 inv.slots[1] = { itemId: ItemId.copperOre, quantity: 5 };
608
609 harness.simulation.enqueue(1, {
610 type: "buy-from-shop",
611 characterId: character.character_id,
612 npcEntityId: npcId,
613 itemId: ItemId.copperOre,
614 quantity: 2,
615 listingId: `stock:${ItemId.copperOre}`
616 });
617 const boughtOut = harness.simulation.step();
618 assert.equal(boughtOut.events.some((event) => event.type === "command-error"), false, JSON.stringify(boughtOut.events));
619 assert.equal(shop.remaining[ItemId.copperOre], 0);
620
621 const oreSlot = inv.slots.findIndex((slot) => slot?.itemId === ItemId.copperOre && (slot.quantity | 0) >= 5);
622 assert.ok(oreSlot >= 0);
623
624 harness.simulation.enqueue(1, {
625 type: "sell-to-shop",
626 characterId: character.character_id,
627 npcEntityId: npcId,
628 slotIndex: oreSlot,
629 quantity: 5
630 });
631 const sold = harness.simulation.step();
632 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
633 assert.equal(shop.remaining[ItemId.copperOre], 2);
634 assert.equal(boughtQty(shop, ItemId.copperOre), 3);
635
636 const open = sold.events.find((event) => event.type === "shop-open");
637 assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));
638 assert.ok(open.stock.some((row) => row.source === "bought" && row.available === 3));
639 }
640 finally
641 { harness.close(); }
642});
643
644test("shop adjacency errors use gendered pronouns", () =>
645{
646 const harness = makeSimulation({ workerCount: 1 });
647 try
648 {
649 const data = createEmptyChunkData();
650 data.open = true;
651 data.spawners = [{
652 localX: 9,
653 localY: 8,
654 config: {
655 mobTypeId: MobId.humanoid,
656 maxAlive: 1,
657 spawnRangeTiles: 0,
658 maxWanderRangeTiles: 0,
659 sex: "female",
660 displayName: "Trader",
661 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
662 hiddenDiscount: 1
663 }
664 }];
665 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
666 harness.simulation.reloadWorld();
667
668 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
669 harness.stateDb.saveBag(character.character_id, {
670 inventory: emptySlots(INVENTORY_SLOTS),
671 equipment: emptyEquipment(),
672 vault: [],
673 vaultReserved: []
674 });
675 const playerId = harness.simulation.spawnCharacter(1, character);
676 harness.simulation.step();
677 harness.advance(50);
678 harness.simulation.step();
679
680 const record = harness.simulation.entityRecord(playerId);
681 const worker = harness.simulation.workers[record.workerId];
682 let npcId = null;
683 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
684 {
685 if (entity.creature.mobTypeId === MobId.humanoid)
686 {
687 npcId = entity.entityId;
688 break;
689 }
690 }
691 assert.ok(npcId);
692
693 harness.simulation.enqueue(1, {
694 type: "interact",
695 characterId: character.character_id,
696 targetEntityId: npcId
697 });
698 const open = harness.simulation.step();
699 const err = open.events.find((event) => event.type === "command-error");
700 assert.ok(err, JSON.stringify(open.events));
701 assert.match(err.message, /stand next to her/i);
702 assert.doesNotMatch(err.message, /\bthem\b/i);
703 }
704 finally
705 { harness.close(); }
706});
707
708test("shopkeeper stops wandering while a player has the shop open", () =>
709{
710 const harness = makeSimulation({ workerCount: 1 });
711 try
712 {
713 const data = createEmptyChunkData();
714 data.open = true;
715 data.spawners = [{
716 localX: 8,
717 localY: 8,
718 config: {
719 mobTypeId: MobId.humanoid,
720 maxAlive: 1,
721 spawnRangeTiles: 4,
722 maxWanderRangeTiles: 8,
723 sex: "male",
724 displayName: "Stay put",
725 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
726 hiddenDiscount: 1
727 }
728 }];
729 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
730 harness.simulation.reloadWorld();
731
732 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
733 harness.stateDb.saveBag(character.character_id, {
734 inventory: emptySlots(INVENTORY_SLOTS),
735 equipment: emptyEquipment(),
736 vault: [],
737 vaultReserved: []
738 });
739 const playerId = harness.simulation.spawnCharacter(1, character);
740 harness.simulation.step();
741 harness.advance(50);
742 harness.simulation.step();
743
744 const record = harness.simulation.entityRecord(playerId);
745 const worker = harness.simulation.workers[record.workerId];
746 let npc = null;
747 for (const entity of worker.world.ecs.query(Component.shop, Component.creature, Component.position, Component.path))
748 {
749 if (entity.creature.mobTypeId === MobId.humanoid)
750 {
751 npc = entity;
752 break;
753 }
754 }
755 assert.ok(npc);
756
757 const playerHandle = worker.world.ecs.handleOf(playerId);
758 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
759 playerPos.tileX = npc.position.tileX;
760 playerPos.tileY = npc.position.tileY;
761
762 harness.simulation.enqueue(1, {
763 type: "interact",
764 characterId: character.character_id,
765 targetEntityId: npc.entityId
766 });
767 const open = harness.simulation.step();
768 assert.ok(open.events.some((event) => event.type === "shop-open"));
769 assert.equal(!!npc.shop.browsers?.[character.character_id], true);
770
771 npc.path.tiles = [{ x: npc.position.tileX + 1, y: npc.position.tileY }];
772 for (let i = 0; i < 20; i++)
773 { harness.simulation.step(); }
774 assert.equal(npc.path.tiles.length, 0);
775 assert.equal(npc.position.tileX, playerPos.tileX);
776 assert.equal(npc.position.tileY, playerPos.tileY);
777
778 harness.simulation.enqueue(1, {
779 type: "close-shop",
780 characterId: character.character_id,
781 npcEntityId: npc.entityId
782 });
783 harness.simulation.step();
784 assert.equal(!!npc.shop.browsers?.[character.character_id], false);
785 }
786 finally
787 { harness.close(); }
788});
789
790test("buysItems accepts non-ingredient tools like sticks", () =>
791{
792 const harness = makeSimulation({ workerCount: 1 });
793 try
794 {
795 const data = createEmptyChunkData();
796 data.open = true;
797 data.spawners = [{
798 localX: 9,
799 localY: 8,
800 config: {
801 mobTypeId: MobId.humanoid,
802 maxAlive: 1,
803 spawnRangeTiles: 0,
804 maxWanderRangeTiles: 0,
805 displayName: "Buyer",
806 buysItems: true,
807 hiddenDiscount: 1
808 }
809 }];
810 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
811 harness.simulation.reloadWorld();
812
813 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
814 const slots = emptySlots(INVENTORY_SLOTS);
815 slots[0] = { itemId: ItemId.stick, quantity: 1 };
816 harness.stateDb.saveBag(character.character_id, {
817 inventory: slots,
818 equipment: emptyEquipment(),
819 vault: [],
820 vaultReserved: []
821 });
822 const playerId = harness.simulation.spawnCharacter(1, character);
823 harness.simulation.step();
824 harness.advance(50);
825 harness.simulation.step();
826
827 const record = harness.simulation.entityRecord(playerId);
828 const worker = harness.simulation.workers[record.workerId];
829 let npcId = null;
830 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
831 {
832 if (entity.creature.mobTypeId === MobId.humanoid)
833 {
834 npcId = entity.entityId;
835 break;
836 }
837 }
838 assert.ok(npcId);
839 const npcHandle = worker.world.ecs.handleOf(npcId);
840 const shop = worker.world.ecs.get(npcHandle, Component.shop);
841 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
842 const playerHandle = worker.world.ecs.handleOf(playerId);
843 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
844 playerPos.tileX = npcPos.tileX;
845 playerPos.tileY = npcPos.tileY;
846
847 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
848 harness.simulation.enqueue(1, {
849 type: "sell-to-shop",
850 characterId: character.character_id,
851 npcEntityId: npcId,
852 slotIndex: 0,
853 quantity: 1
854 });
855 const sold = harness.simulation.step();
856 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
857 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
858 assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);
859 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));
860 assert.equal(boughtQty(shop, ItemId.stick), 1);
861 }
862 finally
863 { harness.close(); }
864});
865
866test("selling a filled cheque pays reserved-goods price minus 5% admin fee", () =>
867{
868 const harness = makeSimulation({ workerCount: 1 });
869 try
870 {
871 const data = createEmptyChunkData();
872 data.open = true;
873 data.blocks[8 * 16 + 8] = { typeId: BlockType.bank, state: 0 };
874 data.spawners = [{
875 localX: 9,
876 localY: 8,
877 config: {
878 mobTypeId: MobId.humanoid,
879 maxAlive: 1,
880 spawnRangeTiles: 0,
881 maxWanderRangeTiles: 0,
882 displayName: "Buyer",
883 sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
884 buysItems: true,
885 hiddenDiscount: 1
886 }
887 }];
888 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
889 harness.simulation.reloadWorld();
890
891 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
892 const slots = emptySlots(INVENTORY_SLOTS);
893 slots[0] = { itemId: ItemId.copperOre, quantity: 2 };
894 harness.stateDb.saveBag(character.character_id, {
895 inventory: slots,
896 equipment: emptyEquipment(),
897 vault: [],
898 vaultReserved: []
899 });
900 const playerId = harness.simulation.spawnCharacter(1, character);
901 harness.simulation.step();
902
903 harness.simulation.enqueue(1, {
904 type: "get-blank-cheques",
905 characterId: character.character_id
906 });
907 harness.simulation.step();
908 harness.simulation.enqueue(1, {
909 type: "bank-deposit",
910 characterId: character.character_id,
911 slotIndex: 0,
912 quantity: null
913 });
914 harness.simulation.step();
915 let bag = harness.simulation.bagOf(playerId);
916 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
917 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.copperOre);
918 harness.simulation.enqueue(1, {
919 type: "write-cheque",
920 characterId: character.character_id,
921 slotIndex: blankIndex,
922 vaultSlotIndex: vaultIndex,
923 quantity: 2
924 });
925 harness.simulation.step();
926 bag = harness.simulation.bagOf(playerId);
927 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
928 assert.ok(chequeIndex >= 0);
929
930 const record = harness.simulation.entityRecord(playerId);
931 const worker = harness.simulation.workers[record.workerId];
932 let npcId = null;
933 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
934 {
935 if (entity.creature.mobTypeId === MobId.humanoid)
936 {
937 npcId = entity.entityId;
938 break;
939 }
940 }
941 assert.ok(npcId);
942 const npcHandle = worker.world.ecs.handleOf(npcId);
943 const shop = worker.world.ecs.get(npcHandle, Component.shop);
944 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
945 const playerHandle = worker.world.ecs.handleOf(playerId);
946 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
947 playerPos.tileX = npcPos.tileX;
948 playerPos.tileY = npcPos.tileY;
949
950 const quote = resolveShopSellQuote(bag.inventory[chequeIndex]);
951 assert.ok(quote?.isCheque);
952 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
953 harness.simulation.enqueue(1, {
954 type: "sell-to-shop",
955 characterId: character.character_id,
956 npcEntityId: npcId,
957 slotIndex: chequeIndex,
958 quantity: 1
959 });
960 const sold = harness.simulation.step();
961 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
962 bag = harness.simulation.bagOf(playerId);
963 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
964 assert.equal((bag.vaultReserved ?? []).length, 0);
965 const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
966 assert.equal(afterCoins - beforeCoins, quote.payout);
967 // Infinite catalog absorbs goods without bought-from-player resale stock.
968 assert.equal(boughtQty(shop, ItemId.copperOre), 0);
969 }
970 finally
971 { harness.close(); }
972});
973
974test("resale stock keeps the seller origin instead of Bought from NPC", () =>
975{
976 const harness = makeSimulation({ workerCount: 1 });
977 try
978 {
979 const data = createEmptyChunkData();
980 data.open = true;
981 data.spawners = [{
982 localX: 9,
983 localY: 8,
984 config: {
985 mobTypeId: MobId.humanoid,
986 maxAlive: 1,
987 spawnRangeTiles: 0,
988 maxWanderRangeTiles: 0,
989 displayName: "Fence",
990 sells: [],
991 buysItems: true,
992 hiddenDiscount: 1
993 }
994 }];
995 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
996 harness.simulation.reloadWorld();
997
998 const minerOrigin = gatherOrigin(GatherOriginVerb.mined, "Ada Miner");
999 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1000 const funded = addCoinsToSlots(emptySlots(), 50);
1001 assert.equal(funded.ok, true);
1002 funded.slots[1] = {
1003 itemId: ItemId.copperOre,
1004 quantity: 2,
1005 origins: [{ origin: minerOrigin, quantity: 2 }]
1006 };
1007 harness.stateDb.saveBag(character.character_id, {
1008 inventory: funded.slots,
1009 equipment: emptyEquipment(),
1010 vault: [],
1011 vaultReserved: []
1012 });
1013 const playerId = harness.simulation.spawnCharacter(1, character);
1014 harness.simulation.step();
1015 harness.advance(50);
1016 harness.simulation.step();
1017
1018 const record = harness.simulation.entityRecord(playerId);
1019 const worker = harness.simulation.workers[record.workerId];
1020 let npcId = null;
1021 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1022 {
1023 if (entity.creature.mobTypeId === MobId.humanoid)
1024 {
1025 npcId = entity.entityId;
1026 break;
1027 }
1028 }
1029 assert.ok(npcId);
1030 const npcHandle = worker.world.ecs.handleOf(npcId);
1031 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1032 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1033 const playerHandle = worker.world.ecs.handleOf(playerId);
1034 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1035 playerPos.tileX = npcPos.tileX;
1036 playerPos.tileY = npcPos.tileY;
1037
1038 harness.simulation.enqueue(1, {
1039 type: "sell-to-shop",
1040 characterId: character.character_id,
1041 npcEntityId: npcId,
1042 slotIndex: 1,
1043 quantity: 2
1044 });
1045 const sold = harness.simulation.step();
1046 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1047 assert.equal(boughtQty(shop, ItemId.copperOre), 2);
1048 assert.deepEqual(shop.boughtStock[ItemId.copperOre].origins, [
1049 { origin: minerOrigin, quantity: 2 }
1050 ]);
1051
1052 harness.simulation.enqueue(1, {
1053 type: "buy-from-shop",
1054 characterId: character.character_id,
1055 npcEntityId: npcId,
1056 itemId: ItemId.copperOre,
1057 quantity: 2,
1058 listingId: `bought:${ItemId.copperOre}`,
1059 source: "bought"
1060 });
1061 const buy = harness.simulation.step();
1062 assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
1063 const bag = harness.simulation.bagOf(playerId);
1064 const ore = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.copperOre);
1065 assert.ok(ore);
1066 assert.equal(ore.origins?.[0]?.origin?.kind, ItemOriginKind.gathered);
1067 assert.equal(ore.origins?.[0]?.origin?.displayName, "Ada Miner");
1068 assert.equal(ore.origins?.[0]?.origin?.kind === ItemOriginKind.shop, false);
1069 }
1070 finally
1071 { harness.close(); }
1072});
1073
1074test("NPC letter sales pay out and destroy the letter without stock", () =>
1075{
1076 const harness = makeSimulation({ workerCount: 1 });
1077 try
1078 {
1079 const data = createEmptyChunkData();
1080 data.open = true;
1081 data.spawners = [{
1082 localX: 9,
1083 localY: 8,
1084 config: {
1085 mobTypeId: MobId.humanoid,
1086 maxAlive: 1,
1087 spawnRangeTiles: 0,
1088 maxWanderRangeTiles: 0,
1089 displayName: "Fence",
1090 sells: [],
1091 buysItems: true,
1092 hiddenDiscount: 1
1093 }
1094 }];
1095 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
1096 harness.simulation.reloadWorld();
1097
1098 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1099 const funded = addCoinsToSlots(emptySlots(), 10);
1100 assert.equal(funded.ok, true);
1101 funded.slots[1] = {
1102 itemId: ItemId.letter,
1103 quantity: 1,
1104 instance: {
1105 kind: "letter",
1106 letterId: "sell-me",
1107 authorCharacterId: character.character_id,
1108 authorDisplayName: "Ada",
1109 body: "For sale",
1110 opened: true,
1111 writtenAt: Date.now()
1112 }
1113 };
1114 harness.stateDb.saveBag(character.character_id, {
1115 inventory: funded.slots,
1116 equipment: emptyEquipment(),
1117 vault: [],
1118 vaultReserved: []
1119 });
1120 const playerId = harness.simulation.spawnCharacter(1, character);
1121 harness.simulation.step();
1122 harness.advance(50);
1123 harness.simulation.step();
1124
1125 const record = harness.simulation.entityRecord(playerId);
1126 const worker = harness.simulation.workers[record.workerId];
1127 let npcId = null;
1128 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1129 {
1130 if (entity.creature.mobTypeId === MobId.humanoid)
1131 {
1132 npcId = entity.entityId;
1133 break;
1134 }
1135 }
1136 assert.ok(npcId);
1137 const npcHandle = worker.world.ecs.handleOf(npcId);
1138 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1139 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1140 const playerHandle = worker.world.ecs.handleOf(playerId);
1141 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1142 playerPos.tileX = npcPos.tileX;
1143 playerPos.tileY = npcPos.tileY;
1144
1145 const letterSlot = harness.simulation.bagOf(playerId).inventory
1146 .findIndex((slot) => slot?.itemId === ItemId.letter);
1147 assert.ok(letterSlot >= 0);
1148 const quote = resolveShopSellQuote(harness.simulation.bagOf(playerId).inventory[letterSlot]);
1149 assert.ok(quote);
1150 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
1151
1152 harness.simulation.enqueue(1, {
1153 type: "sell-to-shop",
1154 characterId: character.character_id,
1155 npcEntityId: npcId,
1156 slotIndex: letterSlot,
1157 quantity: 1
1158 });
1159 const sold = harness.simulation.step();
1160 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1161 const bag = harness.simulation.bagOf(playerId);
1162 assert.equal(bag.inventory.some((slot) => slot?.itemId === ItemId.letter), false);
1163 assert.equal(boughtQty(shop, ItemId.letter), 0);
1164 assert.equal(shop.boughtStock?.[ItemId.letter], undefined);
1165 const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
1166 assert.equal(afterCoins - beforeCoins, quote.payout);
1167 }
1168 finally
1169 { harness.close(); }
1170});
1171
1172test("vendor bought dye stays split by colour and resells that colour", () =>
1173{
1174 const harness = makeSimulation({ workerCount: 1 });
1175 try
1176 {
1177 const data = createEmptyChunkData();
1178 data.open = true;
1179 data.spawners = [{
1180 localX: 9,
1181 localY: 8,
1182 config: {
1183 mobTypeId: MobId.humanoid,
1184 maxAlive: 1,
1185 spawnRangeTiles: 0,
1186 maxWanderRangeTiles: 0,
1187 displayName: "Dyer",
1188 sells: [],
1189 buysItems: true,
1190 hiddenDiscount: 1
1191 }
1192 }];
1193 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
1194 harness.simulation.reloadWorld();
1195
1196 const yellow = dyeItemInstance(
1197 { r: 240 / 255, g: 210 / 255, b: 40 / 255 },
1198 DEFAULT_DYE_FILL,
1199 FlowerColorId.yellow
1200 );
1201 const magenta = dyeItemInstance(
1202 { r: 220 / 255, g: 40 / 255, b: 180 / 255 },
1203 DEFAULT_DYE_FILL,
1204 FlowerColorId.magenta
1205 );
1206 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1207 const funded = addCoinsToSlots(emptySlots(), 200);
1208 assert.equal(funded.ok, true);
1209 funded.slots[1] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(yellow) };
1210 funded.slots[2] = { itemId: ItemId.dye, quantity: 1, instance: structuredClone(magenta) };
1211 harness.stateDb.saveBag(character.character_id, {
1212 inventory: funded.slots,
1213 equipment: emptyEquipment(),
1214 vault: [],
1215 vaultReserved: []
1216 });
1217 const playerId = harness.simulation.spawnCharacter(1, character);
1218 harness.simulation.step();
1219 harness.advance(50);
1220 harness.simulation.step();
1221
1222 const record = harness.simulation.entityRecord(playerId);
1223 const worker = harness.simulation.workers[record.workerId];
1224 let npcId = null;
1225 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
1226 {
1227 if (entity.creature.mobTypeId === MobId.humanoid)
1228 {
1229 npcId = entity.entityId;
1230 break;
1231 }
1232 }
1233 assert.ok(npcId);
1234 const npcHandle = worker.world.ecs.handleOf(npcId);
1235 const shop = worker.world.ecs.get(npcHandle, Component.shop);
1236 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
1237 const playerHandle = worker.world.ecs.handleOf(playerId);
1238 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
1239 playerPos.tileX = npcPos.tileX;
1240 playerPos.tileY = npcPos.tileY;
1241
1242 for (const slotIndex of [1, 2])
1243 {
1244 harness.simulation.enqueue(1, {
1245 type: "sell-to-shop",
1246 characterId: character.character_id,
1247 npcEntityId: npcId,
1248 slotIndex,
1249 quantity: 1
1250 });
1251 const sold = harness.simulation.step();
1252 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
1253 }
1254
1255 const yellowKey = boughtStockKey(ItemId.dye, yellow);
1256 const magentaKey = boughtStockKey(ItemId.dye, magenta);
1257 assert.notEqual(yellowKey, magentaKey);
1258 assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1259 assert.equal(shop.boughtStock[magentaKey]?.quantity, 1);
1260 assert.equal(shop.boughtStock[yellowKey]?.instance?.colorId, FlowerColorId.yellow);
1261 assert.equal(shop.boughtStock[magentaKey]?.instance?.colorId, FlowerColorId.magenta);
1262 assert.equal(shop.boughtStock[ItemId.dye], undefined);
1263
1264 harness.simulation.enqueue(1, {
1265 type: "buy-from-shop",
1266 characterId: character.character_id,
1267 npcEntityId: npcId,
1268 itemId: ItemId.dye,
1269 quantity: 1,
1270 listingId: `bought:${magentaKey}`,
1271 source: "bought"
1272 });
1273 const bought = harness.simulation.step();
1274 assert.equal(bought.events.some((event) => event.type === "command-error"), false, JSON.stringify(bought.events));
1275 const bag = harness.simulation.bagOf(playerId);
1276 const dye = (bag.inventory ?? []).find((slot) => slot?.itemId === ItemId.dye);
1277 assert.ok(dye);
1278 assert.equal(dye.instance?.colorId, FlowerColorId.magenta);
1279 assert.equal(shop.boughtStock[magentaKey], undefined);
1280 assert.equal(shop.boughtStock[yellowKey]?.quantity, 1);
1281 }
1282 finally
1283 { harness.close(); }
1284});