BlueGit

timfa questward

Fix system letters, item origins, and cauldron slot locking.

Route CE/bank/bounty letters to inventory while online, put signatures in the Signed UI (with optional org), stamp Written/minted origins so unknown origin is rare, and lock alchemy ingredient slots after the first brew step.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
d28051eccc1141f06e34e4f4485c2e059a767184
Parent
07a95f71
29 files changed +520 −145
client/src/play/alchemy.js +42 −8
@@ -166,11 +166,19 @@ export function initAlchemy ({
166 166 { saveBtn.hidden = !state?.canSaveRecipe; }
167 167 }
168 168
169 function renderSlotButton (reserved, onClick)
169 function alchemySlotsLocked ()
170 {
171 return state?.canAddIngredients === false
172 || ((state?.steps?.length ?? 0) > 0);
173 }
174
175 function renderSlotButton (reserved, { onClick, locked = false } = {})
170 176 {
171 177 const slotBtn = document.createElement("button");
172 178 slotBtn.type = "button";
173 179 slotBtn.className = "cauldron-slot";
180 if (locked)
181 { slotBtn.classList.add("locked"); }
174 182 if (reserved)
175 183 {
176 184 const stack = {
@@ -185,11 +193,24 @@ export function initAlchemy ({
185 193 qty.className = "qty";
186 194 qty.textContent = formatQuantity(reserved.quantity);
187 195 slotBtn.append(img, qty);
188 slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
196 slotBtn.title = locked
197 ? `${itemDisplayName(stack)} ×${reserved.quantity} (locked until Bottle)`
198 : `${itemDisplayName(stack)} ×${reserved.quantity}`;
189 199 }
190 200 else
191 { slotBtn.textContent = "+"; }
192 slotBtn.addEventListener("click", onClick);
201 {
202 slotBtn.textContent = "+";
203 if (locked)
204 { slotBtn.title = "Ingredient slots lock after the first brew step"; }
205 }
206 slotBtn.disabled = locked && !reserved;
207 if (!locked)
208 { slotBtn.addEventListener("click", onClick); }
209 else if (reserved)
210 {
211 // Filled + locked: still show contents, no replace/clear via click.
212 slotBtn.disabled = true;
213 }
193 214 return slotBtn;
194 215 }
195 216
@@ -197,10 +218,14 @@ export function initAlchemy ({
197 218 {
198 219 slotsEl.replaceChildren();
199 220 insertsEl.replaceChildren();
221 const locked = alchemySlotsLocked();
200 222 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
201 223 {
202 224 const reserved = localSlots[i] ?? null;
203 slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
225 slotsEl.append(renderSlotButton(reserved, {
226 locked,
227 onClick: () => openPick("alchemy", i)
228 }));
204 229 const insertBtn = document.createElement("button");
205 230 insertBtn.type = "button";
206 231 insertBtn.className = "cauldron-insert";
@@ -233,7 +258,9 @@ export function initAlchemy ({
233 258 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
234 259 {
235 260 const reserved = localDyeSlots[i] ?? null;
236 dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
261 dyeSlotsEl.append(renderSlotButton(reserved, {
262 onClick: () => openPick("dye", i)
263 }));
237 264 }
238 265 }
239 266
@@ -256,6 +283,8 @@ export function initAlchemy ({
256 283
257 284 function openPick (mode, slotIndex)
258 285 {
286 if (mode === "alchemy" && alchemySlotsLocked())
287 { return; }
259 288 pickMode = mode;
260 289 pickSlotIndex = slotIndex;
261 290 pickItemId = null;
@@ -459,8 +488,13 @@ export function initAlchemy ({
459 488 { dyeStatusEl.textContent = line; }
460 489 render();
461 490 }
462 else if (statusEl)
463 { statusEl.textContent = line; }
491 else
492 {
493 localSlots = emptyAlchemySlots();
494 if (statusEl)
495 { statusEl.textContent = line; }
496 render();
497 }
464 498 }
465 499 },
466 500 refresh ()
@@ -166,11 +166,19 @@ export function initAlchemy ({
166 { saveBtn.hidden = !state?.canSaveRecipe; }
166 { saveBtn.hidden = !state?.canSaveRecipe; }
167 }
167 }
168
168
169 function renderSlotButton (reserved, onClick)
169 function alchemySlotsLocked ()
170 {
171 return state?.canAddIngredients === false
172 || ((state?.steps?.length ?? 0) > 0);
173 }
174
175 function renderSlotButton (reserved, { onClick, locked = false } = {})
170 {
176 {
171 const slotBtn = document.createElement("button");
177 const slotBtn = document.createElement("button");
172 slotBtn.type = "button";
178 slotBtn.type = "button";
173 slotBtn.className = "cauldron-slot";
179 slotBtn.className = "cauldron-slot";
180 if (locked)
181 { slotBtn.classList.add("locked"); }
174 if (reserved)
182 if (reserved)
175 {
183 {
176 const stack = {
184 const stack = {
@@ -185,11 +193,24 @@ export function initAlchemy ({
185 qty.className = "qty";
193 qty.className = "qty";
186 qty.textContent = formatQuantity(reserved.quantity);
194 qty.textContent = formatQuantity(reserved.quantity);
187 slotBtn.append(img, qty);
195 slotBtn.append(img, qty);
188 slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
196 slotBtn.title = locked
197 ? `${itemDisplayName(stack)} ×${reserved.quantity} (locked until Bottle)`
198 : `${itemDisplayName(stack)} ×${reserved.quantity}`;
189 }
199 }
190 else
200 else
191 { slotBtn.textContent = "+"; }
201 {
192 slotBtn.addEventListener("click", onClick);
202 slotBtn.textContent = "+";
203 if (locked)
204 { slotBtn.title = "Ingredient slots lock after the first brew step"; }
205 }
206 slotBtn.disabled = locked && !reserved;
207 if (!locked)
208 { slotBtn.addEventListener("click", onClick); }
209 else if (reserved)
210 {
211 // Filled + locked: still show contents, no replace/clear via click.
212 slotBtn.disabled = true;
213 }
193 return slotBtn;
214 return slotBtn;
194 }
215 }
195
216
@@ -197,10 +218,14 @@ export function initAlchemy ({
197 {
218 {
198 slotsEl.replaceChildren();
219 slotsEl.replaceChildren();
199 insertsEl.replaceChildren();
220 insertsEl.replaceChildren();
221 const locked = alchemySlotsLocked();
200 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
222 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
201 {
223 {
202 const reserved = localSlots[i] ?? null;
224 const reserved = localSlots[i] ?? null;
203 slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
225 slotsEl.append(renderSlotButton(reserved, {
226 locked,
227 onClick: () => openPick("alchemy", i)
228 }));
204 const insertBtn = document.createElement("button");
229 const insertBtn = document.createElement("button");
205 insertBtn.type = "button";
230 insertBtn.type = "button";
206 insertBtn.className = "cauldron-insert";
231 insertBtn.className = "cauldron-insert";
@@ -233,7 +258,9 @@ export function initAlchemy ({
233 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
258 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
234 {
259 {
235 const reserved = localDyeSlots[i] ?? null;
260 const reserved = localDyeSlots[i] ?? null;
236 dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
261 dyeSlotsEl.append(renderSlotButton(reserved, {
262 onClick: () => openPick("dye", i)
263 }));
237 }
264 }
238 }
265 }
239
266
@@ -256,6 +283,8 @@ export function initAlchemy ({
256
283
257 function openPick (mode, slotIndex)
284 function openPick (mode, slotIndex)
258 {
285 {
286 if (mode === "alchemy" && alchemySlotsLocked())
287 { return; }
259 pickMode = mode;
288 pickMode = mode;
260 pickSlotIndex = slotIndex;
289 pickSlotIndex = slotIndex;
261 pickItemId = null;
290 pickItemId = null;
@@ -459,8 +488,13 @@ export function initAlchemy ({
459 { dyeStatusEl.textContent = line; }
488 { dyeStatusEl.textContent = line; }
460 render();
489 render();
461 }
490 }
462 else if (statusEl)
491 else
463 { statusEl.textContent = line; }
492 {
493 localSlots = emptyAlchemySlots();
494 if (statusEl)
495 { statusEl.textContent = line; }
496 render();
497 }
464 }
498 }
465 },
499 },
466 refresh ()
500 refresh ()
client/src/play/inventory.js +3 −4
@@ -9,6 +9,7 @@ import {
9 9 EQUIPMENT_SLOT,
10 10 LETTER_MAX_BODY_CHARS
11 11 } from "/shared/definitions/items.js";
12 import { formatLetterSignature } from "/shared/courier/systemLetters.js";
12 13 import { applyItemIcon } from "../render/potionIcon.js";
13 14
14 15 const EQUIP_LABELS = {
@@ -713,10 +714,8 @@ export function initInventory ({
713 714
714 715 function refreshLetterSignature ()
715 716 {
716 const name = letterState?.instance?.authorDisplayName
717 || getLocalName?.()
718 || "Unknown";
719 letterSignature.textContent = `Signed:\n${name}`;
717 const fallback = getLocalName?.() || "Unknown";
718 letterSignature.textContent = formatLetterSignature(letterState?.instance, fallback);
720 719 }
721 720
722 721 function closeLetter ()
@@ -9,6 +9,7 @@ import {
9 EQUIPMENT_SLOT,
9 EQUIPMENT_SLOT,
10 LETTER_MAX_BODY_CHARS
10 LETTER_MAX_BODY_CHARS
11} from "/shared/definitions/items.js";
11} from "/shared/definitions/items.js";
12import { formatLetterSignature } from "/shared/courier/systemLetters.js";
12import { applyItemIcon } from "../render/potionIcon.js";
13import { applyItemIcon } from "../render/potionIcon.js";
13
14
14const EQUIP_LABELS = {
15const EQUIP_LABELS = {
@@ -713,10 +714,8 @@ export function initInventory ({
713
714
714 function refreshLetterSignature ()
715 function refreshLetterSignature ()
715 {
716 {
716 const name = letterState?.instance?.authorDisplayName
717 const fallback = getLocalName?.() || "Unknown";
717 || getLocalName?.()
718 letterSignature.textContent = formatLetterSignature(letterState?.instance, fallback);
718 || "Unknown";
719 letterSignature.textContent = `Signed:\n${name}`;
720 }
719 }
721
720
722 function closeLetter ()
721 function closeLetter ()
client/ui/play.css +10 −0
@@ -877,6 +877,16 @@ a { color: #d4c48a; }
877 877 background: #12151c;
878 878 }
879 879
880 .cauldron-slot.locked {
881 opacity: 0.72;
882 cursor: default;
883 }
884
885 .cauldron-slot:disabled {
886 opacity: 0.55;
887 cursor: not-allowed;
888 }
889
880 890 .cauldron-slot img,
881 891 .cauldron-pick-item img {
882 892 width: 32px;
@@ -877,6 +877,16 @@ a { color: #d4c48a; }
877 background: #12151c;
877 background: #12151c;
878}
878}
879
879
880.cauldron-slot.locked {
881 opacity: 0.72;
882 cursor: default;
883}
884
885.cauldron-slot:disabled {
886 opacity: 0.55;
887 cursor: not-allowed;
888}
889
880.cauldron-slot img,
890.cauldron-slot img,
881.cauldron-pick-item img {
891.cauldron-pick-item img {
882 width: 32px;
892 width: 32px;
docs/FEATURES.md +1 −1
@@ -220,7 +220,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
220 220 ## Combat, skills, groups, pigeons
221 221
222 222 **Status:** partial
223 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
223 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken (lethal hits grant none). Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
224 224 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
225 225
226 226 ## Player death and respawn
@@ -220,7 +220,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
220## Combat, skills, groups, pigeons
220## Combat, skills, groups, pigeons
221
221
222**Status:** partial
222**Status:** partial
223**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
223**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken (lethal hits grant none). Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
224**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
224**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
225
225
226## Player death and respawn
226## Player death and respawn
server/src/alchemy/service.js +30 −14
@@ -26,7 +26,7 @@ import {
26 26 takeMatchingFromSlots,
27 27 stackQuantity
28 28 } from "../../../shared/items/inventory.js";
29 import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";
29 import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
30 30 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31 31 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32 32 import { randomUUID } from "node:crypto";
@@ -84,6 +84,8 @@ function sessionView (session)
84 84 steps: steps.map((step) => ({ ...step })),
85 85 flavorText: cauldronFlavorText(steps),
86 86 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
87 /** Top ingredient slots lock after the first brew step until Bottle/Clear. */
88 canAddIngredients: steps.length === 0,
87 89 canSaveRecipe: !!session.lastSuccessRecipe,
88 90 lastSuccess: session.lastSuccessRecipe
89 91 ? {
@@ -186,11 +188,12 @@ function refundStacks (inventory, rows)
186 188 for (const row of rows ?? [])
187 189 {
188 190 const def = itemDefinition(row.itemId);
189 const refund = insertStack(inventory.slots, {
191 const refund = insertStack(inventory.slots, attachOrigins({
190 192 itemId: row.itemId,
191 193 quantity: row.quantity,
192 instance: row.instance ? structuredClone(row.instance) : null
193 }, def);
194 instance: row.instance ? structuredClone(row.instance) : null,
195 origins: row.origins ?? normalizeOrigins(row)
196 }), def);
194 197 if (refund.ok)
195 198 { inventory.slots = refund.slots; }
196 199 }
@@ -298,6 +301,14 @@ function insertIngredient (world, sessionId, command)
298 301 if (have < alreadyClaimed + quantity)
299 302 { throw userError("Not enough of that item in your inventory."); }
300 303
304 const uniqueIds = new Set((session.pendingBrew ?? []).map((row) => row.itemId | 0));
305 if (!uniqueIds.has(itemId) && uniqueIds.size >= CAULDRON_SLOT_COUNT)
306 {
307 throw userError(
308 `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.`
309 );
310 }
311
301 312 addPendingBrew(session, { itemId, quantity, instance });
302 313 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
303 314 session.lastSuccessRecipe = null;
@@ -364,6 +375,7 @@ function bottle (world, sessionId, command)
364 375 }
365 376
366 377 // Consume soft-claimed ingredients only now (success path).
378 const consumed = [];
367 379 for (const row of session.pendingBrew ?? [])
368 380 {
369 381 const pulled = takeMatchingFromSlots(inventory.slots, {
@@ -373,8 +385,12 @@ function bottle (world, sessionId, command)
373 385 compact: false
374 386 });
375 387 if (!pulled.ok)
376 { throw userError("Not enough of that item in your inventory."); }
388 {
389 refundStacks(inventory, consumed);
390 throw userError("Not enough of that item in your inventory.");
391 }
377 392 inventory.slots = pulled.slots;
393 consumed.push(pulled.taken);
378 394 }
379 395
380 396 const takeBottles = takeMatchingFromSlots(inventory.slots, {
@@ -384,7 +400,7 @@ function bottle (world, sessionId, command)
384 400 });
385 401 if (!takeBottles.ok)
386 402 {
387 refundStacks(inventory, session.pendingBrew);
403 refundStacks(inventory, consumed);
388 404 throw userError("You need glass bottles to bottle the brew.");
389 405 }
390 406 inventory.slots = takeBottles.slots;
@@ -400,12 +416,8 @@ function bottle (world, sessionId, command)
400 416 }), potionDef);
401 417 if (!inserted.ok)
402 418 {
403 refundStacks(inventory, session.pendingBrew);
404 const refundBottles = insertStack(inventory.slots, {
405 itemId: ItemId.glassBottle,
406 quantity: produced
407 }, itemDefinition(ItemId.glassBottle));
408 inventory.slots = refundBottles.ok ? refundBottles.slots : inventory.slots;
419 refundStacks(inventory, consumed);
420 refundStacks(inventory, [takeBottles.taken]);
409 421 throw userError("Not enough inventory space for potions.");
410 422 }
411 423 inventory.slots = inserted.slots;
@@ -596,9 +608,13 @@ function saveRecipe (world, sessionId, command)
596 608 if (paperIndex < 0)
597 609 { throw userError("You need paper to write a recipe."); }
598 610 const paperSlot = inventory.slots[paperIndex];
599 const recipeStack = {
611 const recipeStack = attachOrigins({
600 612 itemId: ItemId.recipePaper,
601 613 quantity: 1,
614 origins: [{
615 origin: writtenOrigin(characterDisplayName(world, handle)),
616 quantity: 1
617 }],
602 618 instance: {
603 619 kind: "recipe-paper",
604 620 recipeId: randomUUID(),
@@ -610,7 +626,7 @@ function saveRecipe (world, sessionId, command)
610 626 body: recipePaperBody(recipe),
611 627 writtenAt: Date.now()
612 628 }
613 };
629 });
614 630
615 631 if (stackQuantity(paperSlot.quantity) <= 1)
616 632 { inventory.slots[paperIndex] = recipeStack; }
@@ -26,7 +26,7 @@ import {
26 takeMatchingFromSlots,
26 takeMatchingFromSlots,
27 stackQuantity
27 stackQuantity
28} from "../../../shared/items/inventory.js";
28} from "../../../shared/items/inventory.js";
29import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";
29import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32import { randomUUID } from "node:crypto";
32import { randomUUID } from "node:crypto";
@@ -84,6 +84,8 @@ function sessionView (session)
84 steps: steps.map((step) => ({ ...step })),
84 steps: steps.map((step) => ({ ...step })),
85 flavorText: cauldronFlavorText(steps),
85 flavorText: cauldronFlavorText(steps),
86 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
86 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
87 /** Top ingredient slots lock after the first brew step until Bottle/Clear. */
88 canAddIngredients: steps.length === 0,
87 canSaveRecipe: !!session.lastSuccessRecipe,
89 canSaveRecipe: !!session.lastSuccessRecipe,
88 lastSuccess: session.lastSuccessRecipe
90 lastSuccess: session.lastSuccessRecipe
89 ? {
91 ? {
@@ -186,11 +188,12 @@ function refundStacks (inventory, rows)
186 for (const row of rows ?? [])
188 for (const row of rows ?? [])
187 {
189 {
188 const def = itemDefinition(row.itemId);
190 const def = itemDefinition(row.itemId);
189 const refund = insertStack(inventory.slots, {
191 const refund = insertStack(inventory.slots, attachOrigins({
190 itemId: row.itemId,
192 itemId: row.itemId,
191 quantity: row.quantity,
193 quantity: row.quantity,
192 instance: row.instance ? structuredClone(row.instance) : null
194 instance: row.instance ? structuredClone(row.instance) : null,
193 }, def);
195 origins: row.origins ?? normalizeOrigins(row)
196 }), def);
194 if (refund.ok)
197 if (refund.ok)
195 { inventory.slots = refund.slots; }
198 { inventory.slots = refund.slots; }
196 }
199 }
@@ -298,6 +301,14 @@ function insertIngredient (world, sessionId, command)
298 if (have < alreadyClaimed + quantity)
301 if (have < alreadyClaimed + quantity)
299 { throw userError("Not enough of that item in your inventory."); }
302 { throw userError("Not enough of that item in your inventory."); }
300
303
304 const uniqueIds = new Set((session.pendingBrew ?? []).map((row) => row.itemId | 0));
305 if (!uniqueIds.has(itemId) && uniqueIds.size >= CAULDRON_SLOT_COUNT)
306 {
307 throw userError(
308 `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.`
309 );
310 }
311
301 addPendingBrew(session, { itemId, quantity, instance });
312 addPendingBrew(session, { itemId, quantity, instance });
302 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
313 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
303 session.lastSuccessRecipe = null;
314 session.lastSuccessRecipe = null;
@@ -364,6 +375,7 @@ function bottle (world, sessionId, command)
364 }
375 }
365
376
366 // Consume soft-claimed ingredients only now (success path).
377 // Consume soft-claimed ingredients only now (success path).
378 const consumed = [];
367 for (const row of session.pendingBrew ?? [])
379 for (const row of session.pendingBrew ?? [])
368 {
380 {
369 const pulled = takeMatchingFromSlots(inventory.slots, {
381 const pulled = takeMatchingFromSlots(inventory.slots, {
@@ -373,8 +385,12 @@ function bottle (world, sessionId, command)
373 compact: false
385 compact: false
374 });
386 });
375 if (!pulled.ok)
387 if (!pulled.ok)
376 { throw userError("Not enough of that item in your inventory."); }
388 {
389 refundStacks(inventory, consumed);
390 throw userError("Not enough of that item in your inventory.");
391 }
377 inventory.slots = pulled.slots;
392 inventory.slots = pulled.slots;
393 consumed.push(pulled.taken);
378 }
394 }
379
395
380 const takeBottles = takeMatchingFromSlots(inventory.slots, {
396 const takeBottles = takeMatchingFromSlots(inventory.slots, {
@@ -384,7 +400,7 @@ function bottle (world, sessionId, command)
384 });
400 });
385 if (!takeBottles.ok)
401 if (!takeBottles.ok)
386 {
402 {
387 refundStacks(inventory, session.pendingBrew);
403 refundStacks(inventory, consumed);
388 throw userError("You need glass bottles to bottle the brew.");
404 throw userError("You need glass bottles to bottle the brew.");
389 }
405 }
390 inventory.slots = takeBottles.slots;
406 inventory.slots = takeBottles.slots;
@@ -400,12 +416,8 @@ function bottle (world, sessionId, command)
400 }), potionDef);
416 }), potionDef);
401 if (!inserted.ok)
417 if (!inserted.ok)
402 {
418 {
403 refundStacks(inventory, session.pendingBrew);
419 refundStacks(inventory, consumed);
404 const refundBottles = insertStack(inventory.slots, {
420 refundStacks(inventory, [takeBottles.taken]);
405 itemId: ItemId.glassBottle,
406 quantity: produced
407 }, itemDefinition(ItemId.glassBottle));
408 inventory.slots = refundBottles.ok ? refundBottles.slots : inventory.slots;
409 throw userError("Not enough inventory space for potions.");
421 throw userError("Not enough inventory space for potions.");
410 }
422 }
411 inventory.slots = inserted.slots;
423 inventory.slots = inserted.slots;
@@ -596,9 +608,13 @@ function saveRecipe (world, sessionId, command)
596 if (paperIndex < 0)
608 if (paperIndex < 0)
597 { throw userError("You need paper to write a recipe."); }
609 { throw userError("You need paper to write a recipe."); }
598 const paperSlot = inventory.slots[paperIndex];
610 const paperSlot = inventory.slots[paperIndex];
599 const recipeStack = {
611 const recipeStack = attachOrigins({
600 itemId: ItemId.recipePaper,
612 itemId: ItemId.recipePaper,
601 quantity: 1,
613 quantity: 1,
614 origins: [{
615 origin: writtenOrigin(characterDisplayName(world, handle)),
616 quantity: 1
617 }],
602 instance: {
618 instance: {
603 kind: "recipe-paper",
619 kind: "recipe-paper",
604 recipeId: randomUUID(),
620 recipeId: randomUUID(),
@@ -610,7 +626,7 @@ function saveRecipe (world, sessionId, command)
610 body: recipePaperBody(recipe),
626 body: recipePaperBody(recipe),
611 writtenAt: Date.now()
627 writtenAt: Date.now()
612 }
628 }
613 };
629 });
614
630
615 if (stackQuantity(paperSlot.quantity) <= 1)
631 if (stackQuantity(paperSlot.quantity) <= 1)
616 { inventory.slots[paperIndex] = recipeStack; }
632 { inventory.slots[paperIndex] = recipeStack; }
server/src/bounty/service.js +9 −8
@@ -1,6 +1,8 @@
1 1 import { randomUUID } from "node:crypto";
2 2 import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
3 3 import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
4 import { BOUNTY_OFFICE_AUTHOR } from "../../../shared/courier/systemLetters.js";
5 import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";
4 6 import { layersFromBag } from "../../../shared/appearance/layers.js";
5 7 import {
6 8 addCoinsToSlots,
@@ -246,28 +248,27 @@ export class BountyService
246 248 victimName,
247 249 amountCopper: paidCopper
248 250 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
249 const stack = {
251 const stack = attachOrigins({
250 252 itemId: ItemId.letter,
251 253 quantity: 1,
254 origins: [{ origin: writtenOrigin(BOUNTY_OFFICE_AUTHOR), quantity: 1 }],
252 255 instance: {
253 256 kind: "letter",
254 257 letterId: randomUUID(),
255 258 authorCharacterId: 0,
256 authorDisplayName: "Bounty Office",
259 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
257 260 body,
258 261 opened: false,
259 262 writtenAt: Date.now()
260 263 }
261 };
264 });
262 265 try
263 266 {
264 this.courier.dispatchHeldCargo({
265 senderCharacterId: killerCharacterId,
267 this.courier.dispatchSystemLetter({
268 characterId: killerCharacterId,
266 269 originTileX: office.tileX,
267 270 originTileY: office.tileY,
268 destination: { kind: "bank" },
269 cargo: { kind: "item", stack },
270 vaultCharacterId: killerCharacterId
271 stack
271 272 });
272 273 }
273 274 catch
@@ -1,6 +1,8 @@
1import { randomUUID } from "node:crypto";
1import { randomUUID } from "node:crypto";
2import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
2import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
3import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
3import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
4import { BOUNTY_OFFICE_AUTHOR } from "../../../shared/courier/systemLetters.js";
5import { attachOrigins, writtenOrigin } from "../../../shared/items/origin.js";
4import { layersFromBag } from "../../../shared/appearance/layers.js";
6import { layersFromBag } from "../../../shared/appearance/layers.js";
5import {
7import {
6 addCoinsToSlots,
8 addCoinsToSlots,
@@ -246,28 +248,27 @@ export class BountyService
246 victimName,
248 victimName,
247 amountCopper: paidCopper
249 amountCopper: paidCopper
248 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
250 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
249 const stack = {
251 const stack = attachOrigins({
250 itemId: ItemId.letter,
252 itemId: ItemId.letter,
251 quantity: 1,
253 quantity: 1,
254 origins: [{ origin: writtenOrigin(BOUNTY_OFFICE_AUTHOR), quantity: 1 }],
252 instance: {
255 instance: {
253 kind: "letter",
256 kind: "letter",
254 letterId: randomUUID(),
257 letterId: randomUUID(),
255 authorCharacterId: 0,
258 authorCharacterId: 0,
256 authorDisplayName: "Bounty Office",
259 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
257 body,
260 body,
258 opened: false,
261 opened: false,
259 writtenAt: Date.now()
262 writtenAt: Date.now()
260 }
263 }
261 };
264 });
262 try
265 try
263 {
266 {
264 this.courier.dispatchHeldCargo({
267 this.courier.dispatchSystemLetter({
265 senderCharacterId: killerCharacterId,
268 characterId: killerCharacterId,
266 originTileX: office.tileX,
269 originTileX: office.tileX,
267 originTileY: office.tileY,
270 originTileY: office.tileY,
268 destination: { kind: "bank" },
271 stack
269 cargo: { kind: "item", stack },
270 vaultCharacterId: killerCharacterId
271 });
272 });
272 }
273 }
273 catch
274 catch
server/src/courier/service.js +44 −14
@@ -3,6 +3,7 @@ import { BlockType } from "../../../shared/definitions/tiles.js";
3 3 import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4 4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 5 import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6 import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
6 7 import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7 8 import { GAIT } from "../../../shared/protocol/constants.js";
8 9 import { decodeChunkBlob } from "../world/chunkData.js";
@@ -177,6 +178,40 @@ export class CourierService
177 178 return { transit, bag };
178 179 }
179 180
181 /**
182 * System letters (CE / bank / bounty): to inventory while online (bank if full),
183 * or straight to the bank vault while offline.
184 */
185 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
186 {
187 const recipientId = characterId | 0;
188 const cargo = { kind: "item", stack };
189 if (this.simulation.isCharacterOnline(recipientId))
190 {
191 const row = this.stateDb.getCharacter(recipientId);
192 return this.dispatchHeldCargo({
193 senderCharacterId: recipientId,
194 originTileX,
195 originTileY,
196 destination: {
197 kind: "player",
198 firstName: row?.first_name ?? "Unknown",
199 lastName: row?.last_name ?? ""
200 },
201 cargo,
202 vaultCharacterId: recipientId
203 });
204 }
205 return this.dispatchHeldCargo({
206 senderCharacterId: recipientId,
207 originTileX,
208 originTileY,
209 destination: { kind: "bank" },
210 cargo,
211 vaultCharacterId: recipientId
212 });
213 }
214
180 215 /**
181 216 * Market / system dispatch already holding cargo (no bag take).
182 217 * When the recipient is offline, holds delivery until login (CE letters, etc.).
@@ -504,7 +539,7 @@ export class CourierService
504 539 {
505 540 return {
506 541 kind: "item",
507 stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
542 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
508 543 };
509 544 }
510 545 return cargo;
@@ -651,25 +686,19 @@ export class CourierService
651 686 }
652 687
653 688 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
654 const inserted = insertStackGrowable(vault.slots, {
689 const goodsStack = attachOrigins({
655 690 itemId: reservedStack.itemId,
656 691 quantity: reservedStack.quantity,
657 origin: reservedStack.origin ?? null,
658 origins: reservedStack.origins ?? null,
692 origins: normalizeOrigins(reservedStack),
659 693 instance: reservedStack.instance ?? null
660 }, goodsDef);
694 });
695 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
661 696 bag.vault = inserted.slots;
662 697 bag.vaultReserved = vault.reserved;
663 698 this.#persistBag(characterId, bag);
664 699 this.#maybeRecordRestNotice({
665 700 characterId,
666 stack: {
667 itemId: reservedStack.itemId,
668 quantity: reservedStack.quantity,
669 origin: reservedStack.origin ?? null,
670 origins: reservedStack.origins ?? null,
671 instance: reservedStack.instance ?? null
672 },
701 stack: goodsStack,
673 702 senderCharacterId: null,
674 703 recordRestNotice: !this.simulation.characterEntities.get(characterId)
675 704 });
@@ -712,9 +741,10 @@ export class CourierService
712 741 })));
713 742 const { full: playerName } = this.#characterDisplayName(characterId);
714 743 const body = bankRestNoticeLetterBody({ playerName, lines });
715 const stack = {
744 const stack = attachOrigins({
716 745 itemId: ItemId.letter,
717 746 quantity: 1,
747 origins: [{ origin: writtenOrigin(BANK_LETTER_AUTHOR), quantity: 1 }],
718 748 instance: {
719 749 kind: "letter",
720 750 letterId: randomUUID(),
@@ -725,7 +755,7 @@ export class CourierService
725 755 writtenAt: Date.now(),
726 756 bankRestNotice: true
727 757 }
728 };
758 });
729 759 this.stateDb.clearBankRestNotices(characterId);
730 760 return this.stateDb.insertCourierTransit({
731 761 senderCharacterId: characterId,
@@ -3,6 +3,7 @@ import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { attachOrigins, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
8import { GAIT } from "../../../shared/protocol/constants.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
9import { decodeChunkBlob } from "../world/chunkData.js";
@@ -177,6 +178,40 @@ export class CourierService
177 return { transit, bag };
178 return { transit, bag };
178 }
179 }
179
180
181 /**
182 * System letters (CE / bank / bounty): to inventory while online (bank if full),
183 * or straight to the bank vault while offline.
184 */
185 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
186 {
187 const recipientId = characterId | 0;
188 const cargo = { kind: "item", stack };
189 if (this.simulation.isCharacterOnline(recipientId))
190 {
191 const row = this.stateDb.getCharacter(recipientId);
192 return this.dispatchHeldCargo({
193 senderCharacterId: recipientId,
194 originTileX,
195 originTileY,
196 destination: {
197 kind: "player",
198 firstName: row?.first_name ?? "Unknown",
199 lastName: row?.last_name ?? ""
200 },
201 cargo,
202 vaultCharacterId: recipientId
203 });
204 }
205 return this.dispatchHeldCargo({
206 senderCharacterId: recipientId,
207 originTileX,
208 originTileY,
209 destination: { kind: "bank" },
210 cargo,
211 vaultCharacterId: recipientId
212 });
213 }
214
180 /**
215 /**
181 * Market / system dispatch already holding cargo (no bag take).
216 * Market / system dispatch already holding cargo (no bag take).
182 * When the recipient is offline, holds delivery until login (CE letters, etc.).
217 * When the recipient is offline, holds delivery until login (CE letters, etc.).
@@ -504,7 +539,7 @@ export class CourierService
504 {
539 {
505 return {
540 return {
506 kind: "item",
541 kind: "item",
507 stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
542 stack: attachOrigins({ itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) })
508 };
543 };
509 }
544 }
510 return cargo;
545 return cargo;
@@ -651,25 +686,19 @@ export class CourierService
651 }
686 }
652
687
653 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
688 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
654 const inserted = insertStackGrowable(vault.slots, {
689 const goodsStack = attachOrigins({
655 itemId: reservedStack.itemId,
690 itemId: reservedStack.itemId,
656 quantity: reservedStack.quantity,
691 quantity: reservedStack.quantity,
657 origin: reservedStack.origin ?? null,
692 origins: normalizeOrigins(reservedStack),
658 origins: reservedStack.origins ?? null,
659 instance: reservedStack.instance ?? null
693 instance: reservedStack.instance ?? null
660 }, goodsDef);
694 });
695 const inserted = insertStackGrowable(vault.slots, goodsStack, goodsDef);
661 bag.vault = inserted.slots;
696 bag.vault = inserted.slots;
662 bag.vaultReserved = vault.reserved;
697 bag.vaultReserved = vault.reserved;
663 this.#persistBag(characterId, bag);
698 this.#persistBag(characterId, bag);
664 this.#maybeRecordRestNotice({
699 this.#maybeRecordRestNotice({
665 characterId,
700 characterId,
666 stack: {
701 stack: goodsStack,
667 itemId: reservedStack.itemId,
668 quantity: reservedStack.quantity,
669 origin: reservedStack.origin ?? null,
670 origins: reservedStack.origins ?? null,
671 instance: reservedStack.instance ?? null
672 },
673 senderCharacterId: null,
702 senderCharacterId: null,
674 recordRestNotice: !this.simulation.characterEntities.get(characterId)
703 recordRestNotice: !this.simulation.characterEntities.get(characterId)
675 });
704 });
@@ -712,9 +741,10 @@ export class CourierService
712 })));
741 })));
713 const { full: playerName } = this.#characterDisplayName(characterId);
742 const { full: playerName } = this.#characterDisplayName(characterId);
714 const body = bankRestNoticeLetterBody({ playerName, lines });
743 const body = bankRestNoticeLetterBody({ playerName, lines });
715 const stack = {
744 const stack = attachOrigins({
716 itemId: ItemId.letter,
745 itemId: ItemId.letter,
717 quantity: 1,
746 quantity: 1,
747 origins: [{ origin: writtenOrigin(BANK_LETTER_AUTHOR), quantity: 1 }],
718 instance: {
748 instance: {
719 kind: "letter",
749 kind: "letter",
720 letterId: randomUUID(),
750 letterId: randomUUID(),
@@ -725,7 +755,7 @@ export class CourierService
725 writtenAt: Date.now(),
755 writtenAt: Date.now(),
726 bankRestNotice: true
756 bankRestNotice: true
727 }
757 }
728 };
758 });
729 this.stateDb.clearBankRestNotices(characterId);
759 this.stateDb.clearBankRestNotices(characterId);
730 return this.stateDb.insertCourierTransit({
760 return this.stateDb.insertCourierTransit({
731 senderCharacterId: characterId,
761 senderCharacterId: characterId,
server/src/items/bags.js +27 −12
@@ -32,6 +32,13 @@ import {
32 32 emptyStatusEffects,
33 33 StatusEffectType
34 34 } from "../../../shared/statusEffects/rules.js";
35 import {
36 attachOrigins,
37 writtenOrigin,
38 bankIssuedOrigin,
39 normalizeOrigins
40 } from "../../../shared/items/origin.js";
41 import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
35 42
36 43 export function publicGroundItem (item)
37 44 {
@@ -564,7 +571,11 @@ function getBlankCheques (world, sessionId, command)
564 571 if (!need)
565 572 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
566 573 const def = itemDefinition(ItemId.blankCheque);
567 const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
574 const inserted = insertStack(inventory.slots, attachOrigins({
575 itemId: ItemId.blankCheque,
576 quantity: need,
577 origins: [{ origin: bankIssuedOrigin(BANK_LETTER_AUTHOR), quantity: need }]
578 }), def);
568 579 if (!inserted.ok)
569 580 { throw userError("Need inventory space for blank cheques."); }
570 581 inventory.slots = inserted.slots;
@@ -617,21 +628,24 @@ function writeCheque (world, sessionId, command)
617 628 if (!pulled.ok)
618 629 { throw userError("Not enough unreserved goods in the vault."); }
619 630
631 const appearance = world.ecs.get(handle, Component.appearance);
632 const issuerName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim()
633 || "Unknown";
620 634 const chequeId = randomUUID();
621 635 const reservedStack = {
622 636 itemId: pulled.taken.itemId,
623 637 quantity: pulled.taken.quantity,
624 origin: pulled.taken.origin ?? null,
638 origins: normalizeOrigins(pulled.taken),
625 639 instance: pulled.taken.instance ?? null,
626 640 chequeId
627 641 };
628 642 vault.slots = pulled.slots;
629 643 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
630 644
631 const filled = {
645 const filled = attachOrigins({
632 646 itemId: ItemId.filledCheque,
633 647 quantity: 1,
634 origin: null,
648 origins: [{ origin: writtenOrigin(issuerName), quantity: 1 }],
635 649 instance: {
636 650 kind: "filled-cheque",
637 651 chequeId,
@@ -641,7 +655,7 @@ function writeCheque (world, sessionId, command)
641 655 reservedInstance: pulled.taken.instance ?? null,
642 656 createdAt: Date.now()
643 657 }
644 };
658 });
645 659 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
646 660 inventory.slots = blankTaken.slots;
647 661 if (!inventory.slots[slotIndex])
@@ -699,13 +713,12 @@ function redeemCheque (world, sessionId, command)
699 713 reservedStack = release.stack;
700 714 }
701 715
702 const inserted = insertStackGrowable(vault.slots, {
716 const inserted = insertStackGrowable(vault.slots, attachOrigins({
703 717 itemId: reservedStack.itemId,
704 718 quantity: reservedStack.quantity,
705 origin: reservedStack.origin ?? null,
706 origins: reservedStack.origins ?? null,
719 origins: normalizeOrigins(reservedStack),
707 720 instance: reservedStack.instance ?? null
708 }, goodsDef);
721 }), goodsDef);
709 722 if (!inserted.ok)
710 723 {
711 724 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -776,10 +789,10 @@ function writeLetter (world, sessionId, command)
776 789 const body = normalizeLetterBody(command.body);
777 790 const appearance = world.ecs.get(handle, Component.appearance);
778 791 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
779 const letterStack = {
792 const letterStack = attachOrigins({
780 793 itemId: ItemId.letter,
781 794 quantity: 1,
782 origin: null,
795 origins: [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }],
783 796 instance: {
784 797 kind: "letter",
785 798 letterId: randomUUID(),
@@ -789,7 +802,7 @@ function writeLetter (world, sessionId, command)
789 802 opened: true,
790 803 writtenAt: Date.now()
791 804 }
792 };
805 });
793 806 if (slot.quantity <= 1)
794 807 {
795 808 inventory.slots[slotIndex] = letterStack;
@@ -822,6 +835,8 @@ function editLetter (world, sessionId, command)
822 835 body: normalizeLetterBody(command.body),
823 836 writtenAt: Date.now()
824 837 };
838 slot.origins = [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }];
839 delete slot.origin;
825 840 return { events: [], private: bagView(world.ecs, handle) };
826 841 }
827 842
@@ -32,6 +32,13 @@ import {
32 emptyStatusEffects,
32 emptyStatusEffects,
33 StatusEffectType
33 StatusEffectType
34} from "../../../shared/statusEffects/rules.js";
34} from "../../../shared/statusEffects/rules.js";
35import {
36 attachOrigins,
37 writtenOrigin,
38 bankIssuedOrigin,
39 normalizeOrigins
40} from "../../../shared/items/origin.js";
41import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js";
35
42
36export function publicGroundItem (item)
43export function publicGroundItem (item)
37{
44{
@@ -564,7 +571,11 @@ function getBlankCheques (world, sessionId, command)
564 if (!need)
571 if (!need)
565 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
572 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
566 const def = itemDefinition(ItemId.blankCheque);
573 const def = itemDefinition(ItemId.blankCheque);
567 const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
574 const inserted = insertStack(inventory.slots, attachOrigins({
575 itemId: ItemId.blankCheque,
576 quantity: need,
577 origins: [{ origin: bankIssuedOrigin(BANK_LETTER_AUTHOR), quantity: need }]
578 }), def);
568 if (!inserted.ok)
579 if (!inserted.ok)
569 { throw userError("Need inventory space for blank cheques."); }
580 { throw userError("Need inventory space for blank cheques."); }
570 inventory.slots = inserted.slots;
581 inventory.slots = inserted.slots;
@@ -617,21 +628,24 @@ function writeCheque (world, sessionId, command)
617 if (!pulled.ok)
628 if (!pulled.ok)
618 { throw userError("Not enough unreserved goods in the vault."); }
629 { throw userError("Not enough unreserved goods in the vault."); }
619
630
631 const appearance = world.ecs.get(handle, Component.appearance);
632 const issuerName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim()
633 || "Unknown";
620 const chequeId = randomUUID();
634 const chequeId = randomUUID();
621 const reservedStack = {
635 const reservedStack = {
622 itemId: pulled.taken.itemId,
636 itemId: pulled.taken.itemId,
623 quantity: pulled.taken.quantity,
637 quantity: pulled.taken.quantity,
624 origin: pulled.taken.origin ?? null,
638 origins: normalizeOrigins(pulled.taken),
625 instance: pulled.taken.instance ?? null,
639 instance: pulled.taken.instance ?? null,
626 chequeId
640 chequeId
627 };
641 };
628 vault.slots = pulled.slots;
642 vault.slots = pulled.slots;
629 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
643 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
630
644
631 const filled = {
645 const filled = attachOrigins({
632 itemId: ItemId.filledCheque,
646 itemId: ItemId.filledCheque,
633 quantity: 1,
647 quantity: 1,
634 origin: null,
648 origins: [{ origin: writtenOrigin(issuerName), quantity: 1 }],
635 instance: {
649 instance: {
636 kind: "filled-cheque",
650 kind: "filled-cheque",
637 chequeId,
651 chequeId,
@@ -641,7 +655,7 @@ function writeCheque (world, sessionId, command)
641 reservedInstance: pulled.taken.instance ?? null,
655 reservedInstance: pulled.taken.instance ?? null,
642 createdAt: Date.now()
656 createdAt: Date.now()
643 }
657 }
644 };
658 });
645 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
659 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
646 inventory.slots = blankTaken.slots;
660 inventory.slots = blankTaken.slots;
647 if (!inventory.slots[slotIndex])
661 if (!inventory.slots[slotIndex])
@@ -699,13 +713,12 @@ function redeemCheque (world, sessionId, command)
699 reservedStack = release.stack;
713 reservedStack = release.stack;
700 }
714 }
701
715
702 const inserted = insertStackGrowable(vault.slots, {
716 const inserted = insertStackGrowable(vault.slots, attachOrigins({
703 itemId: reservedStack.itemId,
717 itemId: reservedStack.itemId,
704 quantity: reservedStack.quantity,
718 quantity: reservedStack.quantity,
705 origin: reservedStack.origin ?? null,
719 origins: normalizeOrigins(reservedStack),
706 origins: reservedStack.origins ?? null,
707 instance: reservedStack.instance ?? null
720 instance: reservedStack.instance ?? null
708 }, goodsDef);
721 }), goodsDef);
709 if (!inserted.ok)
722 if (!inserted.ok)
710 {
723 {
711 inventory.slots[slotIndex] = chequeTaken.taken;
724 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -776,10 +789,10 @@ function writeLetter (world, sessionId, command)
776 const body = normalizeLetterBody(command.body);
789 const body = normalizeLetterBody(command.body);
777 const appearance = world.ecs.get(handle, Component.appearance);
790 const appearance = world.ecs.get(handle, Component.appearance);
778 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
791 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
779 const letterStack = {
792 const letterStack = attachOrigins({
780 itemId: ItemId.letter,
793 itemId: ItemId.letter,
781 quantity: 1,
794 quantity: 1,
782 origin: null,
795 origins: [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }],
783 instance: {
796 instance: {
784 kind: "letter",
797 kind: "letter",
785 letterId: randomUUID(),
798 letterId: randomUUID(),
@@ -789,7 +802,7 @@ function writeLetter (world, sessionId, command)
789 opened: true,
802 opened: true,
790 writtenAt: Date.now()
803 writtenAt: Date.now()
791 }
804 }
792 };
805 });
793 if (slot.quantity <= 1)
806 if (slot.quantity <= 1)
794 {
807 {
795 inventory.slots[slotIndex] = letterStack;
808 inventory.slots[slotIndex] = letterStack;
@@ -822,6 +835,8 @@ function editLetter (world, sessionId, command)
822 body: normalizeLetterBody(command.body),
835 body: normalizeLetterBody(command.body),
823 writtenAt: Date.now()
836 writtenAt: Date.now()
824 };
837 };
838 slot.origins = [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }];
839 delete slot.origin;
825 return { events: [], private: bagView(world.ecs, handle) };
840 return { events: [], private: bagView(world.ecs, handle) };
826}
841}
827
842
server/src/market/service.js +26 −14
@@ -11,8 +11,9 @@ import {
11 11 cloneStack
12 12 } from "../../../shared/items/inventory.js";
13 13 import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
14 import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
14 import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
15 15 import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
16 import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
16 17 import {
17 18 MARKET_ORDER_MAX_AGE_MS,
18 19 buyFilledLetterBody,
@@ -330,6 +331,7 @@ export class MarketService
330 331 { throw userError("That order is no longer open."); }
331 332 if (Number(order.characterId) !== Number(characterId))
332 333 { throw userError("That is not your order."); }
334 const clerkName = pickExchangeClerk();
333 335 this.#returnEscrowByPigeon(order, {
334 336 letterBody: orderCancelledLetterBody({
335 337 side: order.side,
@@ -340,8 +342,9 @@ export class MarketService
340 342 : (isFilledChequeEscrow(order.escrowStack)
341 343 ? "written cheque"
342 344 : (itemDefinition(order.itemId)?.displayName ?? "item")),
343 clerkName: pickExchangeClerk()
345 clerkName
344 346 }),
347 clerkName,
345 348 now
346 349 });
347 350 this.stateDb.updateMarketOrder({
@@ -359,6 +362,7 @@ export class MarketService
359 362 #expireOrder (order, now)
360 363 {
361 364 const events = [];
365 const clerkName = pickExchangeClerk();
362 366 this.#returnEscrowByPigeon(order, {
363 367 letterBody: orderExpiredLetterBody({
364 368 side: order.side,
@@ -369,8 +373,9 @@ export class MarketService
369 373 : (isFilledChequeEscrow(order.escrowStack)
370 374 ? "written cheque"
371 375 : (itemDefinition(order.itemId)?.displayName ?? "item")),
372 clerkName: pickExchangeClerk()
376 clerkName
373 377 }),
378 clerkName,
374 379 now
375 380 });
376 381 this.stateDb.updateMarketOrder({
@@ -519,7 +524,7 @@ export class MarketService
519 524 quantity: fillQty,
520 525 unitPrice,
521 526 clerkName: clerk
522 }));
527 }), clerk);
523 528 }
524 529 else
525 530 {
@@ -532,7 +537,7 @@ export class MarketService
532 537 quantity: fillQty,
533 538 unitPrice,
534 539 clerkName: clerk
535 }));
540 }), clerk);
536 541 }
537 542
538 543 events.push({
@@ -608,7 +613,7 @@ export class MarketService
608 613 return { ok: true };
609 614 }
610 615
611 #returnEscrowByPigeon (order, { letterBody, now })
616 #returnEscrowByPigeon (order, { letterBody, clerkName = null, now })
612 617 {
613 618 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
614 619 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
@@ -625,29 +630,36 @@ export class MarketService
625 630 stack: cloneStack(order.escrowStack)
626 631 });
627 632 }
628 this.#dispatchBankLetter(order.characterId, origin, letterBody);
633 this.#dispatchBankLetter(order.characterId, origin, letterBody, clerkName);
629 634 void now;
630 635 }
631 636
632 #dispatchBankLetter (characterId, origin, body)
637 #dispatchBankLetter (characterId, origin, body, clerkName = null)
633 638 {
634 639 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
635 const signed = /Signed,\n([^\n]+)\nCentral Exchange/.exec(trimmed);
636 const clerkName = signed?.[1] ?? pickExchangeClerk();
637 const stack = {
640 const name = String(clerkName || pickExchangeClerk()).trim() || pickExchangeClerk();
641 const stack = attachOrigins({
638 642 itemId: ItemId.letter,
639 643 quantity: 1,
644 origins: [{ origin: writtenOrigin(name), quantity: 1 }],
640 645 instance: {
641 646 kind: "letter",
642 647 letterId: randomUUID(),
643 648 authorCharacterId: 0,
644 authorDisplayName: clerkName,
649 authorDisplayName: name,
650 authorOrganization: CENTRAL_EXCHANGE_ORG,
651 centralExchange: true,
645 652 body: trimmed,
646 653 opened: false,
647 654 writtenAt: Date.now()
648 655 }
649 };
650 this.#dispatchBankCargo(characterId, origin, { kind: "item", stack });
656 });
657 this.simulation.courier.dispatchSystemLetter({
658 characterId,
659 originTileX: origin.tileX,
660 originTileY: origin.tileY,
661 stack
662 });
651 663 }
652 664
653 665 #dispatchBankCargo (characterId, origin, cargo)
@@ -11,8 +11,9 @@ import {
11 cloneStack
11 cloneStack
12} from "../../../shared/items/inventory.js";
12} from "../../../shared/items/inventory.js";
13import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
13import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
14import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
14import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
15import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
15import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
16import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
16import {
17import {
17 MARKET_ORDER_MAX_AGE_MS,
18 MARKET_ORDER_MAX_AGE_MS,
18 buyFilledLetterBody,
19 buyFilledLetterBody,
@@ -330,6 +331,7 @@ export class MarketService
330 { throw userError("That order is no longer open."); }
331 { throw userError("That order is no longer open."); }
331 if (Number(order.characterId) !== Number(characterId))
332 if (Number(order.characterId) !== Number(characterId))
332 { throw userError("That is not your order."); }
333 { throw userError("That is not your order."); }
334 const clerkName = pickExchangeClerk();
333 this.#returnEscrowByPigeon(order, {
335 this.#returnEscrowByPigeon(order, {
334 letterBody: orderCancelledLetterBody({
336 letterBody: orderCancelledLetterBody({
335 side: order.side,
337 side: order.side,
@@ -340,8 +342,9 @@ export class MarketService
340 : (isFilledChequeEscrow(order.escrowStack)
342 : (isFilledChequeEscrow(order.escrowStack)
341 ? "written cheque"
343 ? "written cheque"
342 : (itemDefinition(order.itemId)?.displayName ?? "item")),
344 : (itemDefinition(order.itemId)?.displayName ?? "item")),
343 clerkName: pickExchangeClerk()
345 clerkName
344 }),
346 }),
347 clerkName,
345 now
348 now
346 });
349 });
347 this.stateDb.updateMarketOrder({
350 this.stateDb.updateMarketOrder({
@@ -359,6 +362,7 @@ export class MarketService
359 #expireOrder (order, now)
362 #expireOrder (order, now)
360 {
363 {
361 const events = [];
364 const events = [];
365 const clerkName = pickExchangeClerk();
362 this.#returnEscrowByPigeon(order, {
366 this.#returnEscrowByPigeon(order, {
363 letterBody: orderExpiredLetterBody({
367 letterBody: orderExpiredLetterBody({
364 side: order.side,
368 side: order.side,
@@ -369,8 +373,9 @@ export class MarketService
369 : (isFilledChequeEscrow(order.escrowStack)
373 : (isFilledChequeEscrow(order.escrowStack)
370 ? "written cheque"
374 ? "written cheque"
371 : (itemDefinition(order.itemId)?.displayName ?? "item")),
375 : (itemDefinition(order.itemId)?.displayName ?? "item")),
372 clerkName: pickExchangeClerk()
376 clerkName
373 }),
377 }),
378 clerkName,
374 now
379 now
375 });
380 });
376 this.stateDb.updateMarketOrder({
381 this.stateDb.updateMarketOrder({
@@ -519,7 +524,7 @@ export class MarketService
519 quantity: fillQty,
524 quantity: fillQty,
520 unitPrice,
525 unitPrice,
521 clerkName: clerk
526 clerkName: clerk
522 }));
527 }), clerk);
523 }
528 }
524 else
529 else
525 {
530 {
@@ -532,7 +537,7 @@ export class MarketService
532 quantity: fillQty,
537 quantity: fillQty,
533 unitPrice,
538 unitPrice,
534 clerkName: clerk
539 clerkName: clerk
535 }));
540 }), clerk);
536 }
541 }
537
542
538 events.push({
543 events.push({
@@ -608,7 +613,7 @@ export class MarketService
608 return { ok: true };
613 return { ok: true };
609 }
614 }
610
615
611 #returnEscrowByPigeon (order, { letterBody, now })
616 #returnEscrowByPigeon (order, { letterBody, clerkName = null, now })
612 {
617 {
613 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
618 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
614 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
619 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
@@ -625,29 +630,36 @@ export class MarketService
625 stack: cloneStack(order.escrowStack)
630 stack: cloneStack(order.escrowStack)
626 });
631 });
627 }
632 }
628 this.#dispatchBankLetter(order.characterId, origin, letterBody);
633 this.#dispatchBankLetter(order.characterId, origin, letterBody, clerkName);
629 void now;
634 void now;
630 }
635 }
631
636
632 #dispatchBankLetter (characterId, origin, body)
637 #dispatchBankLetter (characterId, origin, body, clerkName = null)
633 {
638 {
634 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
639 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
635 const signed = /Signed,\n([^\n]+)\nCentral Exchange/.exec(trimmed);
640 const name = String(clerkName || pickExchangeClerk()).trim() || pickExchangeClerk();
636 const clerkName = signed?.[1] ?? pickExchangeClerk();
641 const stack = attachOrigins({
637 const stack = {
638 itemId: ItemId.letter,
642 itemId: ItemId.letter,
639 quantity: 1,
643 quantity: 1,
644 origins: [{ origin: writtenOrigin(name), quantity: 1 }],
640 instance: {
645 instance: {
641 kind: "letter",
646 kind: "letter",
642 letterId: randomUUID(),
647 letterId: randomUUID(),
643 authorCharacterId: 0,
648 authorCharacterId: 0,
644 authorDisplayName: clerkName,
649 authorDisplayName: name,
650 authorOrganization: CENTRAL_EXCHANGE_ORG,
651 centralExchange: true,
645 body: trimmed,
652 body: trimmed,
646 opened: false,
653 opened: false,
647 writtenAt: Date.now()
654 writtenAt: Date.now()
648 }
655 }
649 };
656 });
650 this.#dispatchBankCargo(characterId, origin, { kind: "item", stack });
657 this.simulation.courier.dispatchSystemLetter({
658 characterId,
659 originTileX: origin.tileX,
660 originTileY: origin.tileY,
661 stack
662 });
651 }
663 }
652
664
653 #dispatchBankCargo (characterId, origin, cargo)
665 #dispatchBankCargo (characterId, origin, cargo)
server/src/persistence/stateDb.js +11 −2
@@ -1,5 +1,6 @@
1 1 import { openDatabase } from "./database.js";
2 2 import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
3 4 import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4 5 import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5 6 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
@@ -273,11 +274,19 @@ export class StateDatabase
273 274 if (!equipment.slots?.offhand)
274 275 {
275 276 equipment.slots = equipment.slots ?? {};
276 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
277 equipment.slots.offhand = attachOrigins({
278 itemId: ItemId.lantern,
279 quantity: 1,
280 origins: [{ origin: godsOrigin(), quantity: 1 }]
281 });
277 282 }
278 283 else
279 284 {
280 const result = insertStack(inventory, { itemId: ItemId.lantern, quantity: 1 }, def);
285 const result = insertStack(inventory, attachOrigins({
286 itemId: ItemId.lantern,
287 quantity: 1,
288 origins: [{ origin: godsOrigin(), quantity: 1 }]
289 }), def);
281 290 if (!result.ok)
282 291 { continue; }
283 292 inventory.splice(0, inventory.length, ...result.slots);
@@ -1,5 +1,6 @@
1import { openDatabase } from "./database.js";
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
6import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
@@ -273,11 +274,19 @@ export class StateDatabase
273 if (!equipment.slots?.offhand)
274 if (!equipment.slots?.offhand)
274 {
275 {
275 equipment.slots = equipment.slots ?? {};
276 equipment.slots = equipment.slots ?? {};
276 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
277 equipment.slots.offhand = attachOrigins({
278 itemId: ItemId.lantern,
279 quantity: 1,
280 origins: [{ origin: godsOrigin(), quantity: 1 }]
281 });
277 }
282 }
278 else
283 else
279 {
284 {
280 const result = insertStack(inventory, { itemId: ItemId.lantern, quantity: 1 }, def);
285 const result = insertStack(inventory, attachOrigins({
286 itemId: ItemId.lantern,
287 quantity: 1,
288 origins: [{ origin: godsOrigin(), quantity: 1 }]
289 }), def);
281 if (!result.ok)
290 if (!result.ok)
282 { continue; }
291 { continue; }
283 inventory.splice(0, inventory.length, ...result.slots);
292 inventory.splice(0, inventory.length, ...result.slots);
server/src/quests/runtime.js +12 −2
@@ -1,5 +1,6 @@
1 1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 2 import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
3 4 import { itemDefinition } from "../../../shared/definitions/items.js";
4 5 import { applySkillXp } from "../../../shared/skills/state.js";
5 6 import { skillLevel } from "../../../shared/definitions/skills.js";
@@ -388,13 +389,22 @@ export class QuestRuntime
388 389 { continue; }
389 390 const def = itemDefinition(effect.itemId | 0);
390 391 const quantity = Math.max(1, Number(effect.quantity) || 1);
391 const result = insertStack(bag.inventory, { itemId: effect.itemId | 0, quantity }, def);
392 const stack = attachOrigins({
393 itemId: effect.itemId | 0,
394 quantity,
395 origins: [{ origin: godsOrigin(), quantity }]
396 });
397 const result = insertStack(bag.inventory, stack, def);
392 398 bag.inventory = result.slots;
393 399 if (result.remainder > 0)
394 400 {
395 401 const vaultResult = insertStackGrowable(
396 402 bag.vault,
397 { itemId: effect.itemId | 0, quantity: result.remainder },
403 attachOrigins({
404 itemId: effect.itemId | 0,
405 quantity: result.remainder,
406 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
407 }),
398 408 def
399 409 );
400 410 bag.vault = vaultResult.slots;
@@ -1,5 +1,6 @@
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
2import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { itemDefinition } from "../../../shared/definitions/items.js";
4import { applySkillXp } from "../../../shared/skills/state.js";
5import { applySkillXp } from "../../../shared/skills/state.js";
5import { skillLevel } from "../../../shared/definitions/skills.js";
6import { skillLevel } from "../../../shared/definitions/skills.js";
@@ -388,13 +389,22 @@ export class QuestRuntime
388 { continue; }
389 { continue; }
389 const def = itemDefinition(effect.itemId | 0);
390 const def = itemDefinition(effect.itemId | 0);
390 const quantity = Math.max(1, Number(effect.quantity) || 1);
391 const quantity = Math.max(1, Number(effect.quantity) || 1);
391 const result = insertStack(bag.inventory, { itemId: effect.itemId | 0, quantity }, def);
392 const stack = attachOrigins({
393 itemId: effect.itemId | 0,
394 quantity,
395 origins: [{ origin: godsOrigin(), quantity }]
396 });
397 const result = insertStack(bag.inventory, stack, def);
392 bag.inventory = result.slots;
398 bag.inventory = result.slots;
393 if (result.remainder > 0)
399 if (result.remainder > 0)
394 {
400 {
395 const vaultResult = insertStackGrowable(
401 const vaultResult = insertStackGrowable(
396 bag.vault,
402 bag.vault,
397 { itemId: effect.itemId | 0, quantity: result.remainder },
403 attachOrigins({
404 itemId: effect.itemId | 0,
405 quantity: result.remainder,
406 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
407 }),
398 def
408 def
399 );
409 );
400 bag.vault = vaultResult.slots;
410 bag.vault = vaultResult.slots;
server/src/shop/service.js +6 −5
@@ -6,7 +6,8 @@ import {
6 6 attachOrigins,
7 7 mergeOriginLists,
8 8 normalizeOrigins,
9 splitOrigins
9 splitOrigins,
10 shopOrigin
10 11 } from "../../../shared/items/origin.js";
11 12 import {
12 13 addCoinsToSlots,
@@ -227,7 +228,7 @@ function boughtLot (shop, itemId)
227 228 { return null; }
228 229 return {
229 230 quantity,
230 origins: [{ origin: null, quantity }]
231 origins: [{ origin: shopOrigin("a shop"), quantity }]
231 232 };
232 233 }
233 234 const quantity = Math.max(0, raw.quantity | 0 || 0);
@@ -237,7 +238,7 @@ function boughtLot (shop, itemId)
237 238 const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);
238 239 if (originQty < quantity)
239 240 {
240 origins.push({ origin: null, quantity: quantity - originQty });
241 origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty });
241 242 }
242 243 return { quantity, origins };
243 244 }
@@ -485,11 +486,11 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
485 486 }
486 487 else
487 488 {
488 const shopOrigin = { kind: ItemOriginKind.shop, displayName };
489 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
489 490 stack = attachOrigins({
490 491 itemId: buyItemId,
491 492 quantity: qty,
492 origins: [{ origin: shopOrigin, quantity: qty }]
493 origins: [{ origin: shopOriginEntry, quantity: qty }]
493 494 });
494 495 }
495 496 const added = insertStack(paid.slots, stack, def);
@@ -6,7 +6,8 @@ import {
6 attachOrigins,
6 attachOrigins,
7 mergeOriginLists,
7 mergeOriginLists,
8 normalizeOrigins,
8 normalizeOrigins,
9 splitOrigins
9 splitOrigins,
10 shopOrigin
10} from "../../../shared/items/origin.js";
11} from "../../../shared/items/origin.js";
11import {
12import {
12 addCoinsToSlots,
13 addCoinsToSlots,
@@ -227,7 +228,7 @@ function boughtLot (shop, itemId)
227 { return null; }
228 { return null; }
228 return {
229 return {
229 quantity,
230 quantity,
230 origins: [{ origin: null, quantity }]
231 origins: [{ origin: shopOrigin("a shop"), quantity }]
231 };
232 };
232 }
233 }
233 const quantity = Math.max(0, raw.quantity | 0 || 0);
234 const quantity = Math.max(0, raw.quantity | 0 || 0);
@@ -237,7 +238,7 @@ function boughtLot (shop, itemId)
237 const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);
238 const originQty = origins.reduce((sum, entry) => sum + entry.quantity, 0);
238 if (originQty < quantity)
239 if (originQty < quantity)
239 {
240 {
240 origins.push({ origin: null, quantity: quantity - originQty });
241 origins.push({ origin: shopOrigin("a shop"), quantity: quantity - originQty });
241 }
242 }
242 return { quantity, origins };
243 return { quantity, origins };
243}
244}
@@ -485,11 +486,11 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
485 }
486 }
486 else
487 else
487 {
488 {
488 const shopOrigin = { kind: ItemOriginKind.shop, displayName };
489 const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
489 stack = attachOrigins({
490 stack = attachOrigins({
490 itemId: buyItemId,
491 itemId: buyItemId,
491 quantity: qty,
492 quantity: qty,
492 origins: [{ origin: shopOrigin, quantity: qty }]
493 origins: [{ origin: shopOriginEntry, quantity: qty }]
493 });
494 });
494 }
495 }
495 const added = insertStack(paid.slots, stack, def);
496 const added = insertStack(paid.slots, stack, def);
server/src/simulation/simulation.js +26 −2
@@ -30,6 +30,7 @@ import { WorkerMessage } from "./protocol.js";
30 30 import { replicaNeededForOwnedChunks } from "./workerWorld.js";
31 31 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
32 32 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
33 import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
33 34 import { mobComponents } from "./spawners.js";
34 35 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
35 36 import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
@@ -1636,6 +1637,15 @@ export class Simulation
1636 1637 targetEntityId: event.entityId
1637 1638 });
1638 1639 }
1640 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1641 || "someone";
1642 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1643 const killerName = attackerRecord?.appearance
1644 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1645 || attackerRecord.appearance.displayName
1646 || "someone")
1647 : "someone";
1648 const corpseOrigin = lootOrigin(victimName, killerName);
1639 1649 const result = this.workers[record.workerId].call({
1640 1650 type: WorkerMessage.spawnCorpseDrops,
1641 1651 characterId: event.characterId,
@@ -1643,8 +1653,22 @@ export class Simulation
1643 1653 tileY: event.tileY,
1644 1654 now: this.now,
1645 1655 drops: [
1646 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
1647 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
1656 {
1657 groundItemId: this.nextGroundItemId++,
1658 stack: attachOrigins({
1659 itemId: ItemId.bones,
1660 quantity: 1,
1661 origins: [{ origin: corpseOrigin, quantity: 1 }]
1662 })
1663 },
1664 {
1665 groundItemId: this.nextGroundItemId++,
1666 stack: attachOrigins({
1667 itemId: ItemId.skull,
1668 quantity: 1,
1669 origins: [{ origin: corpseOrigin, quantity: 1 }]
1670 })
1671 }
1648 1672 ]
1649 1673 });
1650 1674 const events = [event];
@@ -30,6 +30,7 @@ import { WorkerMessage } from "./protocol.js";
30import { replicaNeededForOwnedChunks } from "./workerWorld.js";
30import { replicaNeededForOwnedChunks } from "./workerWorld.js";
31import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
31import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
32import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
32import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
33import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
33import { mobComponents } from "./spawners.js";
34import { mobComponents } from "./spawners.js";
34import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
35import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
35import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
36import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
@@ -1636,6 +1637,15 @@ export class Simulation
1636 targetEntityId: event.entityId
1637 targetEntityId: event.entityId
1637 });
1638 });
1638 }
1639 }
1640 const victimName = `${record.appearance?.firstName ?? "someone"} ${record.appearance?.lastName ?? ""}`.trim()
1641 || "someone";
1642 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
1643 const killerName = attackerRecord?.appearance
1644 ? (`${attackerRecord.appearance.firstName ?? ""} ${attackerRecord.appearance.lastName ?? ""}`.trim()
1645 || attackerRecord.appearance.displayName
1646 || "someone")
1647 : "someone";
1648 const corpseOrigin = lootOrigin(victimName, killerName);
1639 const result = this.workers[record.workerId].call({
1649 const result = this.workers[record.workerId].call({
1640 type: WorkerMessage.spawnCorpseDrops,
1650 type: WorkerMessage.spawnCorpseDrops,
1641 characterId: event.characterId,
1651 characterId: event.characterId,
@@ -1643,8 +1653,22 @@ export class Simulation
1643 tileY: event.tileY,
1653 tileY: event.tileY,
1644 now: this.now,
1654 now: this.now,
1645 drops: [
1655 drops: [
1646 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
1656 {
1647 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
1657 groundItemId: this.nextGroundItemId++,
1658 stack: attachOrigins({
1659 itemId: ItemId.bones,
1660 quantity: 1,
1661 origins: [{ origin: corpseOrigin, quantity: 1 }]
1662 })
1663 },
1664 {
1665 groundItemId: this.nextGroundItemId++,
1666 stack: attachOrigins({
1667 itemId: ItemId.skull,
1668 quantity: 1,
1669 origins: [{ origin: corpseOrigin, quantity: 1 }]
1670 })
1671 }
1648 ]
1672 ]
1649 });
1673 });
1650 const events = [event];
1674 const events = [event];
server/src/simulation/workerWorld.js +2 −1
@@ -483,11 +483,12 @@ export class WorkerWorld
483 483 const events = [];
484 484 for (const drop of message.drops ?? [])
485 485 {
486 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
486 487 const item = {
487 488 groundItemId: drop.groundItemId,
488 489 tileX: message.tileX,
489 490 tileY: message.tileY,
490 stack: { itemId: drop.itemId, quantity: 1 },
491 stack,
491 492 droppedAt: message.now,
492 493 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
493 494 source: "player-death",
@@ -483,11 +483,12 @@ export class WorkerWorld
483 const events = [];
483 const events = [];
484 for (const drop of message.drops ?? [])
484 for (const drop of message.drops ?? [])
485 {
485 {
486 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
486 const item = {
487 const item = {
487 groundItemId: drop.groundItemId,
488 groundItemId: drop.groundItemId,
488 tileX: message.tileX,
489 tileX: message.tileX,
489 tileY: message.tileY,
490 tileY: message.tileY,
490 stack: { itemId: drop.itemId, quantity: 1 },
491 stack,
491 droppedAt: message.now,
492 droppedAt: message.now,
492 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
493 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
493 source: "player-death",
494 source: "player-death",
server/src/skills/service.js +4 −0
@@ -79,6 +79,10 @@ export function awardDamageHealthXp (ecs, targetHandle, damage)
79 79 const amount = Math.max(0, Math.floor(Number(damage) || 0));
80 80 if (!amount)
81 81 { return null; }
82 const health = ecs.get(targetHandle, Component.health);
83 // Lethal hits grant no Health XP — only damage you survive counts.
84 if (!health || (health.current | 0) <= 0)
85 { return null; }
82 86 const character = ecs.get(targetHandle, Component.character);
83 87 if (!character)
84 88 { return null; }
@@ -79,6 +79,10 @@ export function awardDamageHealthXp (ecs, targetHandle, damage)
79 const amount = Math.max(0, Math.floor(Number(damage) || 0));
79 const amount = Math.max(0, Math.floor(Number(damage) || 0));
80 if (!amount)
80 if (!amount)
81 { return null; }
81 { return null; }
82 const health = ecs.get(targetHandle, Component.health);
83 // Lethal hits grant no Health XP — only damage you survive counts.
84 if (!health || (health.current | 0) <= 0)
85 { return null; }
82 const character = ecs.get(targetHandle, Component.character);
86 const character = ecs.get(targetHandle, Component.character);
83 if (!character)
87 if (!character)
84 { return null; }
88 { return null; }
server/tests/alchemy.test.js +53 −0
@@ -213,6 +213,59 @@ test("cauldron clear / close after insert does not consume ingredients", () =>
213 213 { harness.close(); }
214 214 });
215 215
216 test("cauldron rejects a fifth distinct ingredient type", () =>
217 {
218 const harness = makeSimulation({ workerCount: 1 });
219 try
220 {
221 placeCauldron(harness.worldDb, 8, 8);
222 harness.simulation.reloadWorld();
223 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
224 const inventory = emptySlots();
225 inventory[0] = { itemId: ItemId.thyme, quantity: 1 };
226 inventory[1] = { itemId: ItemId.mint, quantity: 1 };
227 inventory[2] = { itemId: ItemId.lavender, quantity: 1 };
228 inventory[3] = { itemId: ItemId.nettle, quantity: 1 };
229 inventory[4] = { itemId: ItemId.rosemary, quantity: 1 };
230 inventory[5] = { itemId: ItemId.glassBottle, quantity: 1 };
231 harness.stateDb.saveBag(character.character_id, {
232 inventory,
233 equipment: emptyEquipment(),
234 vault: [],
235 vaultReserved: []
236 });
237 harness.simulation.spawnCharacter(1, character);
238 const cid = character.character_id;
239
240 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
241 harness.simulation.step();
242 for (const itemId of [ItemId.thyme, ItemId.mint, ItemId.lavender, ItemId.nettle])
243 {
244 harness.simulation.enqueue(1, {
245 type: "cauldron-insert",
246 characterId: cid,
247 itemId,
248 quantity: 1
249 });
250 }
251 const four = harness.simulation.step();
252 assert.equal(four.events.some((event) => event.type === "command-error"), false, JSON.stringify(four.events));
253
254 harness.simulation.enqueue(1, {
255 type: "cauldron-insert",
256 characterId: cid,
257 itemId: ItemId.rosemary,
258 quantity: 1
259 });
260 const fifth = harness.simulation.step();
261 const error = fifth.events.find((event) => event.type === "command-error");
262 assert.ok(error, JSON.stringify(fifth.events));
263 assert.match(error.message, /at most 4/i);
264 }
265 finally
266 { harness.close(); }
267 });
268
216 269 test("drinking a lesser health tonic applies health regen", () =>
217 270 {
218 271 const harness = makeSimulation({ workerCount: 1 });
@@ -213,6 +213,59 @@ test("cauldron clear / close after insert does not consume ingredients", () =>
213 { harness.close(); }
213 { harness.close(); }
214});
214});
215
215
216test("cauldron rejects a fifth distinct ingredient type", () =>
217{
218 const harness = makeSimulation({ workerCount: 1 });
219 try
220 {
221 placeCauldron(harness.worldDb, 8, 8);
222 harness.simulation.reloadWorld();
223 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
224 const inventory = emptySlots();
225 inventory[0] = { itemId: ItemId.thyme, quantity: 1 };
226 inventory[1] = { itemId: ItemId.mint, quantity: 1 };
227 inventory[2] = { itemId: ItemId.lavender, quantity: 1 };
228 inventory[3] = { itemId: ItemId.nettle, quantity: 1 };
229 inventory[4] = { itemId: ItemId.rosemary, quantity: 1 };
230 inventory[5] = { itemId: ItemId.glassBottle, quantity: 1 };
231 harness.stateDb.saveBag(character.character_id, {
232 inventory,
233 equipment: emptyEquipment(),
234 vault: [],
235 vaultReserved: []
236 });
237 harness.simulation.spawnCharacter(1, character);
238 const cid = character.character_id;
239
240 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
241 harness.simulation.step();
242 for (const itemId of [ItemId.thyme, ItemId.mint, ItemId.lavender, ItemId.nettle])
243 {
244 harness.simulation.enqueue(1, {
245 type: "cauldron-insert",
246 characterId: cid,
247 itemId,
248 quantity: 1
249 });
250 }
251 const four = harness.simulation.step();
252 assert.equal(four.events.some((event) => event.type === "command-error"), false, JSON.stringify(four.events));
253
254 harness.simulation.enqueue(1, {
255 type: "cauldron-insert",
256 characterId: cid,
257 itemId: ItemId.rosemary,
258 quantity: 1
259 });
260 const fifth = harness.simulation.step();
261 const error = fifth.events.find((event) => event.type === "command-error");
262 assert.ok(error, JSON.stringify(fifth.events));
263 assert.match(error.message, /at most 4/i);
264 }
265 finally
266 { harness.close(); }
267});
268
216test("drinking a lesser health tonic applies health regen", () =>
269test("drinking a lesser health tonic applies health regen", () =>
217{
270{
218 const harness = makeSimulation({ workerCount: 1 });
271 const harness = makeSimulation({ workerCount: 1 });
server/tests/coins.test.js +2 −0
@@ -27,6 +27,8 @@ test("coin stacks split above max stack size", () =>
27 27 assert.equal(stacks.length, 2);
28 28 assert.equal(stacks[0].quantity, COIN_MAX_STACK);
29 29 assert.equal(stacks[1].quantity, 1);
30 assert.equal(stacks[0].origins?.[0]?.origin?.kind, "minted");
31 assert.equal(stacks[1].origins?.[0]?.origin?.kind, "minted");
30 32 });
31 33
32 34 test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
@@ -27,6 +27,8 @@ test("coin stacks split above max stack size", () =>
27 assert.equal(stacks.length, 2);
27 assert.equal(stacks.length, 2);
28 assert.equal(stacks[0].quantity, COIN_MAX_STACK);
28 assert.equal(stacks[0].quantity, COIN_MAX_STACK);
29 assert.equal(stacks[1].quantity, 1);
29 assert.equal(stacks[1].quantity, 1);
30 assert.equal(stacks[0].origins?.[0]?.origin?.kind, "minted");
31 assert.equal(stacks[1].origins?.[0]?.origin?.kind, "minted");
30});
32});
31
33
32test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
34test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
server/tests/combat.test.js +36 −0
@@ -920,6 +920,42 @@ test("taking damage awards Health XP equal to damage dealt", () =>
920 920 }
921 921 });
922 922
923 test("lethal damage awards no Health XP", () =>
924 {
925 const harness = makeSimulation({ workerCount: 1 });
926 const random = Math.random;
927 Math.random = () => 0;
928 try
929 {
930 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
931 const playerId = harness.simulation.spawnCharacter(1, character);
932 const ratId = harness.simulation.spawnEntity(mobComponents({
933 mobTypeId: MobId.rat,
934 tileX: 9,
935 tileY: 8
936 }));
937 const worker = harness.simulation.workers[0];
938 const playerHandle = worker.world.ecs.handleOf(playerId);
939 const health = worker.world.ecs.get(playerHandle, Component.health);
940 health.current = 1;
941 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
942 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
943 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
944 const hit = events.find((event) => event.type === "combat-hit");
945 assert.ok(hit);
946 assert.ok(hit.damage >= 1);
947 assert.equal(hit.health, 0);
948 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
949 assert.equal(updated, undefined);
950 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
951 }
952 finally
953 {
954 Math.random = random;
955 harness.close();
956 }
957 });
958
923 959 test("dodging a hit awards Agility XP equal to avoided damage", () =>
924 960 {
925 961 const harness = makeSimulation({ workerCount: 1 });
@@ -920,6 +920,42 @@ test("taking damage awards Health XP equal to damage dealt", () =>
920 }
920 }
921});
921});
922
922
923test("lethal damage awards no Health XP", () =>
924{
925 const harness = makeSimulation({ workerCount: 1 });
926 const random = Math.random;
927 Math.random = () => 0;
928 try
929 {
930 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
931 const playerId = harness.simulation.spawnCharacter(1, character);
932 const ratId = harness.simulation.spawnEntity(mobComponents({
933 mobTypeId: MobId.rat,
934 tileX: 9,
935 tileY: 8
936 }));
937 const worker = harness.simulation.workers[0];
938 const playerHandle = worker.world.ecs.handleOf(playerId);
939 const health = worker.world.ecs.get(playerHandle, Component.health);
940 health.current = 1;
941 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
942 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
943 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
944 const hit = events.find((event) => event.type === "combat-hit");
945 assert.ok(hit);
946 assert.ok(hit.damage >= 1);
947 assert.equal(hit.health, 0);
948 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
949 assert.equal(updated, undefined);
950 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
951 }
952 finally
953 {
954 Math.random = random;
955 harness.close();
956 }
957});
958
923test("dodging a hit awards Agility XP equal to avoided damage", () =>
959test("dodging a hit awards Agility XP equal to avoided damage", () =>
924{
960{
925 const harness = makeSimulation({ workerCount: 1 });
961 const harness = makeSimulation({ workerCount: 1 });
server/tests/courier.test.js +4 −1
@@ -178,7 +178,10 @@ test("logging in after offline bank deposits sends a bank resting notice by pige
178 178 const receiverBag = harness.simulation.bagOf(receiverId);
179 179 const letterSlot = receiverBag.inventory.find((slot) => slot?.itemId === ItemId.letter);
180 180 assert.ok(letterSlot);
181 assert.match(letterSlot.instance.body, /Signed,\nThe Bank/);
181 assert.equal(letterSlot.instance.authorDisplayName, "The Bank");
182 assert.equal(letterSlot.origins?.[0]?.origin?.verb, "Written");
183 assert.equal(letterSlot.origins?.[0]?.origin?.displayName, "The Bank");
184 assert.doesNotMatch(letterSlot.instance.body, /Signed,/);
182 185 }
183 186 finally
184 187 { harness.close(); }
@@ -178,7 +178,10 @@ test("logging in after offline bank deposits sends a bank resting notice by pige
178 const receiverBag = harness.simulation.bagOf(receiverId);
178 const receiverBag = harness.simulation.bagOf(receiverId);
179 const letterSlot = receiverBag.inventory.find((slot) => slot?.itemId === ItemId.letter);
179 const letterSlot = receiverBag.inventory.find((slot) => slot?.itemId === ItemId.letter);
180 assert.ok(letterSlot);
180 assert.ok(letterSlot);
181 assert.match(letterSlot.instance.body, /Signed,\nThe Bank/);
181 assert.equal(letterSlot.instance.authorDisplayName, "The Bank");
182 assert.equal(letterSlot.origins?.[0]?.origin?.verb, "Written");
183 assert.equal(letterSlot.origins?.[0]?.origin?.displayName, "The Bank");
184 assert.doesNotMatch(letterSlot.instance.body, /Signed,/);
182 }
185 }
183 finally
186 finally
184 { harness.close(); }
187 { harness.close(); }
server/tests/letters.test.js +8 −0
@@ -28,6 +28,14 @@ test("writing paper creates an opened letter only the author can edit", () =>
28 28 assert.equal(after.inventory[letterSlot].instance.authorCharacterId, character.character_id);
29 29 assert.equal(after.inventory[letterSlot].instance.body, "Hello from Ada");
30 30 assert.equal(after.inventory[letterSlot].instance.authorDisplayName, "Ada Writer");
31 assert.equal(
32 after.inventory[letterSlot].origins?.[0]?.origin?.verb,
33 "Written"
34 );
35 assert.equal(
36 after.inventory[letterSlot].origins?.[0]?.origin?.displayName,
37 "Ada Writer"
38 );
31 39 assert.equal(after.inventory[letterSlot].instance.opened, true);
32 40 assert.equal(
33 41 after.inventory.filter((slot) => slot?.itemId === ItemId.paper)
@@ -28,6 +28,14 @@ test("writing paper creates an opened letter only the author can edit", () =>
28 assert.equal(after.inventory[letterSlot].instance.authorCharacterId, character.character_id);
28 assert.equal(after.inventory[letterSlot].instance.authorCharacterId, character.character_id);
29 assert.equal(after.inventory[letterSlot].instance.body, "Hello from Ada");
29 assert.equal(after.inventory[letterSlot].instance.body, "Hello from Ada");
30 assert.equal(after.inventory[letterSlot].instance.authorDisplayName, "Ada Writer");
30 assert.equal(after.inventory[letterSlot].instance.authorDisplayName, "Ada Writer");
31 assert.equal(
32 after.inventory[letterSlot].origins?.[0]?.origin?.verb,
33 "Written"
34 );
35 assert.equal(
36 after.inventory[letterSlot].origins?.[0]?.origin?.displayName,
37 "Ada Writer"
38 );
31 assert.equal(after.inventory[letterSlot].instance.opened, true);
39 assert.equal(after.inventory[letterSlot].instance.opened, true);
32 assert.equal(
40 assert.equal(
33 after.inventory.filter((slot) => slot?.itemId === ItemId.paper)
41 after.inventory.filter((slot) => slot?.itemId === ItemId.paper)
server/tests/marketplace.test.js +42 −14
@@ -4,6 +4,8 @@ import { ItemId } from "../../shared/definitions/items.js";
4 4 import { BlockType } from "../../shared/definitions/tiles.js";
5 5 import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
6 6 import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js";
7 import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";
8 import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";
7 9 import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
8 10 import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
9 11 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
@@ -148,24 +150,29 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
148 150 const buyerBagNow = harness.simulation.bagOf(buyerId);
149 151 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
150 152
151 // Advance courier flight until pigeons deliver to bank.
153 // Coins go to bank; letter goes to the online seller's inventory.
152 154 for (let i = 0; i < 500; i++)
153 155 {
154 156 harness.advance(1000);
155 157 harness.simulation.step();
156 158 const sellerVault = harness.stateDb.getBag(seller.character_id);
159 const sellerBag = harness.simulation.bagOf(sellerId);
157 160 const coins = countCoinsInSlots(sellerVault.vault ?? []);
158 const hasLetter = (sellerVault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
159 if (coins >= 20 && hasLetter)
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)
160 164 {
161 const letter = (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
162 assert.match(letter.instance.body, /Central Exchange/);
163 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);
164 171 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
165 172 return;
166 173 }
167 174 }
168 assert.fail("Seller did not receive coins and letter in vault");
175 assert.fail("Seller did not receive coins in vault and letter");
169 176 }
170 177 finally
171 178 { harness.close(); }
@@ -216,23 +223,25 @@ test("orders older than one month auto-cancel and return escrow to bank", () =>
216 223 harness.advance(1000);
217 224 harness.simulation.step();
218 225 const vault = harness.stateDb.getBag(character.character_id);
226 const bag = harness.simulation.bagOf(1);
219 227 const coins = countCoinsInSlots(vault.vault ?? []);
220 const hasLetter = (vault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
221 if (coins >= 10 && hasLetter)
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)
222 231 {
223 const letter = (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
224 232 assert.match(letter.instance.body, /one month/i);
225 assert.match(letter.instance.body, /Central Exchange/);
233 assert.doesNotMatch(letter.instance.body, /Signed,/);
234 assert.equal(letter.instance.authorOrganization, "Central Exchange");
226 235 return;
227 236 }
228 237 }
229 assert.fail("Expired order did not return escrow letter to bank");
238 assert.fail("Expired order did not return escrow letter");
230 239 }
231 240 finally
232 241 { harness.close(); }
233 242 });
234 243
235 test("exchange letter copy mentions Central Exchange staff signature", () =>
244 test("exchange letter instance carries Central Exchange signature fields", () =>
236 245 {
237 246 const body = soldLetterBody({
238 247 itemName: "Apple",
@@ -240,6 +249,25 @@ test("exchange letter copy mentions Central Exchange staff signature", () =>
240 249 unitPrice: 5,
241 250 clerkName: "Bobby Pennies"
242 251 });
243 assert.match(body, /Bobby Pennies/);
244 assert.match(body, /Central Exchange/);
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
269 test("written origin labels match letter author", () =>
270 {
271 assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
272 assert.equal(CraftOriginVerb.written, "Written");
245 273 });
@@ -4,6 +4,8 @@ import { ItemId } from "../../shared/definitions/items.js";
4import { BlockType } from "../../shared/definitions/tiles.js";
4import { BlockType } from "../../shared/definitions/tiles.js";
5import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
5import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
6import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.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";
7import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
9import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
8import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
10import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
9import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
11import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
@@ -148,24 +150,29 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
148 const buyerBagNow = harness.simulation.bagOf(buyerId);
150 const buyerBagNow = harness.simulation.bagOf(buyerId);
149 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
151 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
150
152
151 // Advance courier flight until pigeons deliver to bank.
153 // Coins go to bank; letter goes to the online seller's inventory.
152 for (let i = 0; i < 500; i++)
154 for (let i = 0; i < 500; i++)
153 {
155 {
154 harness.advance(1000);
156 harness.advance(1000);
155 harness.simulation.step();
157 harness.simulation.step();
156 const sellerVault = harness.stateDb.getBag(seller.character_id);
158 const sellerVault = harness.stateDb.getBag(seller.character_id);
159 const sellerBag = harness.simulation.bagOf(sellerId);
157 const coins = countCoinsInSlots(sellerVault.vault ?? []);
160 const coins = countCoinsInSlots(sellerVault.vault ?? []);
158 const hasLetter = (sellerVault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
161 const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
159 if (coins >= 20 && hasLetter)
162 ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
163 if (coins >= 20 && letter)
160 {
164 {
161 const letter = (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
162 assert.match(letter.instance.body, /Central Exchange/);
163 assert.match(letter.instance.body, /sold|filled|proceeds/i);
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);
164 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
171 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
165 return;
172 return;
166 }
173 }
167 }
174 }
168 assert.fail("Seller did not receive coins and letter in vault");
175 assert.fail("Seller did not receive coins in vault and letter");
169 }
176 }
170 finally
177 finally
171 { harness.close(); }
178 { harness.close(); }
@@ -216,23 +223,25 @@ test("orders older than one month auto-cancel and return escrow to bank", () =>
216 harness.advance(1000);
223 harness.advance(1000);
217 harness.simulation.step();
224 harness.simulation.step();
218 const vault = harness.stateDb.getBag(character.character_id);
225 const vault = harness.stateDb.getBag(character.character_id);
226 const bag = harness.simulation.bagOf(1);
219 const coins = countCoinsInSlots(vault.vault ?? []);
227 const coins = countCoinsInSlots(vault.vault ?? []);
220 const hasLetter = (vault.vault ?? []).some((slot) => slot?.itemId === ItemId.letter);
228 const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
221 if (coins >= 10 && hasLetter)
229 ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
230 if (coins >= 10 && letter)
222 {
231 {
223 const letter = (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
224 assert.match(letter.instance.body, /one month/i);
232 assert.match(letter.instance.body, /one month/i);
225 assert.match(letter.instance.body, /Central Exchange/);
233 assert.doesNotMatch(letter.instance.body, /Signed,/);
234 assert.equal(letter.instance.authorOrganization, "Central Exchange");
226 return;
235 return;
227 }
236 }
228 }
237 }
229 assert.fail("Expired order did not return escrow letter to bank");
238 assert.fail("Expired order did not return escrow letter");
230 }
239 }
231 finally
240 finally
232 { harness.close(); }
241 { harness.close(); }
233});
242});
234
243
235test("exchange letter copy mentions Central Exchange staff signature", () =>
244test("exchange letter instance carries Central Exchange signature fields", () =>
236{
245{
237 const body = soldLetterBody({
246 const body = soldLetterBody({
238 itemName: "Apple",
247 itemName: "Apple",
@@ -240,6 +249,25 @@ test("exchange letter copy mentions Central Exchange staff signature", () =>
240 unitPrice: 5,
249 unitPrice: 5,
241 clerkName: "Bobby Pennies"
250 clerkName: "Bobby Pennies"
242 });
251 });
243 assert.match(body, /Bobby Pennies/);
252 assert.doesNotMatch(body, /Signed,/);
244 assert.match(body, /Central Exchange/);
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");
245});
273});
server/tests/origins.test.js +17 −0
@@ -8,9 +8,12 @@ import {
8 8 lootOrigin,
9 9 craftOrigin,
10 10 craftOriginVerbForStation,
11 royalTreasuryOrigin,
12 ROYAL_TREASURY_ORIGIN_LABEL,
11 13 originLabel,
12 14 formatOriginBreakdown,
13 15 mergeOriginLists,
16 normalizeOrigins,
14 17 splitOrigins
15 18 } from "../../shared/items/origin.js";
16 19 import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
@@ -45,6 +48,20 @@ test("loot origins name the mob and killer", () =>
45 48 }), "Dropped by Rat, slain by Ada Miner.");
46 49 });
47 50
51 test("all coins are minted by the Royal Treasury", () =>
52 {
53 assert.equal(originLabel(royalTreasuryOrigin()), ROYAL_TREASURY_ORIGIN_LABEL);
54 assert.equal(formatOriginBreakdown({
55 itemId: ItemId.coins,
56 quantity: 25
57 }), ROYAL_TREASURY_ORIGIN_LABEL);
58 assert.deepEqual(normalizeOrigins({
59 itemId: ItemId.coins,
60 quantity: 10,
61 origins: [{ origin: craftOrigin(CraftOriginVerb.made, "Ada"), quantity: 10 }]
62 }), [{ origin: royalTreasuryOrigin(), quantity: 10 }]);
63 });
64
48 65 test("craft origins use station verbs", () =>
49 66 {
50 67 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
@@ -8,9 +8,12 @@ import {
8 lootOrigin,
8 lootOrigin,
9 craftOrigin,
9 craftOrigin,
10 craftOriginVerbForStation,
10 craftOriginVerbForStation,
11 royalTreasuryOrigin,
12 ROYAL_TREASURY_ORIGIN_LABEL,
11 originLabel,
13 originLabel,
12 formatOriginBreakdown,
14 formatOriginBreakdown,
13 mergeOriginLists,
15 mergeOriginLists,
16 normalizeOrigins,
14 splitOrigins
17 splitOrigins
15} from "../../shared/items/origin.js";
18} from "../../shared/items/origin.js";
16import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
19import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
@@ -45,6 +48,20 @@ test("loot origins name the mob and killer", () =>
45 }), "Dropped by Rat, slain by Ada Miner.");
48 }), "Dropped by Rat, slain by Ada Miner.");
46});
49});
47
50
51test("all coins are minted by the Royal Treasury", () =>
52{
53 assert.equal(originLabel(royalTreasuryOrigin()), ROYAL_TREASURY_ORIGIN_LABEL);
54 assert.equal(formatOriginBreakdown({
55 itemId: ItemId.coins,
56 quantity: 25
57 }), ROYAL_TREASURY_ORIGIN_LABEL);
58 assert.deepEqual(normalizeOrigins({
59 itemId: ItemId.coins,
60 quantity: 10,
61 origins: [{ origin: craftOrigin(CraftOriginVerb.made, "Ada"), quantity: 10 }]
62 }), [{ origin: royalTreasuryOrigin(), quantity: 10 }]);
63});
64
48test("craft origins use station verbs", () =>
65test("craft origins use station verbs", () =>
49{
66{
50 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
67 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
shared/bounty/pricing.js +1 −4
@@ -18,9 +18,6 @@ export function bountyPayoutLetterBody ({ killerName, victimName, amountCopper }
18 18 return [
19 19 `Dear ${killer},`,
20 20 "",
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`,
22 "",
23 "Signed,",
24 "Bounty Office"
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`
25 22 ].join("\n");
26 23 }
@@ -18,9 +18,6 @@ export function bountyPayoutLetterBody ({ killerName, victimName, amountCopper }
18 return [
18 return [
19 `Dear ${killer},`,
19 `Dear ${killer},`,
20 "",
20 "",
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`,
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`
22 "",
23 "Signed,",
24 "Bounty Office"
25 ].join("\n");
22 ].join("\n");
26}
23}
shared/courier/bankNotice.js +3 −15
@@ -1,17 +1,8 @@
1 1 import { stackDisplayLabel } from "../definitions/items.js";
2 2 import { originLabel } from "../items/origin.js";
3 import { BANK_LETTER_AUTHOR, isBankRestNoticeLetter, isCentralExchangeLetter } from "./systemLetters.js";
3 4
4 export const BANK_LETTER_AUTHOR = "The Bank";
5
6 export function isCentralExchangeLetter (instance)
7 {
8 return instance?.kind === "letter" && /Central Exchange/.test(String(instance.body ?? ""));
9 }
10
11 export function isBankRestNoticeLetter (instance)
12 {
13 return instance?.kind === "letter" && instance.bankRestNotice === true;
14 }
5 export { BANK_LETTER_AUTHOR, isBankRestNoticeLetter, isCentralExchangeLetter };
15 6
16 7 /** @param {{ quantity: number, itemName: string, sourceName: string }[]} lines */
17 8 export function bankRestNoticeLetterBody ({ playerName, lines })
@@ -24,10 +15,7 @@ export function bankRestNoticeLetterBody ({ playerName, lines })
24 15 `Dear ${name},`,
25 16 "While you have been resting, the following items were deposited into your bank account:",
26 17 "",
27 bodyLines,
28 "",
29 "Signed,",
30 BANK_LETTER_AUTHOR
18 bodyLines
31 19 ].join("\n");
32 20 }
33 21
@@ -1,17 +1,8 @@
1import { stackDisplayLabel } from "../definitions/items.js";
1import { stackDisplayLabel } from "../definitions/items.js";
2import { originLabel } from "../items/origin.js";
2import { originLabel } from "../items/origin.js";
3import { BANK_LETTER_AUTHOR, isBankRestNoticeLetter, isCentralExchangeLetter } from "./systemLetters.js";
3
4
4export const BANK_LETTER_AUTHOR = "The Bank";
5export { BANK_LETTER_AUTHOR, isBankRestNoticeLetter, isCentralExchangeLetter };
5
6export function isCentralExchangeLetter (instance)
7{
8 return instance?.kind === "letter" && /Central Exchange/.test(String(instance.body ?? ""));
9}
10
11export function isBankRestNoticeLetter (instance)
12{
13 return instance?.kind === "letter" && instance.bankRestNotice === true;
14}
15
6
16/** @param {{ quantity: number, itemName: string, sourceName: string }[]} lines */
7/** @param {{ quantity: number, itemName: string, sourceName: string }[]} lines */
17export function bankRestNoticeLetterBody ({ playerName, lines })
8export function bankRestNoticeLetterBody ({ playerName, lines })
@@ -24,10 +15,7 @@ export function bankRestNoticeLetterBody ({ playerName, lines })
24 `Dear ${name},`,
15 `Dear ${name},`,
25 "While you have been resting, the following items were deposited into your bank account:",
16 "While you have been resting, the following items were deposited into your bank account:",
26 "",
17 "",
27 bodyLines,
18 bodyLines
28 "",
29 "Signed,",
30 BANK_LETTER_AUTHOR
31 ].join("\n");
19 ].join("\n");
32}
20}
33
21
shared/courier/systemLetters.js added +31 −0
@@ -0,0 +1,31 @@
1 /** Shared helpers for system-authored letters (CE, bank, bounty, …). */
2
3 export const CENTRAL_EXCHANGE_ORG = "Central Exchange";
4 export const BANK_LETTER_AUTHOR = "The Bank";
5 export const BOUNTY_OFFICE_AUTHOR = "Bounty Office";
6
7 export function isCentralExchangeLetter (instance)
8 {
9 if (instance?.kind !== "letter")
10 { return false; }
11 if (instance.centralExchange === true)
12 { return true; }
13 return instance.authorOrganization === CENTRAL_EXCHANGE_ORG;
14 }
15
16 export function isBankRestNoticeLetter (instance)
17 {
18 return instance?.kind === "letter" && instance.bankRestNotice === true;
19 }
20
21 /**
22 * Format the UI "Signed:" block. Optional organization is a second line under the name.
23 * @param {{ authorDisplayName?: string, authorOrganization?: string|null }} instance
24 * @param {string} [fallbackName]
25 */
26 export function formatLetterSignature (instance, fallbackName = "Unknown")
27 {
28 const name = String(instance?.authorDisplayName ?? "").trim() || fallbackName;
29 const org = String(instance?.authorOrganization ?? "").trim();
30 return org ? `Signed:\n${name}\n${org}` : `Signed:\n${name}`;
31 }
@@ -0,0 +1,31 @@
1/** Shared helpers for system-authored letters (CE, bank, bounty, …). */
2
3export const CENTRAL_EXCHANGE_ORG = "Central Exchange";
4export const BANK_LETTER_AUTHOR = "The Bank";
5export const BOUNTY_OFFICE_AUTHOR = "Bounty Office";
6
7export function isCentralExchangeLetter (instance)
8{
9 if (instance?.kind !== "letter")
10 { return false; }
11 if (instance.centralExchange === true)
12 { return true; }
13 return instance.authorOrganization === CENTRAL_EXCHANGE_ORG;
14}
15
16export function isBankRestNoticeLetter (instance)
17{
18 return instance?.kind === "letter" && instance.bankRestNotice === true;
19}
20
21/**
22 * Format the UI "Signed:" block. Optional organization is a second line under the name.
23 * @param {{ authorDisplayName?: string, authorOrganization?: string|null }} instance
24 * @param {string} [fallbackName]
25 */
26export function formatLetterSignature (instance, fallbackName = "Unknown")
27{
28 const name = String(instance?.authorDisplayName ?? "").trim() || fallbackName;
29 const org = String(instance?.authorOrganization ?? "").trim();
30 return org ? `Signed:\n${name}\n${org}` : `Signed:\n${name}`;
31}
shared/definitions/alchemy.js +2 −1
@@ -27,7 +27,8 @@ export const CAULDRON_EMPTY_FLAVOR = "The cauldron is empty";
27 27
28 28 /**
29 29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
30 * A potion may never use more than 4 unique ingredients (ratio units).
30 * A potion may never use more than 4 unique ingredients (one per cauldron slot).
31 * Stage ingredients in the top slots before the first brew step; slots lock until Bottle.
31 32 * Step `insert` is once per ingredient addition; quantity lives in `ingredients`.
32 33 */
33 34 export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
@@ -27,7 +27,8 @@ export const CAULDRON_EMPTY_FLAVOR = "The cauldron is empty";
27
27
28/**
28/**
29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
30 * A potion may never use more than 4 unique ingredients (ratio units).
30 * A potion may never use more than 4 unique ingredients (one per cauldron slot).
31 * Stage ingredients in the top slots before the first brew step; slots lock until Bottle.
31 * Step `insert` is once per ingredient addition; quantity lives in `ingredients`.
32 * Step `insert` is once per ingredient addition; quantity lives in `ingredients`.
32 */
33 */
33export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
34export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
shared/items/inventory.js +13 −3
@@ -227,7 +227,12 @@ export function consumeFillCharge (slots, slotIndex, {
227 227 if (returnEmptyItemId)
228 228 {
229 229 const emptyDef = itemDefinition(returnEmptyItemId);
230 const inserted = insertStack(next, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
230 const emptyStack = attachOrigins({
231 itemId: returnEmptyItemId,
232 quantity: 1,
233 origins: normalizeOrigins(source)
234 });
235 const inserted = insertStack(next, emptyStack, emptyDef);
231 236 if (!inserted.ok || inserted.remainder > 0)
232 237 { return { ok: false, reason: "space" }; }
233 238 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
@@ -259,7 +264,12 @@ function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainde
259 264 if (!returnEmptyItemId)
260 265 { return { ok: true, slots: peeled.slots, exhausted: true }; }
261 266 const emptyDef = itemDefinition(returnEmptyItemId);
262 const inserted = insertStack(peeled.slots, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
267 const emptyStack = attachOrigins({
268 itemId: returnEmptyItemId,
269 quantity: 1,
270 origins: normalizeOrigins(peeled.taken)
271 });
272 const inserted = insertStack(peeled.slots, emptyStack, emptyDef);
263 273 if (!inserted.ok || inserted.remainder > 0)
264 274 { return { ok: false }; }
265 275 return { ok: true, slots: inserted.slots, exhausted: true };
@@ -445,7 +455,7 @@ export function addCoinsToSlots (slots, amount, { growable = false } = {})
445 455 while (remaining > 0)
446 456 {
447 457 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
448 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
458 const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def);
449 459 next = result.slots;
450 460 const placed = chunk - (result.remainder ?? 0);
451 461 remaining -= placed;
@@ -227,7 +227,12 @@ export function consumeFillCharge (slots, slotIndex, {
227 if (returnEmptyItemId)
227 if (returnEmptyItemId)
228 {
228 {
229 const emptyDef = itemDefinition(returnEmptyItemId);
229 const emptyDef = itemDefinition(returnEmptyItemId);
230 const inserted = insertStack(next, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
230 const emptyStack = attachOrigins({
231 itemId: returnEmptyItemId,
232 quantity: 1,
233 origins: normalizeOrigins(source)
234 });
235 const inserted = insertStack(next, emptyStack, emptyDef);
231 if (!inserted.ok || inserted.remainder > 0)
236 if (!inserted.ok || inserted.remainder > 0)
232 { return { ok: false, reason: "space" }; }
237 { return { ok: false, reason: "space" }; }
233 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
238 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
@@ -259,7 +264,12 @@ function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainde
259 if (!returnEmptyItemId)
264 if (!returnEmptyItemId)
260 { return { ok: true, slots: peeled.slots, exhausted: true }; }
265 { return { ok: true, slots: peeled.slots, exhausted: true }; }
261 const emptyDef = itemDefinition(returnEmptyItemId);
266 const emptyDef = itemDefinition(returnEmptyItemId);
262 const inserted = insertStack(peeled.slots, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
267 const emptyStack = attachOrigins({
268 itemId: returnEmptyItemId,
269 quantity: 1,
270 origins: normalizeOrigins(peeled.taken)
271 });
272 const inserted = insertStack(peeled.slots, emptyStack, emptyDef);
263 if (!inserted.ok || inserted.remainder > 0)
273 if (!inserted.ok || inserted.remainder > 0)
264 { return { ok: false }; }
274 { return { ok: false }; }
265 return { ok: true, slots: inserted.slots, exhausted: true };
275 return { ok: true, slots: inserted.slots, exhausted: true };
@@ -445,7 +455,7 @@ export function addCoinsToSlots (slots, amount, { growable = false } = {})
445 while (remaining > 0)
455 while (remaining > 0)
446 {
456 {
447 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
457 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
448 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
458 const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def);
449 next = result.slots;
459 next = result.slots;
450 const placed = chunk - (result.remainder ?? 0);
460 const placed = chunk - (result.remainder ?? 0);
451 remaining -= placed;
461 remaining -= placed;
shared/items/origin.js +47 −3
@@ -4,9 +4,21 @@ export const ItemOriginKind = Object.freeze({
4 4 gathered: "gathered",
5 5 gods: "gods",
6 6 loot: "loot",
7 minted: "minted",
7 8 unknown: "unknown"
8 9 });
9 10
11 /** Must match `ItemId.coins` — kept here to avoid a circular import with definitions/items.js. */
12 const COINS_ITEM_ID = 8;
13
14 export const ROYAL_TREASURY_ORIGIN_LABEL = "Minted by the Royal Treasury";
15
16 /** Official coinage origin for every coin stack. */
17 export function royalTreasuryOrigin ()
18 {
19 return { kind: ItemOriginKind.minted };
20 }
21
10 22 /** Gather verbs for origin labels (`Mined by …`, `Felled by …`). */
11 23 export const GatherOriginVerb = Object.freeze({
12 24 mined: "Mined",
@@ -26,7 +38,9 @@ export const CraftOriginVerb = Object.freeze({
26 38 assembled: "Assembled",
27 39 made: "Made",
28 40 brewed: "Brewed",
29 mixed: "Mixed"
41 mixed: "Mixed",
42 written: "Written",
43 issued: "Issued"
30 44 });
31 45
32 46 /** @type {Readonly<Record<string, string>>} */
@@ -88,6 +102,12 @@ export function originLabel (origin, { lowercaseVerb = false } = {})
88 102 }
89 103 if (origin.kind === ItemOriginKind.gods)
90 104 { return "Received from the gods"; }
105 if (origin.kind === ItemOriginKind.minted)
106 {
107 return lowercaseVerb
108 ? ROYAL_TREASURY_ORIGIN_LABEL.charAt(0).toLowerCase() + ROYAL_TREASURY_ORIGIN_LABEL.slice(1)
109 : ROYAL_TREASURY_ORIGIN_LABEL;
110 }
91 111 return "unknown origin";
92 112 }
93 113
@@ -107,6 +127,27 @@ export function craftOrigin (verb, displayName)
107 127 };
108 128 }
109 129
130 /** Letters / recipe paper: `Written by <signer>`. */
131 export function writtenOrigin (displayName)
132 {
133 return craftOrigin(CraftOriginVerb.written, displayName);
134 }
135
136 /** Blank cheques from the bank: `Issued by The Bank`. */
137 export function bankIssuedOrigin (displayName = "The Bank")
138 {
139 return craftOrigin(CraftOriginVerb.issued, displayName);
140 }
141
142 /** NPC catalog purchase origin (`Bought from …`). */
143 export function shopOrigin (displayName)
144 {
145 return {
146 kind: ItemOriginKind.shop,
147 displayName: String(displayName ?? "").trim() || "a shop"
148 };
149 }
150
110 151 /** Build a gathered-item origin (`Mined by Ada`, …). */
111 152 export function gatherOrigin (verb, displayName)
112 153 {
@@ -139,6 +180,11 @@ export function normalizeOrigins (stack)
139 180 if (!stack)
140 181 { return []; }
141 182 const qty = Math.max(0, Math.floor(Number(stack.quantity) || 0));
183 if (qty <= 0)
184 { return []; }
185 // All coinage is royal mint — ignore any other origin metadata on the stack.
186 if ((stack.itemId | 0) === COINS_ITEM_ID)
187 { return [{ origin: royalTreasuryOrigin(), quantity: qty }]; }
142 188 if (Array.isArray(stack.origins) && stack.origins.length)
143 189 {
144 190 return stack.origins.map((entry) => ({
@@ -146,8 +192,6 @@ export function normalizeOrigins (stack)
146 192 quantity: Math.max(0, Math.floor(Number(entry.quantity) || 0))
147 193 })).filter((entry) => entry.quantity > 0);
148 194 }
149 if (qty <= 0)
150 { return []; }
151 195 return [{ origin: stack.origin ?? null, quantity: qty }];
152 196 }
153 197
@@ -4,9 +4,21 @@ export const ItemOriginKind = Object.freeze({
4 gathered: "gathered",
4 gathered: "gathered",
5 gods: "gods",
5 gods: "gods",
6 loot: "loot",
6 loot: "loot",
7 minted: "minted",
7 unknown: "unknown"
8 unknown: "unknown"
8});
9});
9
10
11/** Must match `ItemId.coins` — kept here to avoid a circular import with definitions/items.js. */
12const COINS_ITEM_ID = 8;
13
14export const ROYAL_TREASURY_ORIGIN_LABEL = "Minted by the Royal Treasury";
15
16/** Official coinage origin for every coin stack. */
17export function royalTreasuryOrigin ()
18{
19 return { kind: ItemOriginKind.minted };
20}
21
10/** Gather verbs for origin labels (`Mined by …`, `Felled by …`). */
22/** Gather verbs for origin labels (`Mined by …`, `Felled by …`). */
11export const GatherOriginVerb = Object.freeze({
23export const GatherOriginVerb = Object.freeze({
12 mined: "Mined",
24 mined: "Mined",
@@ -26,7 +38,9 @@ export const CraftOriginVerb = Object.freeze({
26 assembled: "Assembled",
38 assembled: "Assembled",
27 made: "Made",
39 made: "Made",
28 brewed: "Brewed",
40 brewed: "Brewed",
29 mixed: "Mixed"
41 mixed: "Mixed",
42 written: "Written",
43 issued: "Issued"
30});
44});
31
45
32/** @type {Readonly<Record<string, string>>} */
46/** @type {Readonly<Record<string, string>>} */
@@ -88,6 +102,12 @@ export function originLabel (origin, { lowercaseVerb = false } = {})
88 }
102 }
89 if (origin.kind === ItemOriginKind.gods)
103 if (origin.kind === ItemOriginKind.gods)
90 { return "Received from the gods"; }
104 { return "Received from the gods"; }
105 if (origin.kind === ItemOriginKind.minted)
106 {
107 return lowercaseVerb
108 ? ROYAL_TREASURY_ORIGIN_LABEL.charAt(0).toLowerCase() + ROYAL_TREASURY_ORIGIN_LABEL.slice(1)
109 : ROYAL_TREASURY_ORIGIN_LABEL;
110 }
91 return "unknown origin";
111 return "unknown origin";
92}
112}
93
113
@@ -107,6 +127,27 @@ export function craftOrigin (verb, displayName)
107 };
127 };
108}
128}
109
129
130/** Letters / recipe paper: `Written by <signer>`. */
131export function writtenOrigin (displayName)
132{
133 return craftOrigin(CraftOriginVerb.written, displayName);
134}
135
136/** Blank cheques from the bank: `Issued by The Bank`. */
137export function bankIssuedOrigin (displayName = "The Bank")
138{
139 return craftOrigin(CraftOriginVerb.issued, displayName);
140}
141
142/** NPC catalog purchase origin (`Bought from …`). */
143export function shopOrigin (displayName)
144{
145 return {
146 kind: ItemOriginKind.shop,
147 displayName: String(displayName ?? "").trim() || "a shop"
148 };
149}
150
110/** Build a gathered-item origin (`Mined by Ada`, …). */
151/** Build a gathered-item origin (`Mined by Ada`, …). */
111export function gatherOrigin (verb, displayName)
152export function gatherOrigin (verb, displayName)
112{
153{
@@ -139,6 +180,11 @@ export function normalizeOrigins (stack)
139 if (!stack)
180 if (!stack)
140 { return []; }
181 { return []; }
141 const qty = Math.max(0, Math.floor(Number(stack.quantity) || 0));
182 const qty = Math.max(0, Math.floor(Number(stack.quantity) || 0));
183 if (qty <= 0)
184 { return []; }
185 // All coinage is royal mint — ignore any other origin metadata on the stack.
186 if ((stack.itemId | 0) === COINS_ITEM_ID)
187 { return [{ origin: royalTreasuryOrigin(), quantity: qty }]; }
142 if (Array.isArray(stack.origins) && stack.origins.length)
188 if (Array.isArray(stack.origins) && stack.origins.length)
143 {
189 {
144 return stack.origins.map((entry) => ({
190 return stack.origins.map((entry) => ({
@@ -146,8 +192,6 @@ export function normalizeOrigins (stack)
146 quantity: Math.max(0, Math.floor(Number(entry.quantity) || 0))
192 quantity: Math.max(0, Math.floor(Number(entry.quantity) || 0))
147 })).filter((entry) => entry.quantity > 0);
193 })).filter((entry) => entry.quantity > 0);
148 }
194 }
149 if (qty <= 0)
150 { return []; }
151 return [{ origin: stack.origin ?? null, quantity: qty }];
195 return [{ origin: stack.origin ?? null, quantity: qty }];
152}
196}
153
197
shared/market/exchange.js +8 −17
@@ -38,54 +38,45 @@ export function marketOrderListingFee (unitPrice, quantity)
38 38 return Math.max(1, Math.ceil(notional * MARKET_ORDER_FEE_RATE));
39 39 }
40 40
41 export function exchangeSignature (clerkName)
42 {
43 return `Signed,\n${clerkName}\nCentral Exchange`;
44 }
45
46 41 export function soldLetterBody ({ itemName, quantity, unitPrice, clerkName })
47 42 {
43 void clerkName;
48 44 return [
49 45 `Good news — your sell order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
50 46 "",
51 "The proceeds have been deposited in your bank vault.",
52 "",
53 exchangeSignature(clerkName)
47 "The proceeds have been deposited in your bank vault."
54 48 ].join("\n");
55 49 }
56 50
57 51 export function buyFilledLetterBody ({ itemName, quantity, unitPrice, clerkName })
58 52 {
53 void clerkName;
59 54 return [
60 55 `Your buy order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
61 56 "",
62 "The goods have been deposited in your bank vault.",
63 "",
64 exchangeSignature(clerkName)
57 "The goods have been deposited in your bank vault."
65 58 ].join("\n");
66 59 }
67 60
68 61 export function orderExpiredLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
69 62 {
63 void clerkName;
70 64 const kind = side === "buy" ? "buy" : "sell";
71 65 return [
72 66 `Unfortunately your ${kind} order for ${quantity}× ${itemName} could not be filled within one month.`,
73 67 "",
74 `Your reserved ${escrowLabel} has been returned to your bank.`,
75 "",
76 exchangeSignature(clerkName)
68 `Your reserved ${escrowLabel} has been returned to your bank.`
77 69 ].join("\n");
78 70 }
79 71
80 72 export function orderCancelledLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
81 73 {
74 void clerkName;
82 75 const kind = side === "buy" ? "buy" : "sell";
83 76 return [
84 77 `Your ${kind} order for ${quantity}× ${itemName} was cancelled.`,
85 78 "",
86 `Your reserved ${escrowLabel} has been returned to your bank.`,
87 "",
88 exchangeSignature(clerkName)
79 `Your reserved ${escrowLabel} has been returned to your bank.`
89 80 ].join("\n");
90 81 }
91 82
@@ -38,54 +38,45 @@ export function marketOrderListingFee (unitPrice, quantity)
38 return Math.max(1, Math.ceil(notional * MARKET_ORDER_FEE_RATE));
38 return Math.max(1, Math.ceil(notional * MARKET_ORDER_FEE_RATE));
39}
39}
40
40
41export function exchangeSignature (clerkName)
42{
43 return `Signed,\n${clerkName}\nCentral Exchange`;
44}
45
46export function soldLetterBody ({ itemName, quantity, unitPrice, clerkName })
41export function soldLetterBody ({ itemName, quantity, unitPrice, clerkName })
47{
42{
43 void clerkName;
48 return [
44 return [
49 `Good news — your sell order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
45 `Good news — your sell order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
50 "",
46 "",
51 "The proceeds have been deposited in your bank vault.",
47 "The proceeds have been deposited in your bank vault."
52 "",
53 exchangeSignature(clerkName)
54 ].join("\n");
48 ].join("\n");
55}
49}
56
50
57export function buyFilledLetterBody ({ itemName, quantity, unitPrice, clerkName })
51export function buyFilledLetterBody ({ itemName, quantity, unitPrice, clerkName })
58{
52{
53 void clerkName;
59 return [
54 return [
60 `Your buy order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
55 `Your buy order for ${quantity}× ${itemName} has been filled at ${unitPrice} coins each.`,
61 "",
56 "",
62 "The goods have been deposited in your bank vault.",
57 "The goods have been deposited in your bank vault."
63 "",
64 exchangeSignature(clerkName)
65 ].join("\n");
58 ].join("\n");
66}
59}
67
60
68export function orderExpiredLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
61export function orderExpiredLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
69{
62{
63 void clerkName;
70 const kind = side === "buy" ? "buy" : "sell";
64 const kind = side === "buy" ? "buy" : "sell";
71 return [
65 return [
72 `Unfortunately your ${kind} order for ${quantity}× ${itemName} could not be filled within one month.`,
66 `Unfortunately your ${kind} order for ${quantity}× ${itemName} could not be filled within one month.`,
73 "",
67 "",
74 `Your reserved ${escrowLabel} has been returned to your bank.`,
68 `Your reserved ${escrowLabel} has been returned to your bank.`
75 "",
76 exchangeSignature(clerkName)
77 ].join("\n");
69 ].join("\n");
78}
70}
79
71
80export function orderCancelledLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
72export function orderCancelledLetterBody ({ side, itemName, quantity, escrowLabel, clerkName })
81{
73{
74 void clerkName;
82 const kind = side === "buy" ? "buy" : "sell";
75 const kind = side === "buy" ? "buy" : "sell";
83 return [
76 return [
84 `Your ${kind} order for ${quantity}× ${itemName} was cancelled.`,
77 `Your ${kind} order for ${quantity}× ${itemName} was cancelled.`,
85 "",
78 "",
86 `Your reserved ${escrowLabel} has been returned to your bank.`,
79 `Your reserved ${escrowLabel} has been returned to your bank.`
87 "",
88 exchangeSignature(clerkName)
89 ].join("\n");
80 ].join("\n");
90}
81}
91
82