BlueGit

timfa questward

Exact cheque reservations, goods icon overlay, and 30-day expiry.

Writing a cheque matches vault stacks by full itemId+instance identity, draws the reserved goods at half size on cheque icons, and converts aged cheques into expired stationery while releasing reserved goods.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-09-08 · 2 months ago

Hash
a032151780597780ae6fc24793901e4ec2b01ed7
Parent
d5b670e4
11 files changed +593 −47
client/src/play/inventory.js +11 −2
@@ -3,6 +3,7 @@ import
3 3 itemDefinition,
4 4 itemDescription,
5 5 itemOriginSummary,
6 itemExtraTooltipLines,
6 7 itemAssetPathForStack,
7 8 itemDisplayName,
8 9 formatQuantity,
@@ -12,6 +13,7 @@ import
12 13 } from "/shared/definitions/items.js";
13 14 import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
14 15 import { stackQuantity } from "/shared/items/inventory.js";
16 import { countIdenticalInSlots } from "/shared/items/cheque.js";
15 17 import { formatLetterSignature } from "/shared/courier/systemLetters.js";
16 18 import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
17 19 import { spellDefinition } from "/shared/definitions/spells.js";
@@ -747,7 +749,7 @@ export function initInventory ({
747 749 if (!writeChequeState)
748 750 { return; }
749 751 writeChequeState.vaultSlotIndex = index;
750 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
752 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableMatching(slot);
751 753 document.getElementById("write-cheque-item").textContent =
752 754 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
753 755 const qtyInput = document.getElementById("write-cheque-qty");
@@ -1040,7 +1042,7 @@ export function initInventory ({
1040 1042 writeChequeState.vaultSlotIndex = index;
1041 1043 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
1042 1044 ? 1
1043 : availableOf(slot.itemId);
1045 : availableMatching(slot);
1044 1046 document.getElementById("write-cheque-item").textContent =
1045 1047 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
1046 1048 const qtyInput = document.getElementById("write-cheque-qty");
@@ -1066,6 +1068,11 @@ export function initInventory ({
1066 1068 });
1067 1069 }
1068 1070
1071 function availableMatching (reference)
1072 {
1073 return countIdenticalInSlots(bag.vault ?? [], reference);
1074 }
1075
1069 1076 function availableOf (itemId)
1070 1077 {
1071 1078 let total = 0;
@@ -1102,6 +1109,8 @@ export function initInventory ({
1102 1109 { lines.push(origin); }
1103 1110 if (desc)
1104 1111 { lines.push(desc); }
1112 for (const extra of itemExtraTooltipLines(slot))
1113 { lines.push(extra); }
1105 1114 return lines.join("\n");
1106 1115 }
1107 1116
@@ -3,6 +3,7 @@ import
3 itemDefinition,
3 itemDefinition,
4 itemDescription,
4 itemDescription,
5 itemOriginSummary,
5 itemOriginSummary,
6 itemExtraTooltipLines,
6 itemAssetPathForStack,
7 itemAssetPathForStack,
7 itemDisplayName,
8 itemDisplayName,
8 formatQuantity,
9 formatQuantity,
@@ -12,6 +13,7 @@ import
12} from "/shared/definitions/items.js";
13} from "/shared/definitions/items.js";
13import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
14import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
14import { stackQuantity } from "/shared/items/inventory.js";
15import { stackQuantity } from "/shared/items/inventory.js";
16import { countIdenticalInSlots } from "/shared/items/cheque.js";
15import { formatLetterSignature } from "/shared/courier/systemLetters.js";
17import { formatLetterSignature } from "/shared/courier/systemLetters.js";
16import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
18import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
17import { spellDefinition } from "/shared/definitions/spells.js";
19import { spellDefinition } from "/shared/definitions/spells.js";
@@ -747,7 +749,7 @@ export function initInventory ({
747 if (!writeChequeState)
749 if (!writeChequeState)
748 { return; }
750 { return; }
749 writeChequeState.vaultSlotIndex = index;
751 writeChequeState.vaultSlotIndex = index;
750 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
752 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableMatching(slot);
751 document.getElementById("write-cheque-item").textContent =
753 document.getElementById("write-cheque-item").textContent =
752 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
754 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
753 const qtyInput = document.getElementById("write-cheque-qty");
755 const qtyInput = document.getElementById("write-cheque-qty");
@@ -1040,7 +1042,7 @@ export function initInventory ({
1040 writeChequeState.vaultSlotIndex = index;
1042 writeChequeState.vaultSlotIndex = index;
1041 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
1043 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
1042 ? 1
1044 ? 1
1043 : availableOf(slot.itemId);
1045 : availableMatching(slot);
1044 document.getElementById("write-cheque-item").textContent =
1046 document.getElementById("write-cheque-item").textContent =
1045 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
1047 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
1046 const qtyInput = document.getElementById("write-cheque-qty");
1048 const qtyInput = document.getElementById("write-cheque-qty");
@@ -1066,6 +1068,11 @@ export function initInventory ({
1066 });
1068 });
1067 }
1069 }
1068
1070
1071 function availableMatching (reference)
1072 {
1073 return countIdenticalInSlots(bag.vault ?? [], reference);
1074 }
1075
1069 function availableOf (itemId)
1076 function availableOf (itemId)
1070 {
1077 {
1071 let total = 0;
1078 let total = 0;
@@ -1102,6 +1109,8 @@ export function initInventory ({
1102 { lines.push(origin); }
1109 { lines.push(origin); }
1103 if (desc)
1110 if (desc)
1104 { lines.push(desc); }
1111 { lines.push(desc); }
1112 for (const extra of itemExtraTooltipLines(slot))
1113 { lines.push(extra); }
1105 return lines.join("\n");
1114 return lines.join("\n");
1106 }
1115 }
1107
1116
client/src/render/potionIcon.js +69 −24
@@ -1,6 +1,7 @@
1 1 import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
2 2 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3 3 import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
4 import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
4 5 import
5 6 {
6 7 applyMagentaTintToImageData,
@@ -152,31 +153,80 @@ export function isPotionStack (stack)
152 153 || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
153 154 }
154 155
155 /** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
156 export function applyItemIcon (img, stack, fallbackPath)
156 /** Resolve a stack to a UI icon data URL (tint / potion / framed when needed). */
157 export async function itemIconDataUrl (stack)
157 158 {
158 if (!img)
159 { return; }
160 const path = fallbackPath || itemAssetPathForStack(stack);
161 img.src = path;
159 const path = itemAssetPathForStack(stack);
162 160 const def = itemDefinition(stack?.itemId);
163 161 const frames = def?.frames | 0 || 1;
164 162 if (frames > 1 && itemMaxCharges(def) != null)
165 163 {
166 const frameIndex = chargeSpriteFrameIndex(stack);
167 framedItemIconDataUrl(path, frameIndex, def.framesPerRow ?? 1, frames).then((url) =>
168 {
169 img.src = url;
170 }).catch(() =>
171 {
172 img.src = path;
173 });
174 return;
164 return framedItemIconDataUrl(
165 path,
166 chargeSpriteFrameIndex(stack),
167 def.framesPerRow ?? 1,
168 frames
169 );
175 170 }
176 171 const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
177 172 if (dualTint)
173 { return dualTintedItemIconDataUrl(path, dualTint); }
174 const tint = resolveItemTint(stack, def);
175 if (tint && isPotionStack(stack))
176 { return potionIconDataUrl(stack.instance); }
177 if (tint)
178 { return tintedItemIconDataUrl(path, tint); }
179 return path;
180 }
181
182 /** Cheque paper with reserved goods icon centered at 50% scale. */
183 export async function filledChequeIconDataUrl (chequeStack)
184 {
185 const goods = chequeReservedGoodsStack(chequeStack);
186 const chequePath = itemAssetPathForStack(chequeStack);
187 if (!goods?.itemId)
188 { return chequePath; }
189 const goodsKey = JSON.stringify({
190 itemId: goods.itemId,
191 quantity: goods.quantity,
192 instance: goods.instance
193 });
194 const cacheKey = `cheque|${goodsKey}`;
195 if (urlCache.has(cacheKey))
196 { return urlCache.get(cacheKey); }
197
198 const [chequeImg, goodsUrl] = await Promise.all([
199 loadImage(chequePath),
200 itemIconDataUrl(goods)
201 ]);
202 const goodsImg = await loadImage(goodsUrl);
203 const size = SPRITE_SIZE_PX;
204 const canvas = document.createElement("canvas");
205 canvas.width = size;
206 canvas.height = size;
207 const ctx = canvas.getContext("2d");
208 ctx.imageSmoothingEnabled = false;
209 ctx.clearRect(0, 0, size, size);
210 ctx.drawImage(chequeImg, 0, 0, size, size);
211 const half = size * 0.5;
212 const ox = (size - half) / 2;
213 const oy = (size - half) / 2;
214 ctx.drawImage(goodsImg, 0, 0, goodsImg.width || size, goodsImg.height || size, ox, oy, half, half);
215 const url = canvas.toDataURL("image/png");
216 urlCache.set(cacheKey, url);
217 return url;
218 }
219
220 /** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
221 export function applyItemIcon (img, stack, fallbackPath)
222 {
223 if (!img)
224 { return; }
225 const path = fallbackPath || itemAssetPathForStack(stack);
226 img.src = path;
227 if (isFilledChequeStack(stack))
178 228 {
179 dualTintedItemIconDataUrl(path, dualTint).then((url) =>
229 filledChequeIconDataUrl(stack).then((url) =>
180 230 {
181 231 img.src = url;
182 232 }).catch(() =>
@@ -185,15 +235,10 @@ export function applyItemIcon (img, stack, fallbackPath)
185 235 });
186 236 return;
187 237 }
188 const tint = resolveItemTint(stack, def);
189 if (!tint)
190 { return; }
191 const work = isPotionStack(stack)
192 ? potionIconDataUrl(stack.instance)
193 : tintedItemIconDataUrl(path, tint);
194 work.then((url) =>
238 itemIconDataUrl(stack).then((url) =>
195 239 {
196 img.src = url;
240 if (url !== path)
241 { img.src = url; }
197 242 }).catch(() =>
198 243 {
199 244 img.src = path;
@@ -1,6 +1,7 @@
1import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
1import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
2import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
3import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
4import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
4import
5import
5 {
6 {
6 applyMagentaTintToImageData,
7 applyMagentaTintToImageData,
@@ -152,31 +153,80 @@ export function isPotionStack (stack)
152 || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
153 || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
153}
154}
154
155
155/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
156/** Resolve a stack to a UI icon data URL (tint / potion / framed when needed). */
156export function applyItemIcon (img, stack, fallbackPath)
157export async function itemIconDataUrl (stack)
157{
158{
158 if (!img)
159 const path = itemAssetPathForStack(stack);
159 { return; }
160 const path = fallbackPath || itemAssetPathForStack(stack);
161 img.src = path;
162 const def = itemDefinition(stack?.itemId);
160 const def = itemDefinition(stack?.itemId);
163 const frames = def?.frames | 0 || 1;
161 const frames = def?.frames | 0 || 1;
164 if (frames > 1 && itemMaxCharges(def) != null)
162 if (frames > 1 && itemMaxCharges(def) != null)
165 {
163 {
166 const frameIndex = chargeSpriteFrameIndex(stack);
164 return framedItemIconDataUrl(
167 framedItemIconDataUrl(path, frameIndex, def.framesPerRow ?? 1, frames).then((url) =>
165 path,
168 {
166 chargeSpriteFrameIndex(stack),
169 img.src = url;
167 def.framesPerRow ?? 1,
170 }).catch(() =>
168 frames
171 {
169 );
172 img.src = path;
173 });
174 return;
175 }
170 }
176 const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
171 const dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
177 if (dualTint)
172 if (dualTint)
173 { return dualTintedItemIconDataUrl(path, dualTint); }
174 const tint = resolveItemTint(stack, def);
175 if (tint && isPotionStack(stack))
176 { return potionIconDataUrl(stack.instance); }
177 if (tint)
178 { return tintedItemIconDataUrl(path, tint); }
179 return path;
180}
181
182/** Cheque paper with reserved goods icon centered at 50% scale. */
183export async function filledChequeIconDataUrl (chequeStack)
184{
185 const goods = chequeReservedGoodsStack(chequeStack);
186 const chequePath = itemAssetPathForStack(chequeStack);
187 if (!goods?.itemId)
188 { return chequePath; }
189 const goodsKey = JSON.stringify({
190 itemId: goods.itemId,
191 quantity: goods.quantity,
192 instance: goods.instance
193 });
194 const cacheKey = `cheque|${goodsKey}`;
195 if (urlCache.has(cacheKey))
196 { return urlCache.get(cacheKey); }
197
198 const [chequeImg, goodsUrl] = await Promise.all([
199 loadImage(chequePath),
200 itemIconDataUrl(goods)
201 ]);
202 const goodsImg = await loadImage(goodsUrl);
203 const size = SPRITE_SIZE_PX;
204 const canvas = document.createElement("canvas");
205 canvas.width = size;
206 canvas.height = size;
207 const ctx = canvas.getContext("2d");
208 ctx.imageSmoothingEnabled = false;
209 ctx.clearRect(0, 0, size, size);
210 ctx.drawImage(chequeImg, 0, 0, size, size);
211 const half = size * 0.5;
212 const ox = (size - half) / 2;
213 const oy = (size - half) / 2;
214 ctx.drawImage(goodsImg, 0, 0, goodsImg.width || size, goodsImg.height || size, ox, oy, half, half);
215 const url = canvas.toDataURL("image/png");
216 urlCache.set(cacheKey, url);
217 return url;
218}
219
220/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
221export function applyItemIcon (img, stack, fallbackPath)
222{
223 if (!img)
224 { return; }
225 const path = fallbackPath || itemAssetPathForStack(stack);
226 img.src = path;
227 if (isFilledChequeStack(stack))
178 {
228 {
179 dualTintedItemIconDataUrl(path, dualTint).then((url) =>
229 filledChequeIconDataUrl(stack).then((url) =>
180 {
230 {
181 img.src = url;
231 img.src = url;
182 }).catch(() =>
232 }).catch(() =>
@@ -185,15 +235,10 @@ export function applyItemIcon (img, stack, fallbackPath)
185 });
235 });
186 return;
236 return;
187 }
237 }
188 const tint = resolveItemTint(stack, def);
238 itemIconDataUrl(stack).then((url) =>
189 if (!tint)
190 { return; }
191 const work = isPotionStack(stack)
192 ? potionIconDataUrl(stack.instance)
193 : tintedItemIconDataUrl(path, tint);
194 work.then((url) =>
195 {
239 {
196 img.src = url;
240 if (url !== path)
241 { img.src = url; }
197 }).catch(() =>
242 }).catch(() =>
198 {
243 {
199 img.src = path;
244 img.src = path;
client/src/render/worldView.js +60 −2
@@ -6,6 +6,7 @@ import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRange
6 6 import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7 7 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8 8 import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9 import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
9 10 import
10 11 {
11 12 resolveItemTint,
@@ -2066,13 +2067,14 @@ export class WorldView
2066 2067 item.displayName = payload.displayName;
2067 2068 item.sprite = spriteName;
2068 2069 item.instance = payload.instance ?? null;
2069 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
2070 const stack = { itemId: payload.itemId, instance: payload.instance ?? null, quantity: payload.quantity };
2070 2071 const def = itemDefinition(payload.itemId);
2071 2072 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
2072 2073 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
2073 2074 if (item.object?.renderer && itemMaxCharges(def) != null)
2074 2075 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
2075 2076 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2077 this.#syncGroundChequeOverlay(item, pivot);
2076 2078 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
2077 2079 }
2078 2080
@@ -2081,10 +2083,56 @@ export class WorldView
2081 2083 const item = this.groundItems.get(groundItemId);
2082 2084 if (!item)
2083 2085 { return; }
2086 item.chequeOverlay?.destroy();
2084 2087 item.object?.destroy();
2085 2088 this.groundItems.delete(groundItemId);
2086 2089 }
2087 2090
2091 #syncGroundChequeOverlay (item, pivot)
2092 {
2093 const stack = {
2094 itemId: item.itemId,
2095 instance: item.instance,
2096 quantity: item.quantity
2097 };
2098 const goods = isFilledChequeStack(stack) ? chequeReservedGoodsStack(stack) : null;
2099 if (!goods?.itemId)
2100 {
2101 item.chequeOverlay?.destroy();
2102 item.chequeOverlay = null;
2103 item.chequeOverlayTint = null;
2104 item.chequeOverlayDualTint = null;
2105 return;
2106 }
2107 const goodsPotion = goods.instance?.kind === "potion" ? goods.instance : null;
2108 const goodsSprite = goodsPotion
2109 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, goodsPotion.fillLevel | 0 || 4))}`)
2110 : itemSpriteNameForStack(goods);
2111 const sprite = this.game.images[goodsSprite] ?? this.game.images[itemSpriteName(null)];
2112 if (!sprite)
2113 {
2114 item.chequeOverlay?.destroy();
2115 item.chequeOverlay = null;
2116 return;
2117 }
2118 if (!item.chequeOverlay || item.chequeOverlay.renderer?.sprite !== sprite)
2119 {
2120 item.chequeOverlay?.destroy();
2121 item.chequeOverlay = new GameObject(0, 0, sprite, SORT_BLOCK);
2122 this.scene.addObject(item.chequeOverlay);
2123 }
2124 const goodsDef = itemDefinition(goods.itemId);
2125 item.chequeOverlayDualTint = goodsDef?.iconTintFromTier
2126 ? null
2127 : resolveItemDualTint(goods, goodsDef);
2128 item.chequeOverlayTint = item.chequeOverlayDualTint
2129 ? null
2130 : resolveItemTint(goods, goodsDef);
2131 if (item.chequeOverlay?.renderer && itemMaxCharges(goodsDef) != null)
2132 { item.chequeOverlay.renderer.setSubImage?.(chargeSpriteFrameIndex(goods)); }
2133 this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5);
2134 }
2135
2088 2136 groundItemAtTile (tileX, tileY)
2089 2137 {
2090 2138 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
@@ -2147,6 +2195,8 @@ export class WorldView
2147 2195 {
2148 2196 const pivot = tilePivot(item.tileX, item.tileY, size);
2149 2197 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2198 if (item.chequeOverlay)
2199 { this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); }
2150 2200 }
2151 2201 this.#rebuildAllEdges();
2152 2202 this.#relayoutEditorSpawners();
@@ -3807,9 +3857,17 @@ export class WorldView
3807 3857 if (item?.dualTint)
3808 3858 {
3809 3859 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3860 }
3861 else
3862 { this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); }
3863 if (!item?.chequeOverlay)
3864 { return; }
3865 if (item.chequeOverlayDualTint)
3866 {
3867 this.#syncDualTintLitSprite(item.chequeOverlay, darkness, item.chequeOverlayDualTint);
3810 3868 return;
3811 3869 }
3812 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3870 this.#syncLitSprite(item.chequeOverlay, darkness, 0, false, item.chequeOverlayTint ?? null);
3813 3871 }
3814 3872
3815 3873 #groundTypeAt (tileX, tileY)
@@ -6,6 +6,7 @@ import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRange
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js";
9import
10import
10{
11{
11 resolveItemTint,
12 resolveItemTint,
@@ -2066,13 +2067,14 @@ export class WorldView
2066 item.displayName = payload.displayName;
2067 item.displayName = payload.displayName;
2067 item.sprite = spriteName;
2068 item.sprite = spriteName;
2068 item.instance = payload.instance ?? null;
2069 item.instance = payload.instance ?? null;
2069 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
2070 const stack = { itemId: payload.itemId, instance: payload.instance ?? null, quantity: payload.quantity };
2070 const def = itemDefinition(payload.itemId);
2071 const def = itemDefinition(payload.itemId);
2071 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
2072 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
2072 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
2073 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
2073 if (item.object?.renderer && itemMaxCharges(def) != null)
2074 if (item.object?.renderer && itemMaxCharges(def) != null)
2074 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
2075 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
2075 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2076 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2077 this.#syncGroundChequeOverlay(item, pivot);
2076 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
2078 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
2077 }
2079 }
2078
2080
@@ -2081,10 +2083,56 @@ export class WorldView
2081 const item = this.groundItems.get(groundItemId);
2083 const item = this.groundItems.get(groundItemId);
2082 if (!item)
2084 if (!item)
2083 { return; }
2085 { return; }
2086 item.chequeOverlay?.destroy();
2084 item.object?.destroy();
2087 item.object?.destroy();
2085 this.groundItems.delete(groundItemId);
2088 this.groundItems.delete(groundItemId);
2086 }
2089 }
2087
2090
2091 #syncGroundChequeOverlay (item, pivot)
2092 {
2093 const stack = {
2094 itemId: item.itemId,
2095 instance: item.instance,
2096 quantity: item.quantity
2097 };
2098 const goods = isFilledChequeStack(stack) ? chequeReservedGoodsStack(stack) : null;
2099 if (!goods?.itemId)
2100 {
2101 item.chequeOverlay?.destroy();
2102 item.chequeOverlay = null;
2103 item.chequeOverlayTint = null;
2104 item.chequeOverlayDualTint = null;
2105 return;
2106 }
2107 const goodsPotion = goods.instance?.kind === "potion" ? goods.instance : null;
2108 const goodsSprite = goodsPotion
2109 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, goodsPotion.fillLevel | 0 || 4))}`)
2110 : itemSpriteNameForStack(goods);
2111 const sprite = this.game.images[goodsSprite] ?? this.game.images[itemSpriteName(null)];
2112 if (!sprite)
2113 {
2114 item.chequeOverlay?.destroy();
2115 item.chequeOverlay = null;
2116 return;
2117 }
2118 if (!item.chequeOverlay || item.chequeOverlay.renderer?.sprite !== sprite)
2119 {
2120 item.chequeOverlay?.destroy();
2121 item.chequeOverlay = new GameObject(0, 0, sprite, SORT_BLOCK);
2122 this.scene.addObject(item.chequeOverlay);
2123 }
2124 const goodsDef = itemDefinition(goods.itemId);
2125 item.chequeOverlayDualTint = goodsDef?.iconTintFromTier
2126 ? null
2127 : resolveItemDualTint(goods, goodsDef);
2128 item.chequeOverlayTint = item.chequeOverlayDualTint
2129 ? null
2130 : resolveItemTint(goods, goodsDef);
2131 if (item.chequeOverlay?.renderer && itemMaxCharges(goodsDef) != null)
2132 { item.chequeOverlay.renderer.setSubImage?.(chargeSpriteFrameIndex(goods)); }
2133 this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5);
2134 }
2135
2088 groundItemAtTile (tileX, tileY)
2136 groundItemAtTile (tileX, tileY)
2089 {
2137 {
2090 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
2138 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
@@ -2147,6 +2195,8 @@ export class WorldView
2147 {
2195 {
2148 const pivot = tilePivot(item.tileX, item.tileY, size);
2196 const pivot = tilePivot(item.tileX, item.tileY, size);
2149 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2197 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2198 if (item.chequeOverlay)
2199 { this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); }
2150 }
2200 }
2151 this.#rebuildAllEdges();
2201 this.#rebuildAllEdges();
2152 this.#relayoutEditorSpawners();
2202 this.#relayoutEditorSpawners();
@@ -3807,9 +3857,17 @@ export class WorldView
3807 if (item?.dualTint)
3857 if (item?.dualTint)
3808 {
3858 {
3809 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3859 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3860 }
3861 else
3862 { this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); }
3863 if (!item?.chequeOverlay)
3864 { return; }
3865 if (item.chequeOverlayDualTint)
3866 {
3867 this.#syncDualTintLitSprite(item.chequeOverlay, darkness, item.chequeOverlayDualTint);
3810 return;
3868 return;
3811 }
3869 }
3812 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3870 this.#syncLitSprite(item.chequeOverlay, darkness, 0, false, item.chequeOverlayTint ?? null);
3813 }
3871 }
3814
3872
3815 #groundTypeAt (tileX, tileY)
3873 #groundTypeAt (tileX, tileY)
server/src/items/bags.js +17 −3
@@ -26,6 +26,7 @@ import
26 26 stacksMatch,
27 27 fitStackQuantity
28 28 } from "../../../shared/items/inventory.js";
29 import { countIdenticalInSlots, chequeIsExpired } from "../../../shared/items/cheque.js";
29 30 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30 31 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31 32 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
@@ -860,7 +861,13 @@ function bankMove (world, sessionId, command, fromKey, toKey)
860 861 {
861 862 const slot = inventory.slots[command.slotIndex | 0];
862 863 if (slot?.itemId === ItemId.filledCheque)
863 { return redeemCheque(world, sessionId, command); }
864 {
865 world.sweepExpiredCheques?.(command.characterId);
866 const fresh = inventory.slots[command.slotIndex | 0];
867 if (!fresh || fresh.itemId !== ItemId.filledCheque)
868 { throw userError("That cheque has expired."); }
869 return redeemCheque(world, sessionId, command);
870 }
864 871 }
865 872 if (toKey === "vault")
866 873 {
@@ -949,6 +956,7 @@ function returnBlankCheques (world, sessionId, command)
949 956 function writeCheque (world, sessionId, command)
950 957 {
951 958 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
959 world.sweepExpiredCheques?.(command.characterId);
952 960 const inventory = ensureInventory(world.ecs, handle);
953 961 const vault = ensureVault(world.ecs, handle);
954 962 const slotIndex = command.slotIndex | 0;
@@ -962,7 +970,7 @@ function writeCheque (world, sessionId, command)
962 970 if (!def)
963 971 { throw userError("Unknown item."); }
964 972 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
965 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
973 const available = countIdenticalInSlots(vault.slots, vaultSlot);
966 974 if (available < quantity)
967 975 { throw userError("Not enough unreserved goods in the vault."); }
968 976 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
@@ -971,7 +979,7 @@ function writeCheque (world, sessionId, command)
971 979 const pulled = takeMatchingFromSlots(vault.slots, {
972 980 itemId: vaultSlot.itemId,
973 981 quantity,
974 instance: def.uniqueInstance ? vaultSlot.instance : null
982 matchStack: vaultSlot
975 983 });
976 984 if (!pulled.ok)
977 985 { throw userError("Not enough unreserved goods in the vault."); }
@@ -1019,6 +1027,7 @@ function writeCheque (world, sessionId, command)
1019 1027 function redeemCheque (world, sessionId, command)
1020 1028 {
1021 1029 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
1030 world.sweepExpiredCheques?.(command.characterId);
1022 1031 requireBank(world, handle);
1023 1032 const inventory = ensureInventory(world.ecs, handle);
1024 1033 const vault = ensureVault(world.ecs, handle);
@@ -1026,6 +1035,11 @@ function redeemCheque (world, sessionId, command)
1026 1035 const slot = inventory.slots[slotIndex];
1027 1036 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
1028 1037 { throw userError("Select a filled cheque."); }
1038 if (chequeIsExpired(slot))
1039 {
1040 world.expireFilledChequePaper?.(command.characterId, slotIndex);
1041 throw userError("That cheque has expired.");
1042 }
1029 1043
1030 1044 const chequeId = slot.instance.chequeId;
1031 1045 const issuerId = slot.instance.issuerCharacterId;
@@ -26,6 +26,7 @@ import
26 stacksMatch,
26 stacksMatch,
27 fitStackQuantity
27 fitStackQuantity
28 } from "../../../shared/items/inventory.js";
28 } from "../../../shared/items/inventory.js";
29import { countIdenticalInSlots, chequeIsExpired } from "../../../shared/items/cheque.js";
29import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
32import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
@@ -860,7 +861,13 @@ function bankMove (world, sessionId, command, fromKey, toKey)
860 {
861 {
861 const slot = inventory.slots[command.slotIndex | 0];
862 const slot = inventory.slots[command.slotIndex | 0];
862 if (slot?.itemId === ItemId.filledCheque)
863 if (slot?.itemId === ItemId.filledCheque)
863 { return redeemCheque(world, sessionId, command); }
864 {
865 world.sweepExpiredCheques?.(command.characterId);
866 const fresh = inventory.slots[command.slotIndex | 0];
867 if (!fresh || fresh.itemId !== ItemId.filledCheque)
868 { throw userError("That cheque has expired."); }
869 return redeemCheque(world, sessionId, command);
870 }
864 }
871 }
865 if (toKey === "vault")
872 if (toKey === "vault")
866 {
873 {
@@ -949,6 +956,7 @@ function returnBlankCheques (world, sessionId, command)
949function writeCheque (world, sessionId, command)
956function writeCheque (world, sessionId, command)
950{
957{
951 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
958 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
959 world.sweepExpiredCheques?.(command.characterId);
952 const inventory = ensureInventory(world.ecs, handle);
960 const inventory = ensureInventory(world.ecs, handle);
953 const vault = ensureVault(world.ecs, handle);
961 const vault = ensureVault(world.ecs, handle);
954 const slotIndex = command.slotIndex | 0;
962 const slotIndex = command.slotIndex | 0;
@@ -962,7 +970,7 @@ function writeCheque (world, sessionId, command)
962 if (!def)
970 if (!def)
963 { throw userError("Unknown item."); }
971 { throw userError("Unknown item."); }
964 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
972 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
965 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
973 const available = countIdenticalInSlots(vault.slots, vaultSlot);
966 if (available < quantity)
974 if (available < quantity)
967 { throw userError("Not enough unreserved goods in the vault."); }
975 { throw userError("Not enough unreserved goods in the vault."); }
968 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
976 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
@@ -971,7 +979,7 @@ function writeCheque (world, sessionId, command)
971 const pulled = takeMatchingFromSlots(vault.slots, {
979 const pulled = takeMatchingFromSlots(vault.slots, {
972 itemId: vaultSlot.itemId,
980 itemId: vaultSlot.itemId,
973 quantity,
981 quantity,
974 instance: def.uniqueInstance ? vaultSlot.instance : null
982 matchStack: vaultSlot
975 });
983 });
976 if (!pulled.ok)
984 if (!pulled.ok)
977 { throw userError("Not enough unreserved goods in the vault."); }
985 { throw userError("Not enough unreserved goods in the vault."); }
@@ -1019,6 +1027,7 @@ function writeCheque (world, sessionId, command)
1019function redeemCheque (world, sessionId, command)
1027function redeemCheque (world, sessionId, command)
1020{
1028{
1021 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
1029 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
1030 world.sweepExpiredCheques?.(command.characterId);
1022 requireBank(world, handle);
1031 requireBank(world, handle);
1023 const inventory = ensureInventory(world.ecs, handle);
1032 const inventory = ensureInventory(world.ecs, handle);
1024 const vault = ensureVault(world.ecs, handle);
1033 const vault = ensureVault(world.ecs, handle);
@@ -1026,6 +1035,11 @@ function redeemCheque (world, sessionId, command)
1026 const slot = inventory.slots[slotIndex];
1035 const slot = inventory.slots[slotIndex];
1027 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
1036 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
1028 { throw userError("Select a filled cheque."); }
1037 { throw userError("Select a filled cheque."); }
1038 if (chequeIsExpired(slot))
1039 {
1040 world.expireFilledChequePaper?.(command.characterId, slotIndex);
1041 throw userError("That cheque has expired.");
1042 }
1029
1043
1030 const chequeId = slot.instance.chequeId;
1044 const chequeId = slot.instance.chequeId;
1031 const issuerId = slot.instance.issuerCharacterId;
1045 const issuerId = slot.instance.issuerCharacterId;
server/src/shop/service.js +6 −0
@@ -10,6 +10,7 @@ import {
10 10 shopOrigin
11 11 } from "../../../shared/items/origin.js";
12 12 import { isLetterStack } from "../../../shared/items/letters.js";
13 import { chequeIsExpired } from "../../../shared/items/cheque.js";
13 14 import {
14 15 addCoinsToSlots,
15 16 cloneStack,
@@ -673,6 +674,11 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
673 674 { throw userError("They will not buy that."); }
674 675
675 676 const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
677 if (isCheque && chequeIsExpired(slot))
678 {
679 world.expireFilledChequePaper?.(characterId, slotIndex | 0);
680 throw userError("That cheque has expired.");
681 }
676 682 const isLetter = isLetterStack(slot);
677 683 const quote = resolveShopSellQuote(slot, {
678 684 lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
@@ -10,6 +10,7 @@ import {
10 shopOrigin
10 shopOrigin
11} from "../../../shared/items/origin.js";
11} from "../../../shared/items/origin.js";
12import { isLetterStack } from "../../../shared/items/letters.js";
12import { isLetterStack } from "../../../shared/items/letters.js";
13import { chequeIsExpired } from "../../../shared/items/cheque.js";
13import {
14import {
14 addCoinsToSlots,
15 addCoinsToSlots,
15 cloneStack,
16 cloneStack,
@@ -673,6 +674,11 @@ export function sellToShop (world, sessionId, characterId, npcEntityId, slotInde
673 { throw userError("They will not buy that."); }
674 { throw userError("They will not buy that."); }
674
675
675 const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
676 const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
677 if (isCheque && chequeIsExpired(slot))
678 {
679 world.expireFilledChequePaper?.(characterId, slotIndex | 0);
680 throw userError("That cheque has expired.");
681 }
676 const isLetter = isLetterStack(slot);
682 const isLetter = isLetterStack(slot);
677 const quote = resolveShopSellQuote(slot, {
683 const quote = resolveShopSellQuote(slot, {
678 lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
684 lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
server/src/simulation/simulation.js +101 −6
@@ -50,6 +50,7 @@ import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/st
50 50 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
51 51 import { BlockType } from "../../../shared/definitions/tiles.js";
52 52 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
53 import { chequeIsExpired, isFilledChequeStack } from "../../../shared/items/cheque.js";
53 54 import { seasonIdAt } from "../../../shared/world/season.js";
54 55 import { CourierService } from "../courier/service.js";
55 56 import { MarketService } from "../market/service.js";
@@ -123,6 +124,9 @@ export class Simulation
123 124 this.releaseChequeReservation(issuerId, chequeId, instance);
124 125 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
125 126 worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);
127 worker.world.sweepExpiredCheques = (characterId) => this.sweepExpiredCheques(characterId);
128 worker.world.expireFilledChequePaper = (characterId, slotIndex) =>
129 this.expireFilledChequePaper(characterId, slotIndex);
126 130 }
127 131 this.courier = new CourierService({
128 132 stateDb: this.stateDb,
@@ -241,6 +245,11 @@ export class Simulation
241 245 this.tickIndex += 1;
242 246 if ((this.tickIndex % 1200) === 0)
243 247 { this.worldDb.purgeExpiredDimensions(now); }
248 if ((this.tickIndex % 600) === 0)
249 {
250 for (const characterId of this.characterEntities.keys())
251 { this.sweepExpiredCheques(characterId, { now }); }
252 }
244 253 const events = [];
245 254 const commands = this.commandQueue.splice(0);
246 255 for (const item of commands)
@@ -582,6 +591,7 @@ export class Simulation
582 591 ...snap
583 592 });
584 593 }
594 this.sweepExpiredCheques(characterId);
585 595 return entityId;
586 596 }
587 597
@@ -3350,6 +3360,16 @@ export class Simulation
3350 3360 dim
3351 3361 ))
3352 3362 {
3363 if (chequeIsExpired(item.stack, this.now))
3364 {
3365 this.voidFilledCheque(item.stack, { toast: true });
3366 item.stack = {
3367 itemId: ItemId.expiredCheque,
3368 quantity: 1,
3369 instance: null
3370 };
3371 this.stateDb.upsertGroundItem(item);
3372 }
3353 3373 if (item.expiresAt > this.now)
3354 3374 {
3355 3375 items.push(item);
@@ -3369,7 +3389,7 @@ export class Simulation
3369 3389 }
3370 3390
3371 3391 /** Cheque paper that no longer exists must free reserved vault goods. */
3372 voidFilledCheque (stack)
3392 voidFilledCheque (stack, { toast = true } = {})
3373 3393 {
3374 3394 if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3375 3395 { return { ok: false }; }
@@ -3402,14 +3422,89 @@ export class Simulation
3402 3422 this.applyBag(onlineId, bag);
3403 3423 this.pushInventory(issuerId, bag);
3404 3424 }
3405 this.pendingPrivate.push({
3406 type: "toast",
3407 characterId: issuerId,
3408 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3409 });
3425 if (toast)
3426 {
3427 this.pendingPrivate.push({
3428 type: "toast",
3429 characterId: issuerId,
3430 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3431 });
3432 }
3410 3433 return { ok: true };
3411 3434 }
3412 3435
3436 /**
3437 * Convert an aged filled cheque in a character's bag into an expired cheque
3438 * and release its reservation back to the issuer.
3439 */
3440 expireFilledChequePaper (characterId, slotIndex, { now = this.now } = {})
3441 {
3442 const cid = characterId | 0;
3443 const onlineId = this.characterEntities.get(cid);
3444 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3445 if (!bag?.inventory)
3446 { return { ok: false }; }
3447 const index = slotIndex | 0;
3448 const stack = bag.inventory[index];
3449 if (!isFilledChequeStack(stack))
3450 { return { ok: false }; }
3451 if (!chequeIsExpired(stack, now))
3452 { return { ok: false, expired: false }; }
3453 bag.inventory[index] = {
3454 itemId: ItemId.expiredCheque,
3455 quantity: 1,
3456 instance: null,
3457 origins: []
3458 };
3459 this.stateDb.saveBag(cid, bag);
3460 if (onlineId)
3461 {
3462 this.applyBag(onlineId, bag);
3463 this.pushInventory(cid, bag);
3464 }
3465 this.voidFilledCheque(stack, { toast: true });
3466 return { ok: true, expired: true };
3467 }
3468
3469 /** Scan inventory (and convert) any filled cheques past their 30-day life. */
3470 sweepExpiredCheques (characterId, { now = this.now } = {})
3471 {
3472 const cid = characterId | 0;
3473 const onlineId = this.characterEntities.get(cid);
3474 let bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3475 if (!bag?.inventory)
3476 { return { ok: true, converted: 0 }; }
3477 const toRelease = [];
3478 for (let i = 0; i < bag.inventory.length; i++)
3479 {
3480 const stack = bag.inventory[i];
3481 if (!chequeIsExpired(stack, now))
3482 { continue; }
3483 toRelease.push(stack);
3484 bag.inventory[i] = {
3485 itemId: ItemId.expiredCheque,
3486 quantity: 1,
3487 instance: null,
3488 origins: []
3489 };
3490 }
3491 if (!toRelease.length)
3492 { return { ok: true, converted: 0 }; }
3493 this.stateDb.saveBag(cid, bag);
3494 if (onlineId)
3495 {
3496 this.applyBag(onlineId, bag);
3497 this.pushInventory(cid, bag);
3498 }
3499 let toasted = false;
3500 for (const stack of toRelease)
3501 {
3502 this.voidFilledCheque(stack, { toast: !toasted });
3503 toasted = true;
3504 }
3505 return { ok: true, converted: toRelease.length };
3506 }
3507
3413 3508 #destroyExpiredGroundItem (item)
3414 3509 {
3415 3510 if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
@@ -50,6 +50,7 @@ import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/st
50import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
50import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
51import { BlockType } from "../../../shared/definitions/tiles.js";
51import { BlockType } from "../../../shared/definitions/tiles.js";
52import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
52import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
53import { chequeIsExpired, isFilledChequeStack } from "../../../shared/items/cheque.js";
53import { seasonIdAt } from "../../../shared/world/season.js";
54import { seasonIdAt } from "../../../shared/world/season.js";
54import { CourierService } from "../courier/service.js";
55import { CourierService } from "../courier/service.js";
55import { MarketService } from "../market/service.js";
56import { MarketService } from "../market/service.js";
@@ -123,6 +124,9 @@ export class Simulation
123 this.releaseChequeReservation(issuerId, chequeId, instance);
124 this.releaseChequeReservation(issuerId, chequeId, instance);
124 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
125 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
125 worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);
126 worker.world.voidFilledCheque = (stack) => this.voidFilledCheque(stack);
127 worker.world.sweepExpiredCheques = (characterId) => this.sweepExpiredCheques(characterId);
128 worker.world.expireFilledChequePaper = (characterId, slotIndex) =>
129 this.expireFilledChequePaper(characterId, slotIndex);
126 }
130 }
127 this.courier = new CourierService({
131 this.courier = new CourierService({
128 stateDb: this.stateDb,
132 stateDb: this.stateDb,
@@ -241,6 +245,11 @@ export class Simulation
241 this.tickIndex += 1;
245 this.tickIndex += 1;
242 if ((this.tickIndex % 1200) === 0)
246 if ((this.tickIndex % 1200) === 0)
243 { this.worldDb.purgeExpiredDimensions(now); }
247 { this.worldDb.purgeExpiredDimensions(now); }
248 if ((this.tickIndex % 600) === 0)
249 {
250 for (const characterId of this.characterEntities.keys())
251 { this.sweepExpiredCheques(characterId, { now }); }
252 }
244 const events = [];
253 const events = [];
245 const commands = this.commandQueue.splice(0);
254 const commands = this.commandQueue.splice(0);
246 for (const item of commands)
255 for (const item of commands)
@@ -582,6 +591,7 @@ export class Simulation
582 ...snap
591 ...snap
583 });
592 });
584 }
593 }
594 this.sweepExpiredCheques(characterId);
585 return entityId;
595 return entityId;
586 }
596 }
587
597
@@ -3350,6 +3360,16 @@ export class Simulation
3350 dim
3360 dim
3351 ))
3361 ))
3352 {
3362 {
3363 if (chequeIsExpired(item.stack, this.now))
3364 {
3365 this.voidFilledCheque(item.stack, { toast: true });
3366 item.stack = {
3367 itemId: ItemId.expiredCheque,
3368 quantity: 1,
3369 instance: null
3370 };
3371 this.stateDb.upsertGroundItem(item);
3372 }
3353 if (item.expiresAt > this.now)
3373 if (item.expiresAt > this.now)
3354 {
3374 {
3355 items.push(item);
3375 items.push(item);
@@ -3369,7 +3389,7 @@ export class Simulation
3369 }
3389 }
3370
3390
3371 /** Cheque paper that no longer exists must free reserved vault goods. */
3391 /** Cheque paper that no longer exists must free reserved vault goods. */
3372 voidFilledCheque (stack)
3392 voidFilledCheque (stack, { toast = true } = {})
3373 {
3393 {
3374 if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3394 if ((stack?.itemId | 0) !== ItemId.filledCheque || stack?.instance?.kind !== "filled-cheque")
3375 { return { ok: false }; }
3395 { return { ok: false }; }
@@ -3402,14 +3422,89 @@ export class Simulation
3402 this.applyBag(onlineId, bag);
3422 this.applyBag(onlineId, bag);
3403 this.pushInventory(issuerId, bag);
3423 this.pushInventory(issuerId, bag);
3404 }
3424 }
3405 this.pendingPrivate.push({
3425 if (toast)
3406 type: "toast",
3426 {
3407 characterId: issuerId,
3427 this.pendingPrivate.push({
3408 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3428 type: "toast",
3409 });
3429 characterId: issuerId,
3430 message: "An uncashed cheque expired. Reserved goods returned to your vault."
3431 });
3432 }
3410 return { ok: true };
3433 return { ok: true };
3411 }
3434 }
3412
3435
3436 /**
3437 * Convert an aged filled cheque in a character's bag into an expired cheque
3438 * and release its reservation back to the issuer.
3439 */
3440 expireFilledChequePaper (characterId, slotIndex, { now = this.now } = {})
3441 {
3442 const cid = characterId | 0;
3443 const onlineId = this.characterEntities.get(cid);
3444 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3445 if (!bag?.inventory)
3446 { return { ok: false }; }
3447 const index = slotIndex | 0;
3448 const stack = bag.inventory[index];
3449 if (!isFilledChequeStack(stack))
3450 { return { ok: false }; }
3451 if (!chequeIsExpired(stack, now))
3452 { return { ok: false, expired: false }; }
3453 bag.inventory[index] = {
3454 itemId: ItemId.expiredCheque,
3455 quantity: 1,
3456 instance: null,
3457 origins: []
3458 };
3459 this.stateDb.saveBag(cid, bag);
3460 if (onlineId)
3461 {
3462 this.applyBag(onlineId, bag);
3463 this.pushInventory(cid, bag);
3464 }
3465 this.voidFilledCheque(stack, { toast: true });
3466 return { ok: true, expired: true };
3467 }
3468
3469 /** Scan inventory (and convert) any filled cheques past their 30-day life. */
3470 sweepExpiredCheques (characterId, { now = this.now } = {})
3471 {
3472 const cid = characterId | 0;
3473 const onlineId = this.characterEntities.get(cid);
3474 let bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(cid);
3475 if (!bag?.inventory)
3476 { return { ok: true, converted: 0 }; }
3477 const toRelease = [];
3478 for (let i = 0; i < bag.inventory.length; i++)
3479 {
3480 const stack = bag.inventory[i];
3481 if (!chequeIsExpired(stack, now))
3482 { continue; }
3483 toRelease.push(stack);
3484 bag.inventory[i] = {
3485 itemId: ItemId.expiredCheque,
3486 quantity: 1,
3487 instance: null,
3488 origins: []
3489 };
3490 }
3491 if (!toRelease.length)
3492 { return { ok: true, converted: 0 }; }
3493 this.stateDb.saveBag(cid, bag);
3494 if (onlineId)
3495 {
3496 this.applyBag(onlineId, bag);
3497 this.pushInventory(cid, bag);
3498 }
3499 let toasted = false;
3500 for (const stack of toRelease)
3501 {
3502 this.voidFilledCheque(stack, { toast: !toasted });
3503 toasted = true;
3504 }
3505 return { ok: true, converted: toRelease.length };
3506 }
3507
3413 #destroyExpiredGroundItem (item)
3508 #destroyExpiredGroundItem (item)
3414 {
3509 {
3415 if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
3510 if (item?.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
server/tests/bank.test.js +140 −0
@@ -3,7 +3,9 @@ import assert from "node:assert/strict";
3 3 import { BlockType } from "../../shared/definitions/tiles.js";
4 4 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5 5 import { RangedItemId } from "../../shared/definitions/rangedItems.js";
6 import { FlowerColorId, flowerItemInstance } from "../../shared/definitions/dyes.js";
6 7 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
8 import { CHEQUE_LIFETIME_MS } from "../../shared/items/cheque.js";
7 9 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
8 10 import {
9 11 makeCharacter,
@@ -446,3 +448,141 @@ test("dropping a filled cheque keeps reservation; despawn returns goods to vault
446 448 finally
447 449 { harness.close(); }
448 450 });
451
452 test("write cheque reserves only the selected flower colour stack", () =>
453 {
454 const harness = makeSimulation({ workerCount: 1 });
455 try
456 {
457 placeBank(harness.worldDb, 8, 8);
458 harness.simulation.reloadWorld();
459 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
460 const entityId = harness.simulation.spawnCharacter(1, character);
461 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
462 harness.simulation.step();
463
464 const bagView = harness.simulation.bagOf(entityId);
465 bagView.inventory = emptySlots();
466 bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
467 bagView.equipment = emptyEquipment();
468 bagView.vault = [
469 { itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
470 { itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
471 ];
472 bagView.vaultReserved = [];
473 harness.simulation.applyBag(entityId, bagView);
474
475 const blueIndex = 1;
476 harness.simulation.enqueue(1, {
477 type: "write-cheque",
478 characterId: character.character_id,
479 slotIndex: 0,
480 vaultSlotIndex: blueIndex,
481 quantity: 2
482 });
483 const result = harness.simulation.step();
484 assert.equal(result.events.some((event) => event.type === "command-error"), false);
485
486 const bag = harness.simulation.bagOf(entityId);
487 assert.equal((bag.vaultReserved ?? []).length, 1);
488 assert.equal(bag.vaultReserved[0].quantity, 2);
489 assert.equal(bag.vaultReserved[0].instance?.colorId, FlowerColorId.blue);
490 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.red)?.quantity, 5);
491 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue), undefined);
492
493 const cheque = bag.inventory.find((slot) => slot?.itemId === ItemId.filledCheque);
494 assert.equal(cheque?.instance?.reservedInstance?.colorId, FlowerColorId.blue);
495 assert.equal(cheque?.instance?.quantity, 2);
496 }
497 finally
498 { harness.close(); }
499 });
500
501 test("write cheque rejects quantity beyond matching metadata stacks", () =>
502 {
503 const harness = makeSimulation({ workerCount: 1 });
504 try
505 {
506 placeBank(harness.worldDb, 8, 8);
507 harness.simulation.reloadWorld();
508 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
509 const entityId = harness.simulation.spawnCharacter(1, character);
510 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
511 harness.simulation.step();
512
513 const bagView = harness.simulation.bagOf(entityId);
514 bagView.inventory = emptySlots();
515 bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
516 bagView.equipment = emptyEquipment();
517 bagView.vault = [
518 { itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
519 { itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
520 ];
521 bagView.vaultReserved = [];
522 harness.simulation.applyBag(entityId, bagView);
523
524 harness.simulation.enqueue(1, {
525 type: "write-cheque",
526 characterId: character.character_id,
527 slotIndex: 0,
528 vaultSlotIndex: 1,
529 quantity: 3
530 });
531 const result = harness.simulation.step();
532 const error = result.events.find((event) => event.type === "command-error");
533 assert.ok(error);
534 assert.match(error.message, /Not enough/i);
535 const bag = harness.simulation.bagOf(entityId);
536 assert.equal((bag.vaultReserved ?? []).length, 0);
537 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue)?.quantity, 2);
538 }
539 finally
540 { harness.close(); }
541 });
542
543 test("filled cheque expires after 30 days into expired cheque and releases goods", () =>
544 {
545 const harness = makeSimulation({ workerCount: 1 });
546 try
547 {
548 placeBank(harness.worldDb, 8, 8);
549 harness.simulation.reloadWorld();
550 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
551 const entityId = harness.simulation.spawnCharacter(1, character);
552 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
553 harness.simulation.step();
554 let bag = harness.simulation.bagOf(entityId);
555 const appleQty = countItem(bag.inventory, ItemId.apple);
556 harness.simulation.enqueue(1, {
557 type: "bank-deposit",
558 characterId: character.character_id,
559 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
560 quantity: null
561 });
562 harness.simulation.step();
563 bag = harness.simulation.bagOf(entityId);
564 harness.simulation.enqueue(1, {
565 type: "write-cheque",
566 characterId: character.character_id,
567 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
568 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
569 quantity: 2
570 });
571 harness.simulation.step();
572 bag = harness.simulation.bagOf(entityId);
573 assert.equal((bag.vaultReserved ?? []).length, 1);
574 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
575 assert.ok(chequeIndex >= 0);
576
577 bag.inventory[chequeIndex].instance.createdAt = harness.now() - CHEQUE_LIFETIME_MS - 1000;
578 harness.simulation.applyBag(entityId, bag);
579
580 harness.simulation.sweepExpiredCheques(character.character_id, { now: harness.now() });
581 bag = harness.simulation.bagOf(entityId);
582 assert.equal(bag.inventory[chequeIndex]?.itemId, ItemId.expiredCheque);
583 assert.equal((bag.vaultReserved ?? []).length, 0);
584 assert.equal(countItem(bag.vault, ItemId.apple), appleQty);
585 }
586 finally
587 { harness.close(); }
588 });
@@ -3,7 +3,9 @@ import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { RangedItemId } from "../../shared/definitions/rangedItems.js";
5import { RangedItemId } from "../../shared/definitions/rangedItems.js";
6import { FlowerColorId, flowerItemInstance } from "../../shared/definitions/dyes.js";
6import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
7import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
8import { CHEQUE_LIFETIME_MS } from "../../shared/items/cheque.js";
7import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
9import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
8import {
10import {
9 makeCharacter,
11 makeCharacter,
@@ -446,3 +448,141 @@ test("dropping a filled cheque keeps reservation; despawn returns goods to vault
446 finally
448 finally
447 { harness.close(); }
449 { harness.close(); }
448});
450});
451
452test("write cheque reserves only the selected flower colour stack", () =>
453{
454 const harness = makeSimulation({ workerCount: 1 });
455 try
456 {
457 placeBank(harness.worldDb, 8, 8);
458 harness.simulation.reloadWorld();
459 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
460 const entityId = harness.simulation.spawnCharacter(1, character);
461 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
462 harness.simulation.step();
463
464 const bagView = harness.simulation.bagOf(entityId);
465 bagView.inventory = emptySlots();
466 bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
467 bagView.equipment = emptyEquipment();
468 bagView.vault = [
469 { itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
470 { itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
471 ];
472 bagView.vaultReserved = [];
473 harness.simulation.applyBag(entityId, bagView);
474
475 const blueIndex = 1;
476 harness.simulation.enqueue(1, {
477 type: "write-cheque",
478 characterId: character.character_id,
479 slotIndex: 0,
480 vaultSlotIndex: blueIndex,
481 quantity: 2
482 });
483 const result = harness.simulation.step();
484 assert.equal(result.events.some((event) => event.type === "command-error"), false);
485
486 const bag = harness.simulation.bagOf(entityId);
487 assert.equal((bag.vaultReserved ?? []).length, 1);
488 assert.equal(bag.vaultReserved[0].quantity, 2);
489 assert.equal(bag.vaultReserved[0].instance?.colorId, FlowerColorId.blue);
490 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.red)?.quantity, 5);
491 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue), undefined);
492
493 const cheque = bag.inventory.find((slot) => slot?.itemId === ItemId.filledCheque);
494 assert.equal(cheque?.instance?.reservedInstance?.colorId, FlowerColorId.blue);
495 assert.equal(cheque?.instance?.quantity, 2);
496 }
497 finally
498 { harness.close(); }
499});
500
501test("write cheque rejects quantity beyond matching metadata stacks", () =>
502{
503 const harness = makeSimulation({ workerCount: 1 });
504 try
505 {
506 placeBank(harness.worldDb, 8, 8);
507 harness.simulation.reloadWorld();
508 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
509 const entityId = harness.simulation.spawnCharacter(1, character);
510 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
511 harness.simulation.step();
512
513 const bagView = harness.simulation.bagOf(entityId);
514 bagView.inventory = emptySlots();
515 bagView.inventory[0] = { itemId: ItemId.blankCheque, quantity: 5 };
516 bagView.equipment = emptyEquipment();
517 bagView.vault = [
518 { itemId: ItemId.flower, quantity: 5, instance: flowerItemInstance(FlowerColorId.red) },
519 { itemId: ItemId.flower, quantity: 2, instance: flowerItemInstance(FlowerColorId.blue) }
520 ];
521 bagView.vaultReserved = [];
522 harness.simulation.applyBag(entityId, bagView);
523
524 harness.simulation.enqueue(1, {
525 type: "write-cheque",
526 characterId: character.character_id,
527 slotIndex: 0,
528 vaultSlotIndex: 1,
529 quantity: 3
530 });
531 const result = harness.simulation.step();
532 const error = result.events.find((event) => event.type === "command-error");
533 assert.ok(error);
534 assert.match(error.message, /Not enough/i);
535 const bag = harness.simulation.bagOf(entityId);
536 assert.equal((bag.vaultReserved ?? []).length, 0);
537 assert.equal(bag.vault.find((slot) => slot?.instance?.colorId === FlowerColorId.blue)?.quantity, 2);
538 }
539 finally
540 { harness.close(); }
541});
542
543test("filled cheque expires after 30 days into expired cheque and releases goods", () =>
544{
545 const harness = makeSimulation({ workerCount: 1 });
546 try
547 {
548 placeBank(harness.worldDb, 8, 8);
549 harness.simulation.reloadWorld();
550 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
551 const entityId = harness.simulation.spawnCharacter(1, character);
552 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
553 harness.simulation.step();
554 let bag = harness.simulation.bagOf(entityId);
555 const appleQty = countItem(bag.inventory, ItemId.apple);
556 harness.simulation.enqueue(1, {
557 type: "bank-deposit",
558 characterId: character.character_id,
559 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
560 quantity: null
561 });
562 harness.simulation.step();
563 bag = harness.simulation.bagOf(entityId);
564 harness.simulation.enqueue(1, {
565 type: "write-cheque",
566 characterId: character.character_id,
567 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
568 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
569 quantity: 2
570 });
571 harness.simulation.step();
572 bag = harness.simulation.bagOf(entityId);
573 assert.equal((bag.vaultReserved ?? []).length, 1);
574 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
575 assert.ok(chequeIndex >= 0);
576
577 bag.inventory[chequeIndex].instance.createdAt = harness.now() - CHEQUE_LIFETIME_MS - 1000;
578 harness.simulation.applyBag(entityId, bag);
579
580 harness.simulation.sweepExpiredCheques(character.character_id, { now: harness.now() });
581 bag = harness.simulation.bagOf(entityId);
582 assert.equal(bag.inventory[chequeIndex]?.itemId, ItemId.expiredCheque);
583 assert.equal((bag.vaultReserved ?? []).length, 0);
584 assert.equal(countItem(bag.vault, ItemId.apple), appleQty);
585 }
586 finally
587 { harness.close(); }
588});
shared/definitions/items.js +35 −2
@@ -25,6 +25,10 @@ import { JewelryItemId, JEWELRY_ITEM_DEFINITIONS } from "./jewelryItems.js";
25 25 import { SwordItemId, SWORD_ITEM_DEFINITIONS } from "./swordItems.js";
26 26 import { WarAxeItemId, WAR_AXE_ITEM_DEFINITIONS } from "./warAxeItems.js";
27 27 import { EssenceItemId, ESSENCE_ITEM_DEFINITIONS } from "./essenceItems.js";
28 import {
29 chequeReservedGoodsStack,
30 chequeExpiryTooltipLine
31 } from "../items/cheque.js";
28 32
29 33 export const ItemId = Object.freeze({
30 34 paper: 1,
@@ -35,6 +39,8 @@ export const ItemId = Object.freeze({
35 39 clothShirt: 5,
36 40 letter: 6,
37 41 filledCheque: 7,
42 /** Written cheque past its 30-day life — no longer redeemable. */
43 expiredCheque: 590,
38 44 coins: 8,
39 45 ...CraftingItemId,
40 46 lantern: 26,
@@ -235,6 +241,22 @@ export const ITEM_DEFINITIONS = Object.freeze({
235 241 defaultState: "filled-cheque",
236 242 marketplaceSellable: true
237 243 }),
244 [ItemId.expiredCheque]: Object.freeze({
245 itemId: ItemId.expiredCheque,
246 key: "expired-cheque",
247 displayName: "Expired cheque",
248 description: "A cheque whose claim has lapsed. The reserved goods were returned to the issuer.",
249 seedValue: 1,
250 stackable: true,
251 maxStackSize: DEFAULT_MAX_STACK,
252 uniqueInstance: false,
253 category: "document",
254 /** Reuse blank stationery art — visually distinct from a live written cheque. */
255 iconKey: "blank-cheque",
256 defaultState: "blank-cheque",
257 marketplaceSellable: false,
258 marketplaceSellBlockedReason: "Expired cheques cannot be sold on the marketplace."
259 }),
238 260 [ItemId.coins]: Object.freeze({
239 261 itemId: ItemId.coins,
240 262 key: "coins",
@@ -454,11 +476,15 @@ export function itemDescription (stack, { localCharacterId } = {})
454 476 }
455 477 if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
456 478 {
457 const reserved = itemDefinition(stack.instance.itemId);
479 const goods = chequeReservedGoodsStack(stack);
458 480 const qty = stack.instance.quantity | 0;
459 const name = reserved?.displayName ?? "goods";
481 const name = goods
482 ? itemDisplayName(goods)
483 : (itemDefinition(stack.instance.itemId)?.displayName ?? "goods");
460 484 return `Bearer cheque for ${qty}× ${name}.`;
461 485 }
486 if (stack.itemId === ItemId.expiredCheque)
487 { return def.description ?? ""; }
462 488 if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
463 489 {
464 490 if (stack.instance.unstable)
@@ -488,6 +514,13 @@ export function itemOriginSummary (stack)
488 514 return formatOriginBreakdown(stack);
489 515 }
490 516
517 /** Extra tooltip lines after the description (e.g. cheque expiry). */
518 export function itemExtraTooltipLines (stack, { now = Date.now() } = {})
519 {
520 const line = chequeExpiryTooltipLine(stack, now);
521 return line ? [line] : [];
522 }
523
491 524 export function itemDefaultState (def, instance = null)
492 525 {
493 526 if (def?.familyId === ItemFamilyId.log && isLogDebarked({ instance }))
@@ -25,6 +25,10 @@ import { JewelryItemId, JEWELRY_ITEM_DEFINITIONS } from "./jewelryItems.js";
25import { SwordItemId, SWORD_ITEM_DEFINITIONS } from "./swordItems.js";
25import { SwordItemId, SWORD_ITEM_DEFINITIONS } from "./swordItems.js";
26import { WarAxeItemId, WAR_AXE_ITEM_DEFINITIONS } from "./warAxeItems.js";
26import { WarAxeItemId, WAR_AXE_ITEM_DEFINITIONS } from "./warAxeItems.js";
27import { EssenceItemId, ESSENCE_ITEM_DEFINITIONS } from "./essenceItems.js";
27import { EssenceItemId, ESSENCE_ITEM_DEFINITIONS } from "./essenceItems.js";
28import {
29 chequeReservedGoodsStack,
30 chequeExpiryTooltipLine
31} from "../items/cheque.js";
28
32
29export const ItemId = Object.freeze({
33export const ItemId = Object.freeze({
30 paper: 1,
34 paper: 1,
@@ -35,6 +39,8 @@ export const ItemId = Object.freeze({
35 clothShirt: 5,
39 clothShirt: 5,
36 letter: 6,
40 letter: 6,
37 filledCheque: 7,
41 filledCheque: 7,
42 /** Written cheque past its 30-day life — no longer redeemable. */
43 expiredCheque: 590,
38 coins: 8,
44 coins: 8,
39 ...CraftingItemId,
45 ...CraftingItemId,
40 lantern: 26,
46 lantern: 26,
@@ -235,6 +241,22 @@ export const ITEM_DEFINITIONS = Object.freeze({
235 defaultState: "filled-cheque",
241 defaultState: "filled-cheque",
236 marketplaceSellable: true
242 marketplaceSellable: true
237 }),
243 }),
244 [ItemId.expiredCheque]: Object.freeze({
245 itemId: ItemId.expiredCheque,
246 key: "expired-cheque",
247 displayName: "Expired cheque",
248 description: "A cheque whose claim has lapsed. The reserved goods were returned to the issuer.",
249 seedValue: 1,
250 stackable: true,
251 maxStackSize: DEFAULT_MAX_STACK,
252 uniqueInstance: false,
253 category: "document",
254 /** Reuse blank stationery art — visually distinct from a live written cheque. */
255 iconKey: "blank-cheque",
256 defaultState: "blank-cheque",
257 marketplaceSellable: false,
258 marketplaceSellBlockedReason: "Expired cheques cannot be sold on the marketplace."
259 }),
238 [ItemId.coins]: Object.freeze({
260 [ItemId.coins]: Object.freeze({
239 itemId: ItemId.coins,
261 itemId: ItemId.coins,
240 key: "coins",
262 key: "coins",
@@ -454,11 +476,15 @@ export function itemDescription (stack, { localCharacterId } = {})
454 }
476 }
455 if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
477 if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
456 {
478 {
457 const reserved = itemDefinition(stack.instance.itemId);
479 const goods = chequeReservedGoodsStack(stack);
458 const qty = stack.instance.quantity | 0;
480 const qty = stack.instance.quantity | 0;
459 const name = reserved?.displayName ?? "goods";
481 const name = goods
482 ? itemDisplayName(goods)
483 : (itemDefinition(stack.instance.itemId)?.displayName ?? "goods");
460 return `Bearer cheque for ${qty}× ${name}.`;
484 return `Bearer cheque for ${qty}× ${name}.`;
461 }
485 }
486 if (stack.itemId === ItemId.expiredCheque)
487 { return def.description ?? ""; }
462 if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
488 if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
463 {
489 {
464 if (stack.instance.unstable)
490 if (stack.instance.unstable)
@@ -488,6 +514,13 @@ export function itemOriginSummary (stack)
488 return formatOriginBreakdown(stack);
514 return formatOriginBreakdown(stack);
489}
515}
490
516
517/** Extra tooltip lines after the description (e.g. cheque expiry). */
518export function itemExtraTooltipLines (stack, { now = Date.now() } = {})
519{
520 const line = chequeExpiryTooltipLine(stack, now);
521 return line ? [line] : [];
522}
523
491export function itemDefaultState (def, instance = null)
524export function itemDefaultState (def, instance = null)
492{
525{
493 if (def?.familyId === ItemFamilyId.log && isLogDebarked({ instance }))
526 if (def?.familyId === ItemFamilyId.log && isLogDebarked({ instance }))
shared/items/cheque.js added +114 −0
@@ -0,0 +1,114 @@
1 /**
2 * Cheque identity, lifetime, and reserved-goods helpers.
3 * Matching is exact on itemId + full instance JSON so future metadata fields
4 * automatically participate in which vault stacks a cheque can reserve.
5 *
6 * Note: filled cheque item id is duplicated here to avoid a circular import with
7 * `definitions/items.js` (`ItemId.filledCheque === 7`).
8 */
9
10 /** @see ItemId.filledCheque in definitions/items.js */
11 export const FILLED_CHEQUE_ITEM_ID = 7;
12
13 /** Written cheques lapse after 30 calendar days from `createdAt`. */
14 export const CHEQUE_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
15
16 /** Stable identity for cheque reservation / vault selection (ignores qty & origins). */
17 export function stackIdentityKey (stack)
18 {
19 return JSON.stringify({
20 itemId: stack?.itemId ?? null,
21 instance: stack?.instance ?? null
22 });
23 }
24
25 /** True when two stacks are the same item with identical instance metadata. */
26 export function stacksIdentical (left, right)
27 {
28 if (!left || !right)
29 { return false; }
30 return stackIdentityKey(left) === stackIdentityKey(right);
31 }
32
33 export function countIdenticalInSlots (slots, reference)
34 {
35 if (!reference?.itemId)
36 { return 0; }
37 let total = 0;
38 for (const slot of slots ?? [])
39 {
40 if (!stacksIdentical(slot, reference))
41 { continue; }
42 total += Math.max(0, Math.floor(Number(slot.quantity) || 0));
43 }
44 return total;
45 }
46
47 export function isFilledChequeStack (stack)
48 {
49 return (stack?.itemId | 0) === FILLED_CHEQUE_ITEM_ID
50 && stack?.instance?.kind === "filled-cheque";
51 }
52
53 export function chequeCreatedAtMs (stack)
54 {
55 if (stack?.instance?.createdAt == null || stack.instance.createdAt === "")
56 { return null; }
57 const created = Number(stack.instance.createdAt);
58 return Number.isFinite(created) ? created : null;
59 }
60
61 export function chequeExpiresAtMs (stack)
62 {
63 const created = chequeCreatedAtMs(stack);
64 return created == null ? 0 : created + CHEQUE_LIFETIME_MS;
65 }
66
67 export function chequeIsExpired (stack, now = Date.now())
68 {
69 if (!isFilledChequeStack(stack))
70 { return false; }
71 const created = chequeCreatedAtMs(stack);
72 if (created == null)
73 { return false; }
74 return now >= created + CHEQUE_LIFETIME_MS;
75 }
76
77 /** Whole days remaining until expiry (ceil). 0 if already expired; null if unknown. */
78 export function chequeDaysRemaining (stack, now = Date.now())
79 {
80 if (!isFilledChequeStack(stack))
81 { return null; }
82 const created = chequeCreatedAtMs(stack);
83 if (created == null)
84 { return null; }
85 const ms = created + CHEQUE_LIFETIME_MS - now;
86 if (ms <= 0)
87 { return 0; }
88 return Math.ceil(ms / (24 * 60 * 60 * 1000));
89 }
90
91 export function chequeExpiryTooltipLine (stack, now = Date.now())
92 {
93 const days = chequeDaysRemaining(stack, now);
94 if (days == null)
95 { return ""; }
96 if (days <= 0)
97 { return "Expired."; }
98 if (days === 1)
99 { return "Expires in 1 day."; }
100 return `Expires in ${days} days.`;
101 }
102
103 /** Stack shape for the goods reserved on a filled cheque (icons / names). */
104 export function chequeReservedGoodsStack (chequeStack)
105 {
106 const instance = chequeStack?.instance;
107 if (!instance || instance.kind !== "filled-cheque")
108 { return null; }
109 return {
110 itemId: instance.itemId | 0,
111 quantity: Math.max(1, instance.quantity | 0 || 1),
112 instance: instance.reservedInstance ?? null
113 };
114 }
@@ -0,0 +1,114 @@
1/**
2 * Cheque identity, lifetime, and reserved-goods helpers.
3 * Matching is exact on itemId + full instance JSON so future metadata fields
4 * automatically participate in which vault stacks a cheque can reserve.
5 *
6 * Note: filled cheque item id is duplicated here to avoid a circular import with
7 * `definitions/items.js` (`ItemId.filledCheque === 7`).
8 */
9
10/** @see ItemId.filledCheque in definitions/items.js */
11export const FILLED_CHEQUE_ITEM_ID = 7;
12
13/** Written cheques lapse after 30 calendar days from `createdAt`. */
14export const CHEQUE_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
15
16/** Stable identity for cheque reservation / vault selection (ignores qty & origins). */
17export function stackIdentityKey (stack)
18{
19 return JSON.stringify({
20 itemId: stack?.itemId ?? null,
21 instance: stack?.instance ?? null
22 });
23}
24
25/** True when two stacks are the same item with identical instance metadata. */
26export function stacksIdentical (left, right)
27{
28 if (!left || !right)
29 { return false; }
30 return stackIdentityKey(left) === stackIdentityKey(right);
31}
32
33export function countIdenticalInSlots (slots, reference)
34{
35 if (!reference?.itemId)
36 { return 0; }
37 let total = 0;
38 for (const slot of slots ?? [])
39 {
40 if (!stacksIdentical(slot, reference))
41 { continue; }
42 total += Math.max(0, Math.floor(Number(slot.quantity) || 0));
43 }
44 return total;
45}
46
47export function isFilledChequeStack (stack)
48{
49 return (stack?.itemId | 0) === FILLED_CHEQUE_ITEM_ID
50 && stack?.instance?.kind === "filled-cheque";
51}
52
53export function chequeCreatedAtMs (stack)
54{
55 if (stack?.instance?.createdAt == null || stack.instance.createdAt === "")
56 { return null; }
57 const created = Number(stack.instance.createdAt);
58 return Number.isFinite(created) ? created : null;
59}
60
61export function chequeExpiresAtMs (stack)
62{
63 const created = chequeCreatedAtMs(stack);
64 return created == null ? 0 : created + CHEQUE_LIFETIME_MS;
65}
66
67export function chequeIsExpired (stack, now = Date.now())
68{
69 if (!isFilledChequeStack(stack))
70 { return false; }
71 const created = chequeCreatedAtMs(stack);
72 if (created == null)
73 { return false; }
74 return now >= created + CHEQUE_LIFETIME_MS;
75}
76
77/** Whole days remaining until expiry (ceil). 0 if already expired; null if unknown. */
78export function chequeDaysRemaining (stack, now = Date.now())
79{
80 if (!isFilledChequeStack(stack))
81 { return null; }
82 const created = chequeCreatedAtMs(stack);
83 if (created == null)
84 { return null; }
85 const ms = created + CHEQUE_LIFETIME_MS - now;
86 if (ms <= 0)
87 { return 0; }
88 return Math.ceil(ms / (24 * 60 * 60 * 1000));
89}
90
91export function chequeExpiryTooltipLine (stack, now = Date.now())
92{
93 const days = chequeDaysRemaining(stack, now);
94 if (days == null)
95 { return ""; }
96 if (days <= 0)
97 { return "Expired."; }
98 if (days === 1)
99 { return "Expires in 1 day."; }
100 return `Expires in ${days} days.`;
101}
102
103/** Stack shape for the goods reserved on a filled cheque (icons / names). */
104export function chequeReservedGoodsStack (chequeStack)
105{
106 const instance = chequeStack?.instance;
107 if (!instance || instance.kind !== "filled-cheque")
108 { return null; }
109 return {
110 itemId: instance.itemId | 0,
111 quantity: Math.max(1, instance.quantity | 0 || 1),
112 instance: instance.reservedInstance ?? null
113 };
114}
shared/items/inventory.js +35 −7
@@ -15,6 +15,7 @@ import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from
15 15 import { stackRulesFor } from "./stackRules.js";
16 16 import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
17 17 import { normalizeChargeStack } from "./charges.js";
18 import { stackIdentityKey } from "./cheque.js";
18 19
19 20 /** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
20 21 export function stackQuantity (value)
@@ -470,8 +471,17 @@ export function insertStackGrowable (slots, stack, definition)
470 471 return { ok: remaining === 0, slots: next, remainder: remaining };
471 472 }
472 473
473 /** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }`. */
474 export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance = null, compact = true })
474 /** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }.
475 * Pass `matchStack` to require exact itemId+instance identity (cheque write / metadata-aware takes).
476 * Legacy `instance` still filters with the same identity key when set.
477 */
478 export function takeMatchingUpToFromSlots (slots, {
479 itemId,
480 quantity,
481 instance = null,
482 matchStack = null,
483 compact = true
484 })
475 485 {
476 486 let remaining = Math.max(0, stackQuantity(quantity));
477 487 if (!remaining)
@@ -479,19 +489,25 @@ export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance =
479 489 const next = (slots ?? []).map(cloneStack);
480 490 const takenOrigins = [];
481 491 let takenQuantity = 0;
492 let keptInstance = undefined;
493 const reference = matchStack
494 ? { itemId: matchStack.itemId ?? itemId, instance: matchStack.instance ?? null }
495 : (instance != null ? { itemId, instance } : null);
482 496 for (let i = 0; i < next.length && remaining > 0; i++)
483 497 {
484 498 const slot = next[i];
485 499 if (!slot || slot.itemId !== itemId)
486 500 { continue; }
487 if (instance != null)
501 if (reference)
488 502 {
489 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
503 if (stackIdentityKey(slot) !== stackIdentityKey(reference))
490 504 { continue; }
491 505 }
492 506 const amount = Math.min(stackQuantity(slot.quantity), remaining);
493 507 if (amount <= 0)
494 508 { continue; }
509 if (keptInstance === undefined)
510 { keptInstance = slot.instance != null ? cloneStack(slot.instance) : null; }
495 511 const split = splitOrigins(normalizeOrigins(slot), amount);
496 512 takenOrigins.push(...split.taken);
497 513 if (amount >= stackQuantity(slot.quantity))
@@ -514,19 +530,31 @@ export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance =
514 530 taken: attachOrigins({
515 531 itemId,
516 532 quantity: takenQuantity,
517 instance: instance ?? null,
533 instance: keptInstance !== undefined ? keptInstance : (instance ?? null),
518 534 origins: mergeOriginLists([], takenOrigins)
519 535 })
520 536 };
521 537 }
522 538
523 539 /** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
524 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
540 export function takeMatchingFromSlots (slots, {
541 itemId,
542 quantity,
543 instance = null,
544 matchStack = null,
545 compact = true
546 })
525 547 {
526 548 const want = Math.max(0, stackQuantity(quantity));
527 549 if (!want)
528 550 { return { ok: false, slots, taken: null }; }
529 const soft = takeMatchingUpToFromSlots(slots, { itemId, quantity: want, instance, compact });
551 const soft = takeMatchingUpToFromSlots(slots, {
552 itemId,
553 quantity: want,
554 instance,
555 matchStack,
556 compact
557 });
530 558 if (!soft.ok || soft.takenQuantity < want)
531 559 { return { ok: false, slots, taken: null }; }
532 560 return {
@@ -15,6 +15,7 @@ import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from
15import { stackRulesFor } from "./stackRules.js";
15import { stackRulesFor } from "./stackRules.js";
16import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
16import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
17import { normalizeChargeStack } from "./charges.js";
17import { normalizeChargeStack } from "./charges.js";
18import { stackIdentityKey } from "./cheque.js";
18
19
19/** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
20/** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
20export function stackQuantity (value)
21export function stackQuantity (value)
@@ -470,8 +471,17 @@ export function insertStackGrowable (slots, stack, definition)
470 return { ok: remaining === 0, slots: next, remainder: remaining };
471 return { ok: remaining === 0, slots: next, remainder: remaining };
471}
472}
472
473
473/** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }`. */
474/** Take up to `quantity` of matching goods (partial OK). Inventory should pass `{ compact: false }.
474export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance = null, compact = true })
475 * Pass `matchStack` to require exact itemId+instance identity (cheque write / metadata-aware takes).
476 * Legacy `instance` still filters with the same identity key when set.
477 */
478export function takeMatchingUpToFromSlots (slots, {
479 itemId,
480 quantity,
481 instance = null,
482 matchStack = null,
483 compact = true
484})
475{
485{
476 let remaining = Math.max(0, stackQuantity(quantity));
486 let remaining = Math.max(0, stackQuantity(quantity));
477 if (!remaining)
487 if (!remaining)
@@ -479,19 +489,25 @@ export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance =
479 const next = (slots ?? []).map(cloneStack);
489 const next = (slots ?? []).map(cloneStack);
480 const takenOrigins = [];
490 const takenOrigins = [];
481 let takenQuantity = 0;
491 let takenQuantity = 0;
492 let keptInstance = undefined;
493 const reference = matchStack
494 ? { itemId: matchStack.itemId ?? itemId, instance: matchStack.instance ?? null }
495 : (instance != null ? { itemId, instance } : null);
482 for (let i = 0; i < next.length && remaining > 0; i++)
496 for (let i = 0; i < next.length && remaining > 0; i++)
483 {
497 {
484 const slot = next[i];
498 const slot = next[i];
485 if (!slot || slot.itemId !== itemId)
499 if (!slot || slot.itemId !== itemId)
486 { continue; }
500 { continue; }
487 if (instance != null)
501 if (reference)
488 {
502 {
489 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
503 if (stackIdentityKey(slot) !== stackIdentityKey(reference))
490 { continue; }
504 { continue; }
491 }
505 }
492 const amount = Math.min(stackQuantity(slot.quantity), remaining);
506 const amount = Math.min(stackQuantity(slot.quantity), remaining);
493 if (amount <= 0)
507 if (amount <= 0)
494 { continue; }
508 { continue; }
509 if (keptInstance === undefined)
510 { keptInstance = slot.instance != null ? cloneStack(slot.instance) : null; }
495 const split = splitOrigins(normalizeOrigins(slot), amount);
511 const split = splitOrigins(normalizeOrigins(slot), amount);
496 takenOrigins.push(...split.taken);
512 takenOrigins.push(...split.taken);
497 if (amount >= stackQuantity(slot.quantity))
513 if (amount >= stackQuantity(slot.quantity))
@@ -514,19 +530,31 @@ export function takeMatchingUpToFromSlots (slots, { itemId, quantity, instance =
514 taken: attachOrigins({
530 taken: attachOrigins({
515 itemId,
531 itemId,
516 quantity: takenQuantity,
532 quantity: takenQuantity,
517 instance: instance ?? null,
533 instance: keptInstance !== undefined ? keptInstance : (instance ?? null),
518 origins: mergeOriginLists([], takenOrigins)
534 origins: mergeOriginLists([], takenOrigins)
519 })
535 })
520 };
536 };
521}
537}
522
538
523/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
539/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
524export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
540export function takeMatchingFromSlots (slots, {
541 itemId,
542 quantity,
543 instance = null,
544 matchStack = null,
545 compact = true
546})
525{
547{
526 const want = Math.max(0, stackQuantity(quantity));
548 const want = Math.max(0, stackQuantity(quantity));
527 if (!want)
549 if (!want)
528 { return { ok: false, slots, taken: null }; }
550 { return { ok: false, slots, taken: null }; }
529 const soft = takeMatchingUpToFromSlots(slots, { itemId, quantity: want, instance, compact });
551 const soft = takeMatchingUpToFromSlots(slots, {
552 itemId,
553 quantity: want,
554 instance,
555 matchStack,
556 compact
557 });
530 if (!soft.ok || soft.takenQuantity < want)
558 if (!soft.ok || soft.takenQuantity < want)
531 { return { ok: false, slots, taken: null }; }
559 { return { ok: false, slots, taken: null }; }
532 return {
560 return {
shared/market/funds.js +5 −1
@@ -2,12 +2,15 @@ import { ItemId, itemDefinition, itemDisplayName } from "../definitions/items.js
2 2 import { listingKeyFromStack } from "./listingKey.js";
3 3 import { cloneStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
4 4 import { isPartiallyConsumed } from "../items/charges.js";
5 import { chequeIsExpired } from "../items/cheque.js";
5 6
6 7 /** Filled cheque that reserves coins (usable as market payment, whole only). */
7 8 export function isCoinChequeStack (stack)
8 9 {
9 10 if ((stack?.itemId | 0) !== ItemId.filledCheque)
10 11 { return false; }
12 if (chequeIsExpired(stack))
13 { return false; }
11 14 const instance = stack.instance;
12 15 return instance?.kind === "filled-cheque" && (instance.itemId | 0) === ItemId.coins;
13 16 }
@@ -170,5 +173,6 @@ export function resolveMarketSellListing (stack)
170 173 export function isFilledChequeEscrow (stack)
171 174 {
172 175 return (stack?.itemId | 0) === ItemId.filledCheque
173 && stack?.instance?.kind === "filled-cheque";
176 && stack?.instance?.kind === "filled-cheque"
177 && !chequeIsExpired(stack);
174 178 }
@@ -2,12 +2,15 @@ import { ItemId, itemDefinition, itemDisplayName } from "../definitions/items.js
2import { listingKeyFromStack } from "./listingKey.js";
2import { listingKeyFromStack } from "./listingKey.js";
3import { cloneStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3import { cloneStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
4import { isPartiallyConsumed } from "../items/charges.js";
4import { isPartiallyConsumed } from "../items/charges.js";
5import { chequeIsExpired } from "../items/cheque.js";
5
6
6/** Filled cheque that reserves coins (usable as market payment, whole only). */
7/** Filled cheque that reserves coins (usable as market payment, whole only). */
7export function isCoinChequeStack (stack)
8export function isCoinChequeStack (stack)
8{
9{
9 if ((stack?.itemId | 0) !== ItemId.filledCheque)
10 if ((stack?.itemId | 0) !== ItemId.filledCheque)
10 { return false; }
11 { return false; }
12 if (chequeIsExpired(stack))
13 { return false; }
11 const instance = stack.instance;
14 const instance = stack.instance;
12 return instance?.kind === "filled-cheque" && (instance.itemId | 0) === ItemId.coins;
15 return instance?.kind === "filled-cheque" && (instance.itemId | 0) === ItemId.coins;
13}
16}
@@ -170,5 +173,6 @@ export function resolveMarketSellListing (stack)
170export function isFilledChequeEscrow (stack)
173export function isFilledChequeEscrow (stack)
171{
174{
172 return (stack?.itemId | 0) === ItemId.filledCheque
175 return (stack?.itemId | 0) === ItemId.filledCheque
173 && stack?.instance?.kind === "filled-cheque";
176 && stack?.instance?.kind === "filled-cheque"
177 && !chequeIsExpired(stack);
174}
178}