BlueGit

timfa questward

Add player-to-player trade with invites, soft-claim offers, and slot checks.

timfa Tim Falken · pushed by timfa

Authored 2026-09-04 · 2 months ago

Hash
7d92c5d5f99020fe226eb71a9e050b417c56f890
Parent
48958f27
12 files changed +1806 −68
client/index.html +35 −0
@@ -210,6 +210,41 @@
210 210 <button id="transfer-confirm" type="button">Transfer</button>
211 211 </aside>
212 212
213 <div id="trade-backdrop" class="modal-backdrop" hidden></div>
214 <aside id="trade-panel" hidden>
215 <header>
216 <h2 id="trade-partner">Trade</h2>
217 <button id="trade-cancel" type="button">Cancel</button>
218 </header>
219 <div class="trade-columns">
220 <section class="trade-column">
221 <h3>You will give:</h3>
222 <div id="trade-give-grid" class="trade-offer-grid item-grid"></div>
223 </section>
224 <section class="trade-column">
225 <h3>You will receive:</h3>
226 <div id="trade-receive-grid" class="trade-offer-grid item-grid"></div>
227 </section>
228 </div>
229 <p id="trade-status" class="hint"></p>
230 <div class="trade-actions">
231 <button id="trade-accept" type="button">Accept</button>
232 </div>
233 </aside>
234
235 <div id="trade-qty-backdrop" class="modal-backdrop" hidden></div>
236 <aside id="trade-qty-panel" hidden>
237 <header>
238 <h2>Offer quantity</h2>
239 <button id="trade-qty-close" type="button">Close</button>
240 </header>
241 <p id="trade-qty-name"></p>
242 <label class="send-row">Quantity
243 <input id="trade-qty-input" type="number" min="1" step="1" value="1">
244 </label>
245 <button id="trade-qty-confirm" type="button">Offer</button>
246 </aside>
247
213 248 <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
214 249 <aside id="write-cheque-panel" hidden>
215 250 <header>
@@ -210,6 +210,41 @@
210 <button id="transfer-confirm" type="button">Transfer</button>
210 <button id="transfer-confirm" type="button">Transfer</button>
211 </aside>
211 </aside>
212
212
213 <div id="trade-backdrop" class="modal-backdrop" hidden></div>
214 <aside id="trade-panel" hidden>
215 <header>
216 <h2 id="trade-partner">Trade</h2>
217 <button id="trade-cancel" type="button">Cancel</button>
218 </header>
219 <div class="trade-columns">
220 <section class="trade-column">
221 <h3>You will give:</h3>
222 <div id="trade-give-grid" class="trade-offer-grid item-grid"></div>
223 </section>
224 <section class="trade-column">
225 <h3>You will receive:</h3>
226 <div id="trade-receive-grid" class="trade-offer-grid item-grid"></div>
227 </section>
228 </div>
229 <p id="trade-status" class="hint"></p>
230 <div class="trade-actions">
231 <button id="trade-accept" type="button">Accept</button>
232 </div>
233 </aside>
234
235 <div id="trade-qty-backdrop" class="modal-backdrop" hidden></div>
236 <aside id="trade-qty-panel" hidden>
237 <header>
238 <h2>Offer quantity</h2>
239 <button id="trade-qty-close" type="button">Close</button>
240 </header>
241 <p id="trade-qty-name"></p>
242 <label class="send-row">Quantity
243 <input id="trade-qty-input" type="number" min="1" step="1" value="1">
244 </label>
245 <button id="trade-qty-confirm" type="button">Offer</button>
246 </aside>
247
213 <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
248 <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
214 <aside id="write-cheque-panel" hidden>
249 <aside id="write-cheque-panel" hidden>
215 <header>
250 <header>
client/src/play/inventory.js +7 −1
@@ -39,6 +39,8 @@ export function initInventory ({
39 39 getLocalName,
40 40 tipArrows = null,
41 41 getSoftClaims = null,
42 onBagSlotActivate = null,
43 bagClicksLocked = null,
42 44 knowsSpell = null,
43 45 getSkillLevels = null,
44 46 getSettings = null,
@@ -246,7 +248,7 @@ export function initInventory ({
246 248 else if (realSlot)
247 249 {
248 250 button.classList.add("soft-claimed");
249 button.title = `${itemDisplayName(realSlot)} (in use at the cauldron)`;
251 button.title = `${itemDisplayName(realSlot)} (in use)`;
250 252 }
251 253 button.addEventListener("dragstart", (event) =>
252 254 {
@@ -306,6 +308,10 @@ export function initInventory ({
306 308 }
307 309 if (!slot)
308 310 { return; }
311 if (bagClicksLocked?.())
312 { return; }
313 if (onBagSlotActivate?.(index, slot))
314 { return; }
309 315 if (bankOpen)
310 316 {
311 317 transferSlot("inventory", index, null);
@@ -39,6 +39,8 @@ export function initInventory ({
39 getLocalName,
39 getLocalName,
40 tipArrows = null,
40 tipArrows = null,
41 getSoftClaims = null,
41 getSoftClaims = null,
42 onBagSlotActivate = null,
43 bagClicksLocked = null,
42 knowsSpell = null,
44 knowsSpell = null,
43 getSkillLevels = null,
45 getSkillLevels = null,
44 getSettings = null,
46 getSettings = null,
@@ -246,7 +248,7 @@ export function initInventory ({
246 else if (realSlot)
248 else if (realSlot)
247 {
249 {
248 button.classList.add("soft-claimed");
250 button.classList.add("soft-claimed");
249 button.title = `${itemDisplayName(realSlot)} (in use at the cauldron)`;
251 button.title = `${itemDisplayName(realSlot)} (in use)`;
250 }
252 }
251 button.addEventListener("dragstart", (event) =>
253 button.addEventListener("dragstart", (event) =>
252 {
254 {
@@ -306,6 +308,10 @@ export function initInventory ({
306 }
308 }
307 if (!slot)
309 if (!slot)
308 { return; }
310 { return; }
311 if (bagClicksLocked?.())
312 { return; }
313 if (onBagSlotActivate?.(index, slot))
314 { return; }
309 if (bankOpen)
315 if (bankOpen)
310 {
316 {
311 transferSlot("inventory", index, null);
317 transferSlot("inventory", index, null);
client/src/play/main.js +92 −1
@@ -24,6 +24,7 @@ import { initStatusEffects } from "./statusEffects.js";
24 24 import { initContextMenu } from "./contextMenu.js";
25 25 import { initDeath } from "./death.js";
26 26 import { initToasts } from "./toasts.js";
27 import { initTrade } from "./trade.js";
27 28 import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
28 29 import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
29 30 import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
@@ -80,6 +81,7 @@ let statusEffectsUi;
80 81 let contextMenu;
81 82 let death;
82 83 let toasts;
84 let trade;
83 85 let questsUi;
84 86 let dialogueUi;
85 87 let shop;
@@ -319,6 +321,7 @@ function uiBlocked ()
319 321 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
320 322 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
321 323 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
324 || trade?.isBlocking()
322 325 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
323 326 || graphicsSettingsUi?.isBlocking?.()
324 327 || pointerOverSpellUi());
@@ -966,6 +969,22 @@ function flushPendingInteract ()
966 969 return;
967 970 }
968 971
972 if (pendingInteract.kind === "trade-accept")
973 {
974 const target = view.entities.get(pendingInteract.fromEntityId);
975 if (!target)
976 {
977 pendingInteract = null;
978 return;
979 }
980 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY)
981 && !(local.tileX === target.tileX && local.tileY === target.tileY))
982 { return; }
983 const invite = pendingInteract.invite;
984 pendingInteract = null;
985 trade?.flushPendingAccept?.(invite);
986 return;
987 }
969 988 if (pendingInteract.kind === "shear")
970 989 {
971 990 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -1264,6 +1283,14 @@ function handleRightClick (event, mouseX, mouseY)
1264 1283 }
1265 1284 if (entity.characterId)
1266 1285 {
1286 items.push({
1287 label: "Trade",
1288 onSelect: () =>
1289 {
1290 clearAllPendingActions();
1291 trade?.requestTrade?.(entity.entityId);
1292 }
1293 });
1267 1294 items.push({
1268 1295 label: `${targetName} info`,
1269 1296 onSelect: () =>
@@ -1761,7 +1788,21 @@ async function main ()
1761 1788 },
1762 1789 getSoftClaims ()
1763 1790 {
1764 return alchemy?.listSoftClaims?.() ?? [];
1791 return [
1792 ...(alchemy?.listSoftClaims?.() ?? []),
1793 ...(trade?.listSoftClaims?.() ?? [])
1794 ];
1795 },
1796 onBagSlotActivate (slotIndex, slot)
1797 {
1798 if (!trade?.isOpen?.())
1799 { return false; }
1800 const real = inventory?.getInventorySlots?.()?.[slotIndex] ?? slot;
1801 return trade.offerBagSlot(slotIndex, real);
1802 },
1803 bagClicksLocked ()
1804 {
1805 return !!trade?.inventoryLocked?.();
1765 1806 },
1766 1807 knowsSpell (spellId)
1767 1808 {
@@ -1843,6 +1884,48 @@ async function main ()
1843 1884 healthUi = initHealth();
1844 1885 statusEffectsUi = initStatusEffects();
1845 1886 toasts = initToasts();
1887 trade = initTrade({
1888 socket: { send (payload) { socket.send(payload); } },
1889 MessageType,
1890 toasts,
1891 getLocalEntity ()
1892 {
1893 return view?.entities.get(view.localEntityId) ?? null;
1894 },
1895 getEntity (id)
1896 {
1897 return view?.entities.get(id) ?? null;
1898 },
1899 approachAdjacentTile,
1900 clearPendingActions: clearAllPendingActions,
1901 setPendingTradeAccept (invite)
1902 {
1903 pendingInteract = {
1904 kind: "trade-accept",
1905 fromEntityId: invite.fromEntityId | 0,
1906 invite
1907 };
1908 },
1909 resolveSpriteUrl (name)
1910 {
1911 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1912 },
1913 resolveImage (name)
1914 {
1915 return game?.images?.[name] ?? null;
1916 },
1917 ensureBagOpen ()
1918 {
1919 const bagPanel = document.getElementById("bag-panel");
1920 if (bagPanel?.hidden)
1921 { bagPanel.hidden = false; }
1922 inventory?.refreshBagDisplay?.();
1923 },
1924 onTradeOpenChanged ()
1925 {
1926 inventory?.refreshBagDisplay?.();
1927 }
1928 });
1846 1929 questsUi = initQuests({
1847 1930 socket: { send (payload) { socket.send(payload); } },
1848 1931 MessageType,
@@ -2328,6 +2411,14 @@ async function main ()
2328 2411 if (playing)
2329 2412 { toasts?.show(message.message); }
2330 2413 break;
2414 case MessageType.tradeInvite:
2415 case MessageType.tradeInviteExpired:
2416 case MessageType.tradeOpen:
2417 case MessageType.tradeState:
2418 case MessageType.tradeClosed:
2419 if (playing)
2420 { trade?.handleMessage?.(message); }
2421 break;
2331 2422 case MessageType.questsSnapshot:
2332 2423 questsUi?.applySnapshot(message);
2333 2424 break;
@@ -24,6 +24,7 @@ import { initStatusEffects } from "./statusEffects.js";
24import { initContextMenu } from "./contextMenu.js";
24import { initContextMenu } from "./contextMenu.js";
25import { initDeath } from "./death.js";
25import { initDeath } from "./death.js";
26import { initToasts } from "./toasts.js";
26import { initToasts } from "./toasts.js";
27import { initTrade } from "./trade.js";
27import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
28import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
28import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
29import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
29import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
30import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
@@ -80,6 +81,7 @@ let statusEffectsUi;
80let contextMenu;
81let contextMenu;
81let death;
82let death;
82let toasts;
83let toasts;
84let trade;
83let questsUi;
85let questsUi;
84let dialogueUi;
86let dialogueUi;
85let shop;
87let shop;
@@ -319,6 +321,7 @@ function uiBlocked ()
319 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
321 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
320 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
322 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
321 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
323 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
324 || trade?.isBlocking()
322 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
325 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
323 || graphicsSettingsUi?.isBlocking?.()
326 || graphicsSettingsUi?.isBlocking?.()
324 || pointerOverSpellUi());
327 || pointerOverSpellUi());
@@ -966,6 +969,22 @@ function flushPendingInteract ()
966 return;
969 return;
967 }
970 }
968
971
972 if (pendingInteract.kind === "trade-accept")
973 {
974 const target = view.entities.get(pendingInteract.fromEntityId);
975 if (!target)
976 {
977 pendingInteract = null;
978 return;
979 }
980 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY)
981 && !(local.tileX === target.tileX && local.tileY === target.tileY))
982 { return; }
983 const invite = pendingInteract.invite;
984 pendingInteract = null;
985 trade?.flushPendingAccept?.(invite);
986 return;
987 }
969 if (pendingInteract.kind === "shear")
988 if (pendingInteract.kind === "shear")
970 {
989 {
971 const target = view.entities.get(pendingInteract.targetEntityId);
990 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -1264,6 +1283,14 @@ function handleRightClick (event, mouseX, mouseY)
1264 }
1283 }
1265 if (entity.characterId)
1284 if (entity.characterId)
1266 {
1285 {
1286 items.push({
1287 label: "Trade",
1288 onSelect: () =>
1289 {
1290 clearAllPendingActions();
1291 trade?.requestTrade?.(entity.entityId);
1292 }
1293 });
1267 items.push({
1294 items.push({
1268 label: `${targetName} info`,
1295 label: `${targetName} info`,
1269 onSelect: () =>
1296 onSelect: () =>
@@ -1761,7 +1788,21 @@ async function main ()
1761 },
1788 },
1762 getSoftClaims ()
1789 getSoftClaims ()
1763 {
1790 {
1764 return alchemy?.listSoftClaims?.() ?? [];
1791 return [
1792 ...(alchemy?.listSoftClaims?.() ?? []),
1793 ...(trade?.listSoftClaims?.() ?? [])
1794 ];
1795 },
1796 onBagSlotActivate (slotIndex, slot)
1797 {
1798 if (!trade?.isOpen?.())
1799 { return false; }
1800 const real = inventory?.getInventorySlots?.()?.[slotIndex] ?? slot;
1801 return trade.offerBagSlot(slotIndex, real);
1802 },
1803 bagClicksLocked ()
1804 {
1805 return !!trade?.inventoryLocked?.();
1765 },
1806 },
1766 knowsSpell (spellId)
1807 knowsSpell (spellId)
1767 {
1808 {
@@ -1843,6 +1884,48 @@ async function main ()
1843 healthUi = initHealth();
1884 healthUi = initHealth();
1844 statusEffectsUi = initStatusEffects();
1885 statusEffectsUi = initStatusEffects();
1845 toasts = initToasts();
1886 toasts = initToasts();
1887 trade = initTrade({
1888 socket: { send (payload) { socket.send(payload); } },
1889 MessageType,
1890 toasts,
1891 getLocalEntity ()
1892 {
1893 return view?.entities.get(view.localEntityId) ?? null;
1894 },
1895 getEntity (id)
1896 {
1897 return view?.entities.get(id) ?? null;
1898 },
1899 approachAdjacentTile,
1900 clearPendingActions: clearAllPendingActions,
1901 setPendingTradeAccept (invite)
1902 {
1903 pendingInteract = {
1904 kind: "trade-accept",
1905 fromEntityId: invite.fromEntityId | 0,
1906 invite
1907 };
1908 },
1909 resolveSpriteUrl (name)
1910 {
1911 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1912 },
1913 resolveImage (name)
1914 {
1915 return game?.images?.[name] ?? null;
1916 },
1917 ensureBagOpen ()
1918 {
1919 const bagPanel = document.getElementById("bag-panel");
1920 if (bagPanel?.hidden)
1921 { bagPanel.hidden = false; }
1922 inventory?.refreshBagDisplay?.();
1923 },
1924 onTradeOpenChanged ()
1925 {
1926 inventory?.refreshBagDisplay?.();
1927 }
1928 });
1846 questsUi = initQuests({
1929 questsUi = initQuests({
1847 socket: { send (payload) { socket.send(payload); } },
1930 socket: { send (payload) { socket.send(payload); } },
1848 MessageType,
1931 MessageType,
@@ -2328,6 +2411,14 @@ async function main ()
2328 if (playing)
2411 if (playing)
2329 { toasts?.show(message.message); }
2412 { toasts?.show(message.message); }
2330 break;
2413 break;
2414 case MessageType.tradeInvite:
2415 case MessageType.tradeInviteExpired:
2416 case MessageType.tradeOpen:
2417 case MessageType.tradeState:
2418 case MessageType.tradeClosed:
2419 if (playing)
2420 { trade?.handleMessage?.(message); }
2421 break;
2331 case MessageType.questsSnapshot:
2422 case MessageType.questsSnapshot:
2332 questsUi?.applySnapshot(message);
2423 questsUi?.applySnapshot(message);
2333 break;
2424 break;
client/src/play/toasts.js +59 −65
@@ -19,7 +19,7 @@ export function initToasts ()
19 19 {
20 20 return {
21 21 show ()
22 {},
22 { return { dismiss () {} }; },
23 23 clearPersistent ()
24 24 {},
25 25 applyRestartStatus ()
@@ -31,13 +31,17 @@ export function initToasts ()
31 31 {
32 32 const text = String(message ?? "").trim();
33 33 if (!text)
34 { return; }
34 { return { dismiss () {} }; }
35 35 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
36 36 const onClick = typeof options.onClick === "function" ? options.onClick : null;
37 const actions = Array.isArray(options.actions) ? options.actions : [];
37 38 const el = document.createElement("div");
38 39 el.className = "toast";
39 40 el.setAttribute("role", "status");
40 el.textContent = text;
41 const textEl = document.createElement("div");
42 textEl.className = "toast-text";
43 textEl.textContent = text;
44 el.append(textEl);
41 45 let dismissed = false;
42 46 const dismiss = () =>
43 47 {
@@ -48,7 +52,28 @@ export function initToasts ()
48 52 el.classList.add("toast-leaving");
49 53 window.setTimeout(() => el.remove(), LEAVE_MS);
50 54 };
51 if (onClick)
55 if (actions.length)
56 {
57 el.classList.add("toast-actions");
58 const row = document.createElement("div");
59 row.className = "toast-action-row";
60 for (const action of actions)
61 {
62 const btn = document.createElement("button");
63 btn.type = "button";
64 btn.className = "toast-action";
65 btn.textContent = action.label ?? "OK";
66 btn.addEventListener("click", (event) =>
67 {
68 event.stopPropagation();
69 action.onClick?.();
70 dismiss();
71 });
72 row.append(btn);
73 }
74 el.append(row);
75 }
76 else if (onClick)
52 77 {
53 78 el.classList.add("toast-clickable");
54 79 el.style.cursor = "pointer";
@@ -64,6 +89,7 @@ export function initToasts ()
64 89 el.classList.add("toast-visible");
65 90 });
66 91 window.setTimeout(dismiss, durationMs);
92 return { dismiss };
67 93 }
68 94
69 95 function clearPersistent (id)
@@ -79,79 +105,47 @@ export function initToasts ()
79 105
80 106 function showPersistent (id, text)
81 107 {
82 const message = String(text ?? "").trim();
83 if (!message)
108 const existing = persistent.get(id);
109 if (existing)
84 110 {
85 clearPersistent(id);
111 existing.el.textContent = text;
86 112 return;
87 113 }
88 let entry = persistent.get(id);
89 if (!entry)
90 {
91 const el = document.createElement("div");
92 el.className = "toast toast-persistent";
93 el.setAttribute("role", "status");
94 el.dataset.toastId = id;
95 root.appendChild(el);
96 entry = { el };
97 persistent.set(id, entry);
98 requestAnimationFrame(() =>
99 {
100 el.classList.add("toast-visible");
101 });
102 }
103 entry.el.textContent = message;
104 }
105
106 function stopRestartCountdown ()
107 {
108 if (restartTick != null)
109 {
110 window.clearInterval(restartTick);
111 restartTick = null;
112 }
113 restartScheduledAt = null;
114 clearPersistent(PERSISTENT_RESTART_ID);
115 }
116
117 function refreshRestartToast ()
118 {
119 if (restartScheduledAt == null)
120 { return; }
121 const remaining = restartScheduledAt - Date.now();
122 if (remaining <= 0)
114 const el = document.createElement("div");
115 el.className = "toast toast-persistent";
116 el.setAttribute("role", "status");
117 el.textContent = text;
118 root.appendChild(el);
119 requestAnimationFrame(() =>
123 120 {
124 showPersistent(PERSISTENT_RESTART_ID, "Server restart for a game update is starting…");
125 return;
126 }
127 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(remaining));
121 el.classList.add("toast-visible");
122 });
123 persistent.set(id, { el, timer: null });
128 124 }
129 125
130 /**
131 * @param {{ scheduled?: boolean, warning?: boolean, scheduledAt?: number | null } | null | undefined} status
132 */
133 function applyRestartStatus (status)
126 function applyRestartStatus (payload)
134 127 {
135 if (!status?.scheduled || !status.scheduledAt)
128 const scheduledAt = payload?.scheduledAt ?? null;
129 if (!scheduledAt)
136 130 {
137 stopRestartCountdown();
131 restartScheduledAt = null;
132 if (restartTick != null)
133 {
134 clearInterval(restartTick);
135 restartTick = null;
136 }
137 clearPersistent(PERSISTENT_RESTART_ID);
138 138 return;
139 139 }
140 if (!status.warning)
140 restartScheduledAt = scheduledAt;
141 const tick = () =>
141 142 {
142 stopRestartCountdown();
143 return;
144 }
145 restartScheduledAt = Number(status.scheduledAt);
146 refreshRestartToast();
143 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(restartScheduledAt, Date.now()));
144 };
145 tick();
147 146 if (restartTick == null)
148 { restartTick = window.setInterval(refreshRestartToast, 1000); }
147 { restartTick = window.setInterval(tick, 1000); }
149 148 }
150 149
151 return {
152 show,
153 showPersistent,
154 clearPersistent,
155 applyRestartStatus
156 };
150 return { show, clearPersistent, applyRestartStatus };
157 151 }
@@ -19,7 +19,7 @@ export function initToasts ()
19 {
19 {
20 return {
20 return {
21 show ()
21 show ()
22 {},
22 { return { dismiss () {} }; },
23 clearPersistent ()
23 clearPersistent ()
24 {},
24 {},
25 applyRestartStatus ()
25 applyRestartStatus ()
@@ -31,13 +31,17 @@ export function initToasts ()
31 {
31 {
32 const text = String(message ?? "").trim();
32 const text = String(message ?? "").trim();
33 if (!text)
33 if (!text)
34 { return; }
34 { return { dismiss () {} }; }
35 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
35 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
36 const onClick = typeof options.onClick === "function" ? options.onClick : null;
36 const onClick = typeof options.onClick === "function" ? options.onClick : null;
37 const actions = Array.isArray(options.actions) ? options.actions : [];
37 const el = document.createElement("div");
38 const el = document.createElement("div");
38 el.className = "toast";
39 el.className = "toast";
39 el.setAttribute("role", "status");
40 el.setAttribute("role", "status");
40 el.textContent = text;
41 const textEl = document.createElement("div");
42 textEl.className = "toast-text";
43 textEl.textContent = text;
44 el.append(textEl);
41 let dismissed = false;
45 let dismissed = false;
42 const dismiss = () =>
46 const dismiss = () =>
43 {
47 {
@@ -48,7 +52,28 @@ export function initToasts ()
48 el.classList.add("toast-leaving");
52 el.classList.add("toast-leaving");
49 window.setTimeout(() => el.remove(), LEAVE_MS);
53 window.setTimeout(() => el.remove(), LEAVE_MS);
50 };
54 };
51 if (onClick)
55 if (actions.length)
56 {
57 el.classList.add("toast-actions");
58 const row = document.createElement("div");
59 row.className = "toast-action-row";
60 for (const action of actions)
61 {
62 const btn = document.createElement("button");
63 btn.type = "button";
64 btn.className = "toast-action";
65 btn.textContent = action.label ?? "OK";
66 btn.addEventListener("click", (event) =>
67 {
68 event.stopPropagation();
69 action.onClick?.();
70 dismiss();
71 });
72 row.append(btn);
73 }
74 el.append(row);
75 }
76 else if (onClick)
52 {
77 {
53 el.classList.add("toast-clickable");
78 el.classList.add("toast-clickable");
54 el.style.cursor = "pointer";
79 el.style.cursor = "pointer";
@@ -64,6 +89,7 @@ export function initToasts ()
64 el.classList.add("toast-visible");
89 el.classList.add("toast-visible");
65 });
90 });
66 window.setTimeout(dismiss, durationMs);
91 window.setTimeout(dismiss, durationMs);
92 return { dismiss };
67 }
93 }
68
94
69 function clearPersistent (id)
95 function clearPersistent (id)
@@ -79,79 +105,47 @@ export function initToasts ()
79
105
80 function showPersistent (id, text)
106 function showPersistent (id, text)
81 {
107 {
82 const message = String(text ?? "").trim();
108 const existing = persistent.get(id);
83 if (!message)
109 if (existing)
84 {
110 {
85 clearPersistent(id);
111 existing.el.textContent = text;
86 return;
112 return;
87 }
113 }
88 let entry = persistent.get(id);
114 const el = document.createElement("div");
89 if (!entry)
115 el.className = "toast toast-persistent";
90 {
116 el.setAttribute("role", "status");
91 const el = document.createElement("div");
117 el.textContent = text;
92 el.className = "toast toast-persistent";
118 root.appendChild(el);
93 el.setAttribute("role", "status");
119 requestAnimationFrame(() =>
94 el.dataset.toastId = id;
95 root.appendChild(el);
96 entry = { el };
97 persistent.set(id, entry);
98 requestAnimationFrame(() =>
99 {
100 el.classList.add("toast-visible");
101 });
102 }
103 entry.el.textContent = message;
104 }
105
106 function stopRestartCountdown ()
107 {
108 if (restartTick != null)
109 {
110 window.clearInterval(restartTick);
111 restartTick = null;
112 }
113 restartScheduledAt = null;
114 clearPersistent(PERSISTENT_RESTART_ID);
115 }
116
117 function refreshRestartToast ()
118 {
119 if (restartScheduledAt == null)
120 { return; }
121 const remaining = restartScheduledAt - Date.now();
122 if (remaining <= 0)
123 {
120 {
124 showPersistent(PERSISTENT_RESTART_ID, "Server restart for a game update is starting…");
121 el.classList.add("toast-visible");
125 return;
122 });
126 }
123 persistent.set(id, { el, timer: null });
127 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(remaining));
128 }
124 }
129
125
130 /**
126 function applyRestartStatus (payload)
131 * @param {{ scheduled?: boolean, warning?: boolean, scheduledAt?: number | null } | null | undefined} status
132 */
133 function applyRestartStatus (status)
134 {
127 {
135 if (!status?.scheduled || !status.scheduledAt)
128 const scheduledAt = payload?.scheduledAt ?? null;
129 if (!scheduledAt)
136 {
130 {
137 stopRestartCountdown();
131 restartScheduledAt = null;
132 if (restartTick != null)
133 {
134 clearInterval(restartTick);
135 restartTick = null;
136 }
137 clearPersistent(PERSISTENT_RESTART_ID);
138 return;
138 return;
139 }
139 }
140 if (!status.warning)
140 restartScheduledAt = scheduledAt;
141 const tick = () =>
141 {
142 {
142 stopRestartCountdown();
143 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(restartScheduledAt, Date.now()));
143 return;
144 };
144 }
145 tick();
145 restartScheduledAt = Number(status.scheduledAt);
146 refreshRestartToast();
147 if (restartTick == null)
146 if (restartTick == null)
148 { restartTick = window.setInterval(refreshRestartToast, 1000); }
147 { restartTick = window.setInterval(tick, 1000); }
149 }
148 }
150
149
151 return {
150 return { show, clearPersistent, applyRestartStatus };
152 show,
153 showPersistent,
154 clearPersistent,
155 applyRestartStatus
156 };
157}
151}
client/src/play/trade.js added +384 −0
@@ -0,0 +1,384 @@
1 import {
2 itemAssetPathForStack,
3 itemDisplayName,
4 formatQuantity
5 } from "/shared/definitions/items.js";
6 import { applyItemIcon } from "../render/potionIcon.js";
7 import { isAdjacentTile } from "/shared/navigation/adjacency.js";
8
9 /**
10 * Player-to-player trade UI + invite toasts.
11 */
12 export function initTrade ({
13 socket,
14 MessageType,
15 toasts,
16 getLocalEntity,
17 getEntity,
18 approachAdjacentTile,
19 clearPendingActions,
20 setPendingTradeAccept,
21 resolveSpriteUrl,
22 resolveImage,
23 ensureBagOpen,
24 onTradeOpenChanged
25 })
26 {
27 const backdrop = document.getElementById("trade-backdrop");
28 const panel = document.getElementById("trade-panel");
29 const partnerEl = document.getElementById("trade-partner");
30 const giveGrid = document.getElementById("trade-give-grid");
31 const receiveGrid = document.getElementById("trade-receive-grid");
32 const acceptBtn = document.getElementById("trade-accept");
33 const cancelBtn = document.getElementById("trade-cancel");
34 const statusEl = document.getElementById("trade-status");
35 const qtyBackdrop = document.getElementById("trade-qty-backdrop");
36 const qtyPanel = document.getElementById("trade-qty-panel");
37 const qtyName = document.getElementById("trade-qty-name");
38 const qtyInput = document.getElementById("trade-qty-input");
39 const qtyConfirm = document.getElementById("trade-qty-confirm");
40 const qtyClose = document.getElementById("trade-qty-close");
41
42 let open = false;
43 let partnerName = "";
44 let partnerEntityId = null;
45 let youAccepted = false;
46 let theyAccepted = false;
47 /** @type {any[]} */
48 let yourOffer = [];
49 /** @type {any[]} */
50 let theirOffer = [];
51 /** @type {Map<string, { dismiss: () => void }>} */
52 const inviteToasts = new Map();
53 let pendingQty = null;
54
55 function isBlocking ()
56 {
57 return open || !!(qtyPanel && !qtyPanel.hidden);
58 }
59
60 function isOpen ()
61 {
62 return open;
63 }
64
65 function listSoftClaims ()
66 {
67 if (!open)
68 { return []; }
69 return yourOffer.map((line) => ({
70 itemId: line.itemId,
71 quantity: line.quantity,
72 instance: line.instance ?? null
73 }));
74 }
75
76 function closeQty ()
77 {
78 pendingQty = null;
79 if (qtyPanel)
80 { qtyPanel.hidden = true; }
81 if (qtyBackdrop)
82 { qtyBackdrop.hidden = true; }
83 }
84
85 function closeTradeUi ()
86 {
87 open = false;
88 closeQty();
89 if (panel)
90 { panel.hidden = true; }
91 if (backdrop)
92 { backdrop.hidden = true; }
93 partnerEntityId = null;
94 partnerName = "";
95 youAccepted = false;
96 theyAccepted = false;
97 yourOffer = [];
98 theirOffer = [];
99 onTradeOpenChanged?.(false);
100 }
101
102 function renderOfferGrid (el, lines, { theirs = false } = {})
103 {
104 if (!el)
105 { return; }
106 el.replaceChildren();
107 if (!lines.length)
108 {
109 const empty = document.createElement("p");
110 empty.className = "hint";
111 empty.textContent = theirs ? "Nothing yet." : "Click bag items to offer them.";
112 el.append(empty);
113 return;
114 }
115 for (const line of lines)
116 {
117 const btn = document.createElement("button");
118 btn.type = "button";
119 btn.className = "item-slot";
120 btn.title = `${line.displayName ?? "Item"}${line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""}`;
121 const stack = {
122 itemId: line.itemId,
123 quantity: line.quantity,
124 instance: line.instance ?? null
125 };
126 applyItemIcon(btn, stack, {
127 resolveSpriteUrl,
128 resolveImage,
129 pathForStack: itemAssetPathForStack
130 });
131 if (line.quantity > 1)
132 {
133 const qty = document.createElement("span");
134 qty.className = "qty";
135 qty.textContent = formatQuantity(line.quantity);
136 btn.append(qty);
137 }
138 if (!theirs && !youAccepted)
139 {
140 btn.addEventListener("click", () =>
141 {
142 socket.send({
143 type: MessageType.tradeOfferRemove,
144 bagSlotIndex: line.bagSlotIndex
145 });
146 });
147 }
148 else
149 { btn.disabled = true; }
150 el.append(btn);
151 }
152 }
153
154 function render ()
155 {
156 if (!open)
157 { return; }
158 if (partnerEl)
159 { partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; }
160 renderOfferGrid(giveGrid, yourOffer, { theirs: false });
161 renderOfferGrid(receiveGrid, theirOffer, { theirs: true });
162 if (acceptBtn)
163 {
164 acceptBtn.textContent = youAccepted ? "Accepted" : "Accept";
165 acceptBtn.classList.toggle("active", !!youAccepted);
166 acceptBtn.disabled = false;
167 }
168 if (statusEl)
169 {
170 if (youAccepted && theyAccepted)
171 { statusEl.textContent = "Confirming…"; }
172 else if (theyAccepted)
173 { statusEl.textContent = `${partnerName} has accepted.`; }
174 else if (youAccepted)
175 { statusEl.textContent = "Waiting for them to accept…"; }
176 else
177 { statusEl.textContent = ""; }
178 }
179 }
180
181 function applyState (message)
182 {
183 youAccepted = !!message.youAccepted;
184 theyAccepted = !!message.theyAccepted;
185 yourOffer = message.yourOffer ?? [];
186 theirOffer = message.theirOffer ?? [];
187 render();
188 onTradeOpenChanged?.(true);
189 }
190
191 function openTrade (message)
192 {
193 open = true;
194 partnerName = message.partnerName ?? "Player";
195 partnerEntityId = message.partnerEntityId | 0;
196 if (panel)
197 { panel.hidden = false; }
198 if (backdrop)
199 { backdrop.hidden = false; }
200 ensureBagOpen?.();
201 applyState(message);
202 }
203
204 function requestTrade (targetEntityId)
205 {
206 clearPendingActions?.();
207 socket.send({
208 type: MessageType.tradeRequest,
209 targetEntityId: targetEntityId | 0
210 });
211 }
212
213 function respondAccept (invite)
214 {
215 const local = getLocalEntity?.();
216 const partner = getEntity?.(invite.fromEntityId);
217 if (!local || !partner)
218 {
219 socket.send({
220 type: MessageType.tradeRespondInvite,
221 inviteId: invite.inviteId,
222 accept: true
223 });
224 return;
225 }
226 if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY)
227 || (local.tileX === partner.tileX && local.tileY === partner.tileY))
228 {
229 socket.send({
230 type: MessageType.tradeRespondInvite,
231 inviteId: invite.inviteId,
232 accept: true
233 });
234 return;
235 }
236 setPendingTradeAccept?.(invite);
237 approachAdjacentTile?.(partner.tileX, partner.tileY);
238 }
239
240 function showInvite (message)
241 {
242 const inviteId = message.inviteId;
243 inviteToasts.get(inviteId)?.dismiss?.();
244 const fromName = message.fromName || "Someone";
245 const handle = toasts?.show?.(
246 `${fromName} wishes to trade with you`,
247 {
248 durationMs: Math.max(1000, (message.expiresAt | 0) - Date.now()) || 60_000,
249 actions: [
250 {
251 label: "Accept",
252 onClick: () =>
253 {
254 inviteToasts.delete(inviteId);
255 respondAccept(message);
256 }
257 },
258 {
259 label: "Reject",
260 onClick: () =>
261 {
262 inviteToasts.delete(inviteId);
263 socket.send({
264 type: MessageType.tradeRespondInvite,
265 inviteId,
266 accept: false
267 });
268 }
269 }
270 ]
271 }
272 );
273 if (handle)
274 { inviteToasts.set(inviteId, handle); }
275 }
276
277 function offerBagSlot (slotIndex, slot)
278 {
279 if (!open || youAccepted || !slot)
280 { return false; }
281 const maxQty = Math.max(1, slot.quantity | 0 || 1);
282 if (maxQty <= 1)
283 {
284 socket.send({
285 type: MessageType.tradeOfferSet,
286 bagSlotIndex: slotIndex,
287 quantity: 1
288 });
289 return true;
290 }
291 pendingQty = { bagSlotIndex: slotIndex, maxQty, name: itemDisplayName(slot) };
292 if (qtyName)
293 { qtyName.textContent = pendingQty.name; }
294 if (qtyInput)
295 {
296 qtyInput.min = "1";
297 qtyInput.max = String(maxQty);
298 qtyInput.value = String(maxQty);
299 }
300 if (qtyPanel)
301 { qtyPanel.hidden = false; }
302 if (qtyBackdrop)
303 { qtyBackdrop.hidden = false; }
304 qtyInput?.focus();
305 qtyInput?.select();
306 return true;
307 }
308
309 acceptBtn?.addEventListener("click", () =>
310 {
311 socket.send({ type: MessageType.tradeAccept });
312 });
313 cancelBtn?.addEventListener("click", () =>
314 {
315 socket.send({ type: MessageType.tradeCancel });
316 });
317 backdrop?.addEventListener("click", () =>
318 {
319 socket.send({ type: MessageType.tradeCancel });
320 });
321 qtyClose?.addEventListener("click", () => closeQty());
322 qtyBackdrop?.addEventListener("click", () => closeQty());
323 qtyConfirm?.addEventListener("click", () =>
324 {
325 if (!pendingQty)
326 { return; }
327 const qty = Math.max(1, Math.min(pendingQty.maxQty, qtyInput?.valueAsNumber || 1));
328 socket.send({
329 type: MessageType.tradeOfferSet,
330 bagSlotIndex: pendingQty.bagSlotIndex,
331 quantity: qty
332 });
333 closeQty();
334 });
335
336 return {
337 isBlocking,
338 isOpen,
339 listSoftClaims,
340 requestTrade,
341 offerBagSlot,
342 inventoryLocked: () => (open && youAccepted) || !!(qtyPanel && !qtyPanel.hidden),
343 flushPendingAccept (invite)
344 {
345 socket.send({
346 type: MessageType.tradeRespondInvite,
347 inviteId: invite.inviteId,
348 accept: true
349 });
350 },
351 handleMessage (message)
352 {
353 if (message.type === MessageType.tradeInvite)
354 {
355 showInvite(message);
356 return true;
357 }
358 if (message.type === MessageType.tradeInviteExpired)
359 {
360 inviteToasts.get(message.inviteId)?.dismiss?.();
361 inviteToasts.delete(message.inviteId);
362 return true;
363 }
364 if (message.type === MessageType.tradeOpen)
365 {
366 openTrade(message);
367 return true;
368 }
369 if (message.type === MessageType.tradeState)
370 {
371 if (open)
372 { applyState(message); }
373 return true;
374 }
375 if (message.type === MessageType.tradeClosed)
376 {
377 closeTradeUi();
378 return true;
379 }
380 return false;
381 },
382 close: closeTradeUi
383 };
384 }
@@ -0,0 +1,384 @@
1import {
2 itemAssetPathForStack,
3 itemDisplayName,
4 formatQuantity
5} from "/shared/definitions/items.js";
6import { applyItemIcon } from "../render/potionIcon.js";
7import { isAdjacentTile } from "/shared/navigation/adjacency.js";
8
9/**
10 * Player-to-player trade UI + invite toasts.
11 */
12export function initTrade ({
13 socket,
14 MessageType,
15 toasts,
16 getLocalEntity,
17 getEntity,
18 approachAdjacentTile,
19 clearPendingActions,
20 setPendingTradeAccept,
21 resolveSpriteUrl,
22 resolveImage,
23 ensureBagOpen,
24 onTradeOpenChanged
25})
26{
27 const backdrop = document.getElementById("trade-backdrop");
28 const panel = document.getElementById("trade-panel");
29 const partnerEl = document.getElementById("trade-partner");
30 const giveGrid = document.getElementById("trade-give-grid");
31 const receiveGrid = document.getElementById("trade-receive-grid");
32 const acceptBtn = document.getElementById("trade-accept");
33 const cancelBtn = document.getElementById("trade-cancel");
34 const statusEl = document.getElementById("trade-status");
35 const qtyBackdrop = document.getElementById("trade-qty-backdrop");
36 const qtyPanel = document.getElementById("trade-qty-panel");
37 const qtyName = document.getElementById("trade-qty-name");
38 const qtyInput = document.getElementById("trade-qty-input");
39 const qtyConfirm = document.getElementById("trade-qty-confirm");
40 const qtyClose = document.getElementById("trade-qty-close");
41
42 let open = false;
43 let partnerName = "";
44 let partnerEntityId = null;
45 let youAccepted = false;
46 let theyAccepted = false;
47 /** @type {any[]} */
48 let yourOffer = [];
49 /** @type {any[]} */
50 let theirOffer = [];
51 /** @type {Map<string, { dismiss: () => void }>} */
52 const inviteToasts = new Map();
53 let pendingQty = null;
54
55 function isBlocking ()
56 {
57 return open || !!(qtyPanel && !qtyPanel.hidden);
58 }
59
60 function isOpen ()
61 {
62 return open;
63 }
64
65 function listSoftClaims ()
66 {
67 if (!open)
68 { return []; }
69 return yourOffer.map((line) => ({
70 itemId: line.itemId,
71 quantity: line.quantity,
72 instance: line.instance ?? null
73 }));
74 }
75
76 function closeQty ()
77 {
78 pendingQty = null;
79 if (qtyPanel)
80 { qtyPanel.hidden = true; }
81 if (qtyBackdrop)
82 { qtyBackdrop.hidden = true; }
83 }
84
85 function closeTradeUi ()
86 {
87 open = false;
88 closeQty();
89 if (panel)
90 { panel.hidden = true; }
91 if (backdrop)
92 { backdrop.hidden = true; }
93 partnerEntityId = null;
94 partnerName = "";
95 youAccepted = false;
96 theyAccepted = false;
97 yourOffer = [];
98 theirOffer = [];
99 onTradeOpenChanged?.(false);
100 }
101
102 function renderOfferGrid (el, lines, { theirs = false } = {})
103 {
104 if (!el)
105 { return; }
106 el.replaceChildren();
107 if (!lines.length)
108 {
109 const empty = document.createElement("p");
110 empty.className = "hint";
111 empty.textContent = theirs ? "Nothing yet." : "Click bag items to offer them.";
112 el.append(empty);
113 return;
114 }
115 for (const line of lines)
116 {
117 const btn = document.createElement("button");
118 btn.type = "button";
119 btn.className = "item-slot";
120 btn.title = `${line.displayName ?? "Item"}${line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""}`;
121 const stack = {
122 itemId: line.itemId,
123 quantity: line.quantity,
124 instance: line.instance ?? null
125 };
126 applyItemIcon(btn, stack, {
127 resolveSpriteUrl,
128 resolveImage,
129 pathForStack: itemAssetPathForStack
130 });
131 if (line.quantity > 1)
132 {
133 const qty = document.createElement("span");
134 qty.className = "qty";
135 qty.textContent = formatQuantity(line.quantity);
136 btn.append(qty);
137 }
138 if (!theirs && !youAccepted)
139 {
140 btn.addEventListener("click", () =>
141 {
142 socket.send({
143 type: MessageType.tradeOfferRemove,
144 bagSlotIndex: line.bagSlotIndex
145 });
146 });
147 }
148 else
149 { btn.disabled = true; }
150 el.append(btn);
151 }
152 }
153
154 function render ()
155 {
156 if (!open)
157 { return; }
158 if (partnerEl)
159 { partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; }
160 renderOfferGrid(giveGrid, yourOffer, { theirs: false });
161 renderOfferGrid(receiveGrid, theirOffer, { theirs: true });
162 if (acceptBtn)
163 {
164 acceptBtn.textContent = youAccepted ? "Accepted" : "Accept";
165 acceptBtn.classList.toggle("active", !!youAccepted);
166 acceptBtn.disabled = false;
167 }
168 if (statusEl)
169 {
170 if (youAccepted && theyAccepted)
171 { statusEl.textContent = "Confirming…"; }
172 else if (theyAccepted)
173 { statusEl.textContent = `${partnerName} has accepted.`; }
174 else if (youAccepted)
175 { statusEl.textContent = "Waiting for them to accept…"; }
176 else
177 { statusEl.textContent = ""; }
178 }
179 }
180
181 function applyState (message)
182 {
183 youAccepted = !!message.youAccepted;
184 theyAccepted = !!message.theyAccepted;
185 yourOffer = message.yourOffer ?? [];
186 theirOffer = message.theirOffer ?? [];
187 render();
188 onTradeOpenChanged?.(true);
189 }
190
191 function openTrade (message)
192 {
193 open = true;
194 partnerName = message.partnerName ?? "Player";
195 partnerEntityId = message.partnerEntityId | 0;
196 if (panel)
197 { panel.hidden = false; }
198 if (backdrop)
199 { backdrop.hidden = false; }
200 ensureBagOpen?.();
201 applyState(message);
202 }
203
204 function requestTrade (targetEntityId)
205 {
206 clearPendingActions?.();
207 socket.send({
208 type: MessageType.tradeRequest,
209 targetEntityId: targetEntityId | 0
210 });
211 }
212
213 function respondAccept (invite)
214 {
215 const local = getLocalEntity?.();
216 const partner = getEntity?.(invite.fromEntityId);
217 if (!local || !partner)
218 {
219 socket.send({
220 type: MessageType.tradeRespondInvite,
221 inviteId: invite.inviteId,
222 accept: true
223 });
224 return;
225 }
226 if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY)
227 || (local.tileX === partner.tileX && local.tileY === partner.tileY))
228 {
229 socket.send({
230 type: MessageType.tradeRespondInvite,
231 inviteId: invite.inviteId,
232 accept: true
233 });
234 return;
235 }
236 setPendingTradeAccept?.(invite);
237 approachAdjacentTile?.(partner.tileX, partner.tileY);
238 }
239
240 function showInvite (message)
241 {
242 const inviteId = message.inviteId;
243 inviteToasts.get(inviteId)?.dismiss?.();
244 const fromName = message.fromName || "Someone";
245 const handle = toasts?.show?.(
246 `${fromName} wishes to trade with you`,
247 {
248 durationMs: Math.max(1000, (message.expiresAt | 0) - Date.now()) || 60_000,
249 actions: [
250 {
251 label: "Accept",
252 onClick: () =>
253 {
254 inviteToasts.delete(inviteId);
255 respondAccept(message);
256 }
257 },
258 {
259 label: "Reject",
260 onClick: () =>
261 {
262 inviteToasts.delete(inviteId);
263 socket.send({
264 type: MessageType.tradeRespondInvite,
265 inviteId,
266 accept: false
267 });
268 }
269 }
270 ]
271 }
272 );
273 if (handle)
274 { inviteToasts.set(inviteId, handle); }
275 }
276
277 function offerBagSlot (slotIndex, slot)
278 {
279 if (!open || youAccepted || !slot)
280 { return false; }
281 const maxQty = Math.max(1, slot.quantity | 0 || 1);
282 if (maxQty <= 1)
283 {
284 socket.send({
285 type: MessageType.tradeOfferSet,
286 bagSlotIndex: slotIndex,
287 quantity: 1
288 });
289 return true;
290 }
291 pendingQty = { bagSlotIndex: slotIndex, maxQty, name: itemDisplayName(slot) };
292 if (qtyName)
293 { qtyName.textContent = pendingQty.name; }
294 if (qtyInput)
295 {
296 qtyInput.min = "1";
297 qtyInput.max = String(maxQty);
298 qtyInput.value = String(maxQty);
299 }
300 if (qtyPanel)
301 { qtyPanel.hidden = false; }
302 if (qtyBackdrop)
303 { qtyBackdrop.hidden = false; }
304 qtyInput?.focus();
305 qtyInput?.select();
306 return true;
307 }
308
309 acceptBtn?.addEventListener("click", () =>
310 {
311 socket.send({ type: MessageType.tradeAccept });
312 });
313 cancelBtn?.addEventListener("click", () =>
314 {
315 socket.send({ type: MessageType.tradeCancel });
316 });
317 backdrop?.addEventListener("click", () =>
318 {
319 socket.send({ type: MessageType.tradeCancel });
320 });
321 qtyClose?.addEventListener("click", () => closeQty());
322 qtyBackdrop?.addEventListener("click", () => closeQty());
323 qtyConfirm?.addEventListener("click", () =>
324 {
325 if (!pendingQty)
326 { return; }
327 const qty = Math.max(1, Math.min(pendingQty.maxQty, qtyInput?.valueAsNumber || 1));
328 socket.send({
329 type: MessageType.tradeOfferSet,
330 bagSlotIndex: pendingQty.bagSlotIndex,
331 quantity: qty
332 });
333 closeQty();
334 });
335
336 return {
337 isBlocking,
338 isOpen,
339 listSoftClaims,
340 requestTrade,
341 offerBagSlot,
342 inventoryLocked: () => (open && youAccepted) || !!(qtyPanel && !qtyPanel.hidden),
343 flushPendingAccept (invite)
344 {
345 socket.send({
346 type: MessageType.tradeRespondInvite,
347 inviteId: invite.inviteId,
348 accept: true
349 });
350 },
351 handleMessage (message)
352 {
353 if (message.type === MessageType.tradeInvite)
354 {
355 showInvite(message);
356 return true;
357 }
358 if (message.type === MessageType.tradeInviteExpired)
359 {
360 inviteToasts.get(message.inviteId)?.dismiss?.();
361 inviteToasts.delete(message.inviteId);
362 return true;
363 }
364 if (message.type === MessageType.tradeOpen)
365 {
366 openTrade(message);
367 return true;
368 }
369 if (message.type === MessageType.tradeState)
370 {
371 if (open)
372 { applyState(message); }
373 return true;
374 }
375 if (message.type === MessageType.tradeClosed)
376 {
377 closeTradeUi();
378 return true;
379 }
380 return false;
381 },
382 close: closeTradeUi
383 };
384}
client/ui/play.css +95 −0
@@ -236,9 +236,104 @@ body {
236 236 text-align: center;
237 237 color: #f0ebe0;
238 238 white-space: pre-line;
239 box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
239 240 opacity: 0;
240 241 transform: translateY(-8px);
241 242 transition: opacity 0.22s ease, transform 0.22s ease;
243 pointer-events: auto;
244 }
245
246 .toast-action-row {
247 display: flex;
248 gap: 0.5rem;
249 justify-content: flex-end;
250 margin-top: 0.55rem;
251 }
252
253 .toast-action {
254 font: inherit;
255 font-size: 0.85rem;
256 padding: 0.25rem 0.7rem;
257 border: 1px solid #5a6578;
258 background: #1c2230;
259 color: #e8e4d9;
260 cursor: pointer;
261 }
262
263 .toast-action:hover {
264 border-color: #8a93a5;
265 }
266
267 #trade-backdrop {
268 z-index: 20;
269 }
270
271 #trade-panel {
272 position: fixed;
273 z-index: 21;
274 left: 50%;
275 top: 50%;
276 transform: translate(-50%, -50%);
277 width: min(520px, 94vw);
278 max-height: min(80vh, 640px);
279 overflow: auto;
280 background: rgba(16, 18, 22, 0.96);
281 border: 1px solid #3a4250;
282 padding: 0.75rem 1rem 1rem;
283 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
284 }
285
286 #trade-panel header {
287 display: flex;
288 align-items: center;
289 justify-content: space-between;
290 gap: 0.75rem;
291 margin-bottom: 0.5rem;
292 }
293
294 #trade-panel h2 {
295 margin: 0;
296 font-size: 1.1rem;
297 }
298
299 .trade-columns {
300 display: grid;
301 grid-template-columns: 1fr 1fr;
302 gap: 0.75rem;
303 }
304
305 .trade-column h3 {
306 margin: 0 0 0.4rem;
307 font-size: 0.9rem;
308 font-weight: 600;
309 color: #c8c2b4;
310 }
311
312 .trade-offer-grid {
313 min-height: 7rem;
314 display: flex;
315 flex-wrap: wrap;
316 gap: 0.35rem;
317 align-content: flex-start;
318 padding: 0.4rem;
319 border: 1px solid #2e3542;
320 background: rgba(8, 10, 14, 0.55);
321 }
322
323 .trade-actions {
324 display: flex;
325 gap: 0.6rem;
326 justify-content: flex-end;
327 margin-top: 0.75rem;
328 }
329
330 #trade-accept.active {
331 background: #2a4a32;
332 border-color: #4a8a58;
333 }
334
335 #trade-qty-panel {
336 z-index: 22;
242 337 }
243 338
244 339 .toast.toast-visible {
@@ -236,9 +236,104 @@ body {
236 text-align: center;
236 text-align: center;
237 color: #f0ebe0;
237 color: #f0ebe0;
238 white-space: pre-line;
238 white-space: pre-line;
239 box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
239 opacity: 0;
240 opacity: 0;
240 transform: translateY(-8px);
241 transform: translateY(-8px);
241 transition: opacity 0.22s ease, transform 0.22s ease;
242 transition: opacity 0.22s ease, transform 0.22s ease;
243 pointer-events: auto;
244}
245
246.toast-action-row {
247 display: flex;
248 gap: 0.5rem;
249 justify-content: flex-end;
250 margin-top: 0.55rem;
251}
252
253.toast-action {
254 font: inherit;
255 font-size: 0.85rem;
256 padding: 0.25rem 0.7rem;
257 border: 1px solid #5a6578;
258 background: #1c2230;
259 color: #e8e4d9;
260 cursor: pointer;
261}
262
263.toast-action:hover {
264 border-color: #8a93a5;
265}
266
267#trade-backdrop {
268 z-index: 20;
269}
270
271#trade-panel {
272 position: fixed;
273 z-index: 21;
274 left: 50%;
275 top: 50%;
276 transform: translate(-50%, -50%);
277 width: min(520px, 94vw);
278 max-height: min(80vh, 640px);
279 overflow: auto;
280 background: rgba(16, 18, 22, 0.96);
281 border: 1px solid #3a4250;
282 padding: 0.75rem 1rem 1rem;
283 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
284}
285
286#trade-panel header {
287 display: flex;
288 align-items: center;
289 justify-content: space-between;
290 gap: 0.75rem;
291 margin-bottom: 0.5rem;
292}
293
294#trade-panel h2 {
295 margin: 0;
296 font-size: 1.1rem;
297}
298
299.trade-columns {
300 display: grid;
301 grid-template-columns: 1fr 1fr;
302 gap: 0.75rem;
303}
304
305.trade-column h3 {
306 margin: 0 0 0.4rem;
307 font-size: 0.9rem;
308 font-weight: 600;
309 color: #c8c2b4;
310}
311
312.trade-offer-grid {
313 min-height: 7rem;
314 display: flex;
315 flex-wrap: wrap;
316 gap: 0.35rem;
317 align-content: flex-start;
318 padding: 0.4rem;
319 border: 1px solid #2e3542;
320 background: rgba(8, 10, 14, 0.55);
321}
322
323.trade-actions {
324 display: flex;
325 gap: 0.6rem;
326 justify-content: flex-end;
327 margin-top: 0.75rem;
328}
329
330#trade-accept.active {
331 background: #2a4a32;
332 border-color: #4a8a58;
333}
334
335#trade-qty-panel {
336 z-index: 22;
242}
337}
243
338
244.toast.toast-visible {
339.toast.toast-visible {
server/src/gateway/websocket.js +111 −0
@@ -821,6 +821,54 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
821 821 destination: message.destination === "bank" ? "bank" : "church"
822 822 });
823 823 break;
824 case MessageType.tradeRequest:
825 requirePlaying(session);
826 simulation.enqueue(session.id, {
827 type: "trade-request",
828 characterId: session.characterId,
829 targetEntityId: message.targetEntityId | 0
830 });
831 break;
832 case MessageType.tradeRespondInvite:
833 requirePlaying(session);
834 simulation.enqueue(session.id, {
835 type: "trade-respond-invite",
836 characterId: session.characterId,
837 inviteId: message.inviteId,
838 accept: !!message.accept
839 });
840 break;
841 case MessageType.tradeOfferSet:
842 requirePlaying(session);
843 simulation.enqueue(session.id, {
844 type: "trade-offer-set",
845 characterId: session.characterId,
846 bagSlotIndex: message.bagSlotIndex | 0,
847 quantity: message.quantity | 0 || 1
848 });
849 break;
850 case MessageType.tradeOfferRemove:
851 requirePlaying(session);
852 simulation.enqueue(session.id, {
853 type: "trade-offer-remove",
854 characterId: session.characterId,
855 bagSlotIndex: message.bagSlotIndex | 0
856 });
857 break;
858 case MessageType.tradeAccept:
859 requirePlaying(session);
860 simulation.enqueue(session.id, {
861 type: "trade-accept",
862 characterId: session.characterId
863 });
864 break;
865 case MessageType.tradeCancel:
866 requirePlaying(session);
867 simulation.enqueue(session.id, {
868 type: "trade-cancel",
869 characterId: session.characterId
870 });
871 break;
824 872 case MessageType.sendPigeon:
825 873 requirePlaying(session);
826 874 {
@@ -1633,6 +1681,69 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1633 1681 { send(session, { type: MessageType.toast, message: event.message }); }
1634 1682 continue;
1635 1683 }
1684 if (event.type === "trade-invite")
1685 {
1686 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1687 if (session)
1688 {
1689 send(session, {
1690 type: MessageType.tradeInvite,
1691 inviteId: event.inviteId,
1692 fromCharacterId: event.fromCharacterId,
1693 fromEntityId: event.fromEntityId,
1694 fromName: event.fromName,
1695 expiresAt: event.expiresAt
1696 });
1697 }
1698 continue;
1699 }
1700 if (event.type === "trade-invite-expired")
1701 {
1702 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1703 if (session)
1704 { send(session, { type: MessageType.tradeInviteExpired, inviteId: event.inviteId }); }
1705 continue;
1706 }
1707 if (event.type === "trade-open")
1708 {
1709 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1710 if (session)
1711 {
1712 send(session, {
1713 type: MessageType.tradeOpen,
1714 partnerCharacterId: event.partnerCharacterId,
1715 partnerEntityId: event.partnerEntityId,
1716 partnerName: event.partnerName,
1717 youAccepted: event.youAccepted,
1718 theyAccepted: event.theyAccepted,
1719 yourOffer: event.yourOffer,
1720 theirOffer: event.theirOffer
1721 });
1722 }
1723 continue;
1724 }
1725 if (event.type === "trade-state")
1726 {
1727 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1728 if (session)
1729 {
1730 send(session, {
1731 type: MessageType.tradeState,
1732 youAccepted: event.youAccepted,
1733 theyAccepted: event.theyAccepted,
1734 yourOffer: event.yourOffer,
1735 theirOffer: event.theirOffer
1736 });
1737 }
1738 continue;
1739 }
1740 if (event.type === "trade-closed")
1741 {
1742 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1743 if (session)
1744 { send(session, { type: MessageType.tradeClosed }); }
1745 continue;
1746 }
1636 1747 if (event.type === "quests-snapshot")
1637 1748 {
1638 1749 const session = event.sessionId != null
@@ -821,6 +821,54 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
821 destination: message.destination === "bank" ? "bank" : "church"
821 destination: message.destination === "bank" ? "bank" : "church"
822 });
822 });
823 break;
823 break;
824 case MessageType.tradeRequest:
825 requirePlaying(session);
826 simulation.enqueue(session.id, {
827 type: "trade-request",
828 characterId: session.characterId,
829 targetEntityId: message.targetEntityId | 0
830 });
831 break;
832 case MessageType.tradeRespondInvite:
833 requirePlaying(session);
834 simulation.enqueue(session.id, {
835 type: "trade-respond-invite",
836 characterId: session.characterId,
837 inviteId: message.inviteId,
838 accept: !!message.accept
839 });
840 break;
841 case MessageType.tradeOfferSet:
842 requirePlaying(session);
843 simulation.enqueue(session.id, {
844 type: "trade-offer-set",
845 characterId: session.characterId,
846 bagSlotIndex: message.bagSlotIndex | 0,
847 quantity: message.quantity | 0 || 1
848 });
849 break;
850 case MessageType.tradeOfferRemove:
851 requirePlaying(session);
852 simulation.enqueue(session.id, {
853 type: "trade-offer-remove",
854 characterId: session.characterId,
855 bagSlotIndex: message.bagSlotIndex | 0
856 });
857 break;
858 case MessageType.tradeAccept:
859 requirePlaying(session);
860 simulation.enqueue(session.id, {
861 type: "trade-accept",
862 characterId: session.characterId
863 });
864 break;
865 case MessageType.tradeCancel:
866 requirePlaying(session);
867 simulation.enqueue(session.id, {
868 type: "trade-cancel",
869 characterId: session.characterId
870 });
871 break;
824 case MessageType.sendPigeon:
872 case MessageType.sendPigeon:
825 requirePlaying(session);
873 requirePlaying(session);
826 {
874 {
@@ -1633,6 +1681,69 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1633 { send(session, { type: MessageType.toast, message: event.message }); }
1681 { send(session, { type: MessageType.toast, message: event.message }); }
1634 continue;
1682 continue;
1635 }
1683 }
1684 if (event.type === "trade-invite")
1685 {
1686 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1687 if (session)
1688 {
1689 send(session, {
1690 type: MessageType.tradeInvite,
1691 inviteId: event.inviteId,
1692 fromCharacterId: event.fromCharacterId,
1693 fromEntityId: event.fromEntityId,
1694 fromName: event.fromName,
1695 expiresAt: event.expiresAt
1696 });
1697 }
1698 continue;
1699 }
1700 if (event.type === "trade-invite-expired")
1701 {
1702 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1703 if (session)
1704 { send(session, { type: MessageType.tradeInviteExpired, inviteId: event.inviteId }); }
1705 continue;
1706 }
1707 if (event.type === "trade-open")
1708 {
1709 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1710 if (session)
1711 {
1712 send(session, {
1713 type: MessageType.tradeOpen,
1714 partnerCharacterId: event.partnerCharacterId,
1715 partnerEntityId: event.partnerEntityId,
1716 partnerName: event.partnerName,
1717 youAccepted: event.youAccepted,
1718 theyAccepted: event.theyAccepted,
1719 yourOffer: event.yourOffer,
1720 theirOffer: event.theirOffer
1721 });
1722 }
1723 continue;
1724 }
1725 if (event.type === "trade-state")
1726 {
1727 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1728 if (session)
1729 {
1730 send(session, {
1731 type: MessageType.tradeState,
1732 youAccepted: event.youAccepted,
1733 theyAccepted: event.theyAccepted,
1734 yourOffer: event.yourOffer,
1735 theirOffer: event.theirOffer
1736 });
1737 }
1738 continue;
1739 }
1740 if (event.type === "trade-closed")
1741 {
1742 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1743 if (session)
1744 { send(session, { type: MessageType.tradeClosed }); }
1745 continue;
1746 }
1636 if (event.type === "quests-snapshot")
1747 if (event.type === "quests-snapshot")
1637 {
1748 {
1638 const session = event.sessionId != null
1749 const session = event.sessionId != null
server/src/simulation/simulation.js +22 −0
@@ -53,6 +53,7 @@ import { ItemId } from "../../../shared/definitions/items.js";
53 53 import { seasonIdAt } from "../../../shared/world/season.js";
54 54 import { CourierService } from "../courier/service.js";
55 55 import { MarketService } from "../market/service.js";
56 import { TradeService } from "../trade/service.js";
56 57 import { BountyService } from "../bounty/service.js";
57 58 import { BarberService } from "../barber/service.js";
58 59 import { findReservedChequeIndex } from "../items/bags.js";
@@ -128,6 +129,10 @@ export class Simulation
128 129 worldDb: this.worldDb,
129 130 simulation: this
130 131 });
132 this.trade = new TradeService({
133 stateDb: this.stateDb,
134 simulation: this
135 });
131 136 this.bounty = new BountyService(this.stateDb, this, this.courier);
132 137 this.barber = new BarberService(this.stateDb, this);
133 138 this.quests = new QuestRuntime({
@@ -380,6 +385,8 @@ export class Simulation
380 385 { events.push(...this.courier.step(now, dt)); }
381 386 if (this.market)
382 387 { events.push(...this.market.step(now)); }
388 if (this.trade)
389 { events.push(...this.trade.step(now)); }
383 390
384 391 this.#syncGhosts();
385 392 events.push(...this.pendingPrivate.splice(0));
@@ -861,6 +868,9 @@ export class Simulation
861 868 despawnCharacter (characterId)
862 869 {
863 870 this.market?.leaveExchangeStations?.(characterId);
871 const tradeEvents = this.trade?.onCharacterGone?.(characterId) ?? [];
872 if (tradeEvents.length)
873 { this.pendingPrivate.push(...tradeEvents); }
864 874 const entityId = this.characterEntities.get(characterId);
865 875 if (!entityId)
866 876 {
@@ -1471,6 +1481,18 @@ export class Simulation
1471 1481 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1472 1482 return result?.events ?? [];
1473 1483 }
1484 if (
1485 item.command.type === "trade-request"
1486 || item.command.type === "trade-respond-invite"
1487 || item.command.type === "trade-offer-set"
1488 || item.command.type === "trade-offer-remove"
1489 || item.command.type === "trade-accept"
1490 || item.command.type === "trade-cancel"
1491 )
1492 {
1493 const result = this.trade.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1494 return result?.events ?? [];
1495 }
1474 1496 if (
1475 1497 item.command.type === "open-bounty"
1476 1498 || item.command.type === "raise-bounty"
@@ -53,6 +53,7 @@ import { ItemId } from "../../../shared/definitions/items.js";
53import { seasonIdAt } from "../../../shared/world/season.js";
53import { seasonIdAt } from "../../../shared/world/season.js";
54import { CourierService } from "../courier/service.js";
54import { CourierService } from "../courier/service.js";
55import { MarketService } from "../market/service.js";
55import { MarketService } from "../market/service.js";
56import { TradeService } from "../trade/service.js";
56import { BountyService } from "../bounty/service.js";
57import { BountyService } from "../bounty/service.js";
57import { BarberService } from "../barber/service.js";
58import { BarberService } from "../barber/service.js";
58import { findReservedChequeIndex } from "../items/bags.js";
59import { findReservedChequeIndex } from "../items/bags.js";
@@ -128,6 +129,10 @@ export class Simulation
128 worldDb: this.worldDb,
129 worldDb: this.worldDb,
129 simulation: this
130 simulation: this
130 });
131 });
132 this.trade = new TradeService({
133 stateDb: this.stateDb,
134 simulation: this
135 });
131 this.bounty = new BountyService(this.stateDb, this, this.courier);
136 this.bounty = new BountyService(this.stateDb, this, this.courier);
132 this.barber = new BarberService(this.stateDb, this);
137 this.barber = new BarberService(this.stateDb, this);
133 this.quests = new QuestRuntime({
138 this.quests = new QuestRuntime({
@@ -380,6 +385,8 @@ export class Simulation
380 { events.push(...this.courier.step(now, dt)); }
385 { events.push(...this.courier.step(now, dt)); }
381 if (this.market)
386 if (this.market)
382 { events.push(...this.market.step(now)); }
387 { events.push(...this.market.step(now)); }
388 if (this.trade)
389 { events.push(...this.trade.step(now)); }
383
390
384 this.#syncGhosts();
391 this.#syncGhosts();
385 events.push(...this.pendingPrivate.splice(0));
392 events.push(...this.pendingPrivate.splice(0));
@@ -861,6 +868,9 @@ export class Simulation
861 despawnCharacter (characterId)
868 despawnCharacter (characterId)
862 {
869 {
863 this.market?.leaveExchangeStations?.(characterId);
870 this.market?.leaveExchangeStations?.(characterId);
871 const tradeEvents = this.trade?.onCharacterGone?.(characterId) ?? [];
872 if (tradeEvents.length)
873 { this.pendingPrivate.push(...tradeEvents); }
864 const entityId = this.characterEntities.get(characterId);
874 const entityId = this.characterEntities.get(characterId);
865 if (!entityId)
875 if (!entityId)
866 {
876 {
@@ -1471,6 +1481,18 @@ export class Simulation
1471 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1481 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1472 return result?.events ?? [];
1482 return result?.events ?? [];
1473 }
1483 }
1484 if (
1485 item.command.type === "trade-request"
1486 || item.command.type === "trade-respond-invite"
1487 || item.command.type === "trade-offer-set"
1488 || item.command.type === "trade-offer-remove"
1489 || item.command.type === "trade-accept"
1490 || item.command.type === "trade-cancel"
1491 )
1492 {
1493 const result = this.trade.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
1494 return result?.events ?? [];
1495 }
1474 if (
1496 if (
1475 item.command.type === "open-bounty"
1497 item.command.type === "open-bounty"
1476 || item.command.type === "raise-bounty"
1498 || item.command.type === "raise-bounty"
server/src/trade/service.js added +609 −0
@@ -0,0 +1,609 @@
1 import { randomUUID } from "node:crypto";
2 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
4 import {
5 cloneStack,
6 insertStack,
7 stackQuantity,
8 takeFromSlot
9 } from "../../../shared/items/inventory.js";
10 import { attachOrigins } from "../../../shared/items/origin.js";
11 import {
12 inventorySlotsShortAfterTrade,
13 resolveOfferStacks
14 } from "../../../shared/trade/space.js";
15
16 const INVITE_MS = 60_000;
17 const REJECT_BLOCK_MS = 60_000;
18
19 function userError (message)
20 {
21 const error = new Error(message);
22 error.userFacing = true;
23 return error;
24 }
25
26 export class TradeService
27 {
28 /**
29 * @param {{ simulation: object, stateDb: object }} opts
30 */
31 constructor ({ simulation, stateDb })
32 {
33 this.simulation = simulation;
34 this.stateDb = stateDb;
35 /** @type {Map<string, object>} */
36 this.invites = new Map();
37 /** @type {Map<string, number>} rejectorId:fromId → blockedUntil */
38 this.rejectBlocks = new Map();
39 /** @type {Map<number, object>} characterId → session */
40 this.sessions = new Map();
41 }
42
43 step (now = Date.now())
44 {
45 const events = [];
46 for (const [id, invite] of [...this.invites.entries()])
47 {
48 if (now >= invite.expiresAt)
49 {
50 this.invites.delete(id);
51 events.push({
52 type: "trade-invite-expired",
53 characterId: invite.toCharacterId,
54 inviteId: id
55 });
56 }
57 }
58 for (const [key, until] of [...this.rejectBlocks.entries()])
59 {
60 if (now >= until)
61 { this.rejectBlocks.delete(key); }
62 }
63 for (const [characterId, session] of [...this.sessions.entries()])
64 {
65 if (!this.#partnersAdjacent(session))
66 {
67 events.push(...this.#closeSession(session, "You moved too far apart."));
68 void characterId;
69 }
70 }
71 return events;
72 }
73
74 handleCommand (sessionId, command, now = Date.now())
75 {
76 switch (command.type)
77 {
78 case "trade-request":
79 return this.request(sessionId, command.characterId, command.targetEntityId, now);
80 case "trade-respond-invite":
81 return this.respondInvite(
82 sessionId,
83 command.characterId,
84 command.inviteId,
85 !!command.accept,
86 now
87 );
88 case "trade-offer-set":
89 return this.setOffer(
90 sessionId,
91 command.characterId,
92 command.bagSlotIndex,
93 command.quantity,
94 now
95 );
96 case "trade-offer-remove":
97 return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now);
98 case "trade-accept":
99 return this.accept(sessionId, command.characterId, now);
100 case "trade-cancel":
101 return this.cancel(sessionId, command.characterId, now);
102 default:
103 return { events: [] };
104 }
105 }
106
107 onCharacterGone (characterId)
108 {
109 const events = [];
110 const id = characterId | 0;
111 for (const [inviteId, invite] of [...this.invites.entries()])
112 {
113 if (invite.fromCharacterId === id || invite.toCharacterId === id)
114 {
115 this.invites.delete(inviteId);
116 const other = invite.fromCharacterId === id
117 ? invite.toCharacterId
118 : invite.fromCharacterId;
119 events.push({
120 type: "trade-invite-expired",
121 characterId: other,
122 inviteId
123 });
124 }
125 }
126 const session = this.sessions.get(id);
127 if (session)
128 { events.push(...this.#closeSession(session, "Trade cancelled.")); }
129 return events;
130 }
131
132 request (sessionId, characterId, targetEntityId, now = Date.now())
133 {
134 const fromId = characterId | 0;
135 const fromEntityId = this.simulation.characterEntities.get(fromId);
136 if (!fromEntityId)
137 { throw userError("You are not in the world."); }
138 if (this.sessions.has(fromId))
139 { throw userError("You are already trading."); }
140
141 const target = this.#resolvePlayerTarget(targetEntityId | 0);
142 if (!target)
143 { throw userError("That player is not here."); }
144 if (target.characterId === fromId)
145 { throw userError("You cannot trade with yourself."); }
146 if (this.sessions.has(target.characterId))
147 { throw userError("That player is already trading."); }
148
149 const blockKey = `${target.characterId}:${fromId}`;
150 const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0;
151 if (now < blockedUntil)
152 { throw userError("That player declined a recent trade request."); }
153
154 for (const invite of this.invites.values())
155 {
156 if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId)
157 { throw userError("You already sent a trade request."); }
158 }
159
160 const fromPos = this.#positionOf(fromEntityId);
161 const toPos = this.#positionOf(target.entityId);
162 if (!fromPos || !toPos)
163 { throw userError("That player is not here."); }
164
165 const fromRow = this.stateDb.getCharacter(fromId);
166 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone";
167 const inviteId = randomUUID();
168 this.invites.set(inviteId, {
169 inviteId,
170 fromCharacterId: fromId,
171 fromEntityId,
172 fromSessionId: sessionId,
173 toCharacterId: target.characterId,
174 toEntityId: target.entityId,
175 expiresAt: now + INVITE_MS
176 });
177 return {
178 events: [
179 {
180 type: "toast",
181 characterId: fromId,
182 message: `Trade request sent to ${target.name}.`
183 },
184 {
185 type: "trade-invite",
186 characterId: target.characterId,
187 inviteId,
188 fromCharacterId: fromId,
189 fromEntityId,
190 fromName,
191 expiresAt: now + INVITE_MS
192 }
193 ]
194 };
195 }
196
197 respondInvite (sessionId, characterId, inviteId, accept, now = Date.now())
198 {
199 const toId = characterId | 0;
200 const invite = this.invites.get(String(inviteId ?? ""));
201 if (!invite || invite.toCharacterId !== toId)
202 { throw userError("That trade request expired."); }
203 this.invites.delete(invite.inviteId);
204
205 if (!accept)
206 {
207 this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS);
208 const toRow = this.stateDb.getCharacter(toId);
209 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone";
210 return {
211 events: [
212 {
213 type: "toast",
214 characterId: invite.fromCharacterId,
215 message: `${toName} declined your trade request.`
216 },
217 {
218 type: "trade-invite-expired",
219 characterId: toId,
220 inviteId: invite.inviteId
221 }
222 ]
223 };
224 }
225
226 if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId))
227 { throw userError("A trade is already open."); }
228
229 const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId);
230 const toEntityId = this.simulation.characterEntities.get(toId);
231 if (!fromEntityId || !toEntityId)
232 { throw userError("That player is not here."); }
233 if (!this.#entitiesAdjacent(fromEntityId, toEntityId))
234 { throw userError("You need to stand next to each other to trade."); }
235
236 const fromRow = this.stateDb.getCharacter(invite.fromCharacterId);
237 const toRow = this.stateDb.getCharacter(toId);
238 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player";
239 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player";
240
241 const session = {
242 a: {
243 characterId: invite.fromCharacterId,
244 entityId: fromEntityId,
245 sessionId: invite.fromSessionId,
246 name: fromName,
247 offer: [],
248 accepted: false
249 },
250 b: {
251 characterId: toId,
252 entityId: toEntityId,
253 sessionId,
254 name: toName,
255 offer: [],
256 accepted: false
257 }
258 };
259 this.sessions.set(session.a.characterId, session);
260 this.sessions.set(session.b.characterId, session);
261 return { events: this.#openEvents(session) };
262 }
263
264 setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now())
265 {
266 void now;
267 const side = this.#requireSide(characterId);
268 const slotIndex = bagSlotIndex | 0;
269 const qty = Math.max(1, quantity | 0 || 1);
270 const bag = this.#bagOf(side.characterId);
271 const slot = bag?.inventory?.[slotIndex];
272 if (!slot || stackQuantity(slot.quantity) < qty)
273 { throw userError("That item is not available."); }
274 if (!itemDefinition(slot.itemId))
275 { throw userError("That item cannot be traded."); }
276
277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
278 if (existing >= 0)
279 { side.self.offer[existing].quantity = qty; }
280 else
281 { side.self.offer.push({ bagSlotIndex: slotIndex, quantity: qty }); }
282
283 this.#clearAccepts(side.session);
284 return { events: this.#stateEvents(side.session) };
285 }
286
287 removeOffer (sessionId, characterId, bagSlotIndex, now = Date.now())
288 {
289 void now;
290 const side = this.#requireSide(characterId);
291 const slotIndex = bagSlotIndex | 0;
292 side.self.offer = side.self.offer.filter((line) => line.bagSlotIndex !== slotIndex);
293 this.#clearAccepts(side.session);
294 return { events: this.#stateEvents(side.session) };
295 }
296
297 accept (sessionId, characterId, now = Date.now())
298 {
299 void now;
300 const side = this.#requireSide(characterId);
301 if (side.self.accepted)
302 {
303 side.self.accepted = false;
304 return { events: this.#stateEvents(side.session) };
305 }
306 if (!this.#partnersAdjacent(side.session))
307 { throw userError("You need to stand next to each other to trade."); }
308 this.#assertOffersValid(side.session);
309 side.self.accepted = true;
310 if (side.self.accepted && side.partner.accepted)
311 { return this.#tryComplete(side.session); }
312 return { events: this.#stateEvents(side.session) };
313 }
314
315 cancel (sessionId, characterId, now = Date.now())
316 {
317 void now;
318 const side = this.#requireSide(characterId);
319 return { events: this.#closeSession(side.session, null) };
320 }
321
322 #tryComplete (session)
323 {
324 const bagA = this.#bagOf(session.a.characterId);
325 const bagB = this.#bagOf(session.b.characterId);
326 if (!bagA?.inventory || !bagB?.inventory)
327 { throw userError("Trade failed."); }
328
329 const stacksA = resolveOfferStacks(bagA.inventory, session.a.offer);
330 const stacksB = resolveOfferStacks(bagB.inventory, session.b.offer);
331 if (!stacksA || !stacksB)
332 {
333 this.#clearAccepts(session);
334 return {
335 events: [
336 ...this.#stateEvents(session),
337 {
338 type: "toast",
339 characterId: session.a.characterId,
340 message: "An offered item is no longer available."
341 },
342 {
343 type: "toast",
344 characterId: session.b.characterId,
345 message: "An offered item is no longer available."
346 }
347 ]
348 };
349 }
350
351 const shortA = inventorySlotsShortAfterTrade(bagA.inventory, session.a.offer, stacksB);
352 const shortB = inventorySlotsShortAfterTrade(bagB.inventory, session.b.offer, stacksA);
353 if (shortA > 0 || shortB > 0)
354 {
355 this.#clearAccepts(session);
356 const events = [...this.#stateEvents(session)];
357 if (shortA > 0)
358 {
359 events.push({
360 type: "toast",
361 characterId: session.a.characterId,
362 message: `You need ${shortA} more free inventory slots.`
363 });
364 events.push({
365 type: "toast",
366 characterId: session.b.characterId,
367 message: `${session.a.name} needs ${shortA} more free inventory slots.`
368 });
369 }
370 if (shortB > 0)
371 {
372 events.push({
373 type: "toast",
374 characterId: session.b.characterId,
375 message: `You need ${shortB} more free inventory slots.`
376 });
377 events.push({
378 type: "toast",
379 characterId: session.a.characterId,
380 message: `${session.b.name} needs ${shortB} more free inventory slots.`
381 });
382 }
383 return { events };
384 }
385
386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
388 const takeLines = (inv, lines) =>
389 {
390 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 for (const line of ordered)
392 {
393 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 if (!taken.ok)
395 { throw userError("Trade failed."); }
396 inv = taken.slots;
397 }
398 return inv;
399 };
400 invA = takeLines(invA, session.a.offer);
401 invB = takeLines(invB, session.b.offer);
402
403 for (const stack of stacksB)
404 {
405 const inserted = insertStack(invA, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
406 if (!inserted.ok)
407 { throw userError("Trade failed."); }
408 invA = inserted.slots;
409 }
410 for (const stack of stacksA)
411 {
412 const inserted = insertStack(invB, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
413 if (!inserted.ok)
414 { throw userError("Trade failed."); }
415 invB = inserted.slots;
416 }
417
418 bagA.inventory = invA;
419 bagB.inventory = invB;
420 this.#persistBag(session.a.characterId, bagA);
421 this.#persistBag(session.b.characterId, bagB);
422
423 const events = this.#closeSession(session, null);
424 events.push(
425 {
426 type: "toast",
427 characterId: session.a.characterId,
428 message: "Trade complete."
429 },
430 {
431 type: "toast",
432 characterId: session.b.characterId,
433 message: "Trade complete."
434 }
435 );
436 return { events };
437 }
438
439 #assertOffersValid (session)
440 {
441 const bagA = this.#bagOf(session.a.characterId);
442 const bagB = this.#bagOf(session.b.characterId);
443 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
444 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
445 { throw userError("An offered item is no longer available."); }
446 }
447
448 #clearAccepts (session)
449 {
450 session.a.accepted = false;
451 session.b.accepted = false;
452 }
453
454 #requireSide (characterId)
455 {
456 const id = characterId | 0;
457 const session = this.sessions.get(id);
458 if (!session)
459 { throw userError("You are not trading."); }
460 const self = session.a.characterId === id ? session.a : session.b;
461 const partner = session.a.characterId === id ? session.b : session.a;
462 return { session, self, partner, characterId: id };
463 }
464
465 #openEvents (session)
466 {
467 return [
468 {
469 type: "trade-open",
470 characterId: session.a.characterId,
471 partnerCharacterId: session.b.characterId,
472 partnerEntityId: session.b.entityId,
473 partnerName: session.b.name,
474 ...this.#publicStateFor(session, session.a)
475 },
476 {
477 type: "trade-open",
478 characterId: session.b.characterId,
479 partnerCharacterId: session.a.characterId,
480 partnerEntityId: session.a.entityId,
481 partnerName: session.a.name,
482 ...this.#publicStateFor(session, session.b)
483 }
484 ];
485 }
486
487 #stateEvents (session)
488 {
489 return [
490 {
491 type: "trade-state",
492 characterId: session.a.characterId,
493 ...this.#publicStateFor(session, session.a)
494 },
495 {
496 type: "trade-state",
497 characterId: session.b.characterId,
498 ...this.#publicStateFor(session, session.b)
499 }
500 ];
501 }
502
503 #publicStateFor (session, self)
504 {
505 const partner = session.a === self ? session.b : session.a;
506 const selfBag = this.#bagOf(self.characterId);
507 const partnerBag = this.#bagOf(partner.characterId);
508 return {
509 youAccepted: !!self.accepted,
510 theyAccepted: !!partner.accepted,
511 yourOffer: this.#publicOffer(selfBag?.inventory, self.offer),
512 theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer)
513 };
514 }
515
516 #publicOffer (inventory, offer)
517 {
518 const lines = [];
519 for (const line of offer ?? [])
520 {
521 const slot = inventory?.[line.bagSlotIndex];
522 if (!slot)
523 { continue; }
524 const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));
525 const stack = { itemId: slot.itemId, quantity: qty, instance: slot.instance ?? null };
526 lines.push({
527 bagSlotIndex: line.bagSlotIndex | 0,
528 quantity: qty,
529 itemId: slot.itemId,
530 instance: slot.instance ?? null,
531 displayName: itemDisplayName(stack)
532 });
533 }
534 return lines;
535 }
536
537 #closeSession (session, toastMessage)
538 {
539 this.sessions.delete(session.a.characterId);
540 this.sessions.delete(session.b.characterId);
541 const events = [
542 { type: "trade-closed", characterId: session.a.characterId },
543 { type: "trade-closed", characterId: session.b.characterId }
544 ];
545 if (toastMessage)
546 {
547 events.push(
548 { type: "toast", characterId: session.a.characterId, message: toastMessage },
549 { type: "toast", characterId: session.b.characterId, message: toastMessage }
550 );
551 }
552 return events;
553 }
554
555 #resolvePlayerTarget (entityId)
556 {
557 for (const [characterId, id] of this.simulation.characterEntities.entries())
558 {
559 if ((id | 0) !== (entityId | 0))
560 { continue; }
561 const row = this.stateDb.getCharacter(characterId);
562 const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player";
563 return { characterId: characterId | 0, entityId: id | 0, name };
564 }
565 return null;
566 }
567
568 #positionOf (entityId)
569 {
570 const pos = this.simulation.positionOf(entityId);
571 if (!pos || pos.tileX == null)
572 { return null; }
573 return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 };
574 }
575
576 #entitiesAdjacent (entityIdA, entityIdB)
577 {
578 const a = this.#positionOf(entityIdA);
579 const b = this.#positionOf(entityIdB);
580 if (!a || !b)
581 { return false; }
582 return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY)
583 || (a.tileX === b.tileX && a.tileY === b.tileY);
584 }
585
586 #partnersAdjacent (session)
587 {
588 return this.#entitiesAdjacent(session.a.entityId, session.b.entityId);
589 }
590
591 #bagOf (characterId)
592 {
593 const onlineId = this.simulation.characterEntities.get(characterId | 0);
594 return onlineId
595 ? this.simulation.bagOf(onlineId)
596 : this.stateDb.getBag(characterId);
597 }
598
599 #persistBag (characterId, bag)
600 {
601 this.stateDb.saveBag(characterId, bag);
602 const onlineId = this.simulation.characterEntities.get(characterId | 0);
603 if (onlineId)
604 {
605 this.simulation.applyBag?.(onlineId, bag);
606 this.simulation.pushInventory?.(characterId, bag);
607 }
608 }
609 }
@@ -0,0 +1,609 @@
1import { randomUUID } from "node:crypto";
2import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
4import {
5 cloneStack,
6 insertStack,
7 stackQuantity,
8 takeFromSlot
9} from "../../../shared/items/inventory.js";
10import { attachOrigins } from "../../../shared/items/origin.js";
11import {
12 inventorySlotsShortAfterTrade,
13 resolveOfferStacks
14} from "../../../shared/trade/space.js";
15
16const INVITE_MS = 60_000;
17const REJECT_BLOCK_MS = 60_000;
18
19function userError (message)
20{
21 const error = new Error(message);
22 error.userFacing = true;
23 return error;
24}
25
26export class TradeService
27{
28 /**
29 * @param {{ simulation: object, stateDb: object }} opts
30 */
31 constructor ({ simulation, stateDb })
32 {
33 this.simulation = simulation;
34 this.stateDb = stateDb;
35 /** @type {Map<string, object>} */
36 this.invites = new Map();
37 /** @type {Map<string, number>} rejectorId:fromId → blockedUntil */
38 this.rejectBlocks = new Map();
39 /** @type {Map<number, object>} characterId → session */
40 this.sessions = new Map();
41 }
42
43 step (now = Date.now())
44 {
45 const events = [];
46 for (const [id, invite] of [...this.invites.entries()])
47 {
48 if (now >= invite.expiresAt)
49 {
50 this.invites.delete(id);
51 events.push({
52 type: "trade-invite-expired",
53 characterId: invite.toCharacterId,
54 inviteId: id
55 });
56 }
57 }
58 for (const [key, until] of [...this.rejectBlocks.entries()])
59 {
60 if (now >= until)
61 { this.rejectBlocks.delete(key); }
62 }
63 for (const [characterId, session] of [...this.sessions.entries()])
64 {
65 if (!this.#partnersAdjacent(session))
66 {
67 events.push(...this.#closeSession(session, "You moved too far apart."));
68 void characterId;
69 }
70 }
71 return events;
72 }
73
74 handleCommand (sessionId, command, now = Date.now())
75 {
76 switch (command.type)
77 {
78 case "trade-request":
79 return this.request(sessionId, command.characterId, command.targetEntityId, now);
80 case "trade-respond-invite":
81 return this.respondInvite(
82 sessionId,
83 command.characterId,
84 command.inviteId,
85 !!command.accept,
86 now
87 );
88 case "trade-offer-set":
89 return this.setOffer(
90 sessionId,
91 command.characterId,
92 command.bagSlotIndex,
93 command.quantity,
94 now
95 );
96 case "trade-offer-remove":
97 return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now);
98 case "trade-accept":
99 return this.accept(sessionId, command.characterId, now);
100 case "trade-cancel":
101 return this.cancel(sessionId, command.characterId, now);
102 default:
103 return { events: [] };
104 }
105 }
106
107 onCharacterGone (characterId)
108 {
109 const events = [];
110 const id = characterId | 0;
111 for (const [inviteId, invite] of [...this.invites.entries()])
112 {
113 if (invite.fromCharacterId === id || invite.toCharacterId === id)
114 {
115 this.invites.delete(inviteId);
116 const other = invite.fromCharacterId === id
117 ? invite.toCharacterId
118 : invite.fromCharacterId;
119 events.push({
120 type: "trade-invite-expired",
121 characterId: other,
122 inviteId
123 });
124 }
125 }
126 const session = this.sessions.get(id);
127 if (session)
128 { events.push(...this.#closeSession(session, "Trade cancelled.")); }
129 return events;
130 }
131
132 request (sessionId, characterId, targetEntityId, now = Date.now())
133 {
134 const fromId = characterId | 0;
135 const fromEntityId = this.simulation.characterEntities.get(fromId);
136 if (!fromEntityId)
137 { throw userError("You are not in the world."); }
138 if (this.sessions.has(fromId))
139 { throw userError("You are already trading."); }
140
141 const target = this.#resolvePlayerTarget(targetEntityId | 0);
142 if (!target)
143 { throw userError("That player is not here."); }
144 if (target.characterId === fromId)
145 { throw userError("You cannot trade with yourself."); }
146 if (this.sessions.has(target.characterId))
147 { throw userError("That player is already trading."); }
148
149 const blockKey = `${target.characterId}:${fromId}`;
150 const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0;
151 if (now < blockedUntil)
152 { throw userError("That player declined a recent trade request."); }
153
154 for (const invite of this.invites.values())
155 {
156 if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId)
157 { throw userError("You already sent a trade request."); }
158 }
159
160 const fromPos = this.#positionOf(fromEntityId);
161 const toPos = this.#positionOf(target.entityId);
162 if (!fromPos || !toPos)
163 { throw userError("That player is not here."); }
164
165 const fromRow = this.stateDb.getCharacter(fromId);
166 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone";
167 const inviteId = randomUUID();
168 this.invites.set(inviteId, {
169 inviteId,
170 fromCharacterId: fromId,
171 fromEntityId,
172 fromSessionId: sessionId,
173 toCharacterId: target.characterId,
174 toEntityId: target.entityId,
175 expiresAt: now + INVITE_MS
176 });
177 return {
178 events: [
179 {
180 type: "toast",
181 characterId: fromId,
182 message: `Trade request sent to ${target.name}.`
183 },
184 {
185 type: "trade-invite",
186 characterId: target.characterId,
187 inviteId,
188 fromCharacterId: fromId,
189 fromEntityId,
190 fromName,
191 expiresAt: now + INVITE_MS
192 }
193 ]
194 };
195 }
196
197 respondInvite (sessionId, characterId, inviteId, accept, now = Date.now())
198 {
199 const toId = characterId | 0;
200 const invite = this.invites.get(String(inviteId ?? ""));
201 if (!invite || invite.toCharacterId !== toId)
202 { throw userError("That trade request expired."); }
203 this.invites.delete(invite.inviteId);
204
205 if (!accept)
206 {
207 this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS);
208 const toRow = this.stateDb.getCharacter(toId);
209 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone";
210 return {
211 events: [
212 {
213 type: "toast",
214 characterId: invite.fromCharacterId,
215 message: `${toName} declined your trade request.`
216 },
217 {
218 type: "trade-invite-expired",
219 characterId: toId,
220 inviteId: invite.inviteId
221 }
222 ]
223 };
224 }
225
226 if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId))
227 { throw userError("A trade is already open."); }
228
229 const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId);
230 const toEntityId = this.simulation.characterEntities.get(toId);
231 if (!fromEntityId || !toEntityId)
232 { throw userError("That player is not here."); }
233 if (!this.#entitiesAdjacent(fromEntityId, toEntityId))
234 { throw userError("You need to stand next to each other to trade."); }
235
236 const fromRow = this.stateDb.getCharacter(invite.fromCharacterId);
237 const toRow = this.stateDb.getCharacter(toId);
238 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player";
239 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player";
240
241 const session = {
242 a: {
243 characterId: invite.fromCharacterId,
244 entityId: fromEntityId,
245 sessionId: invite.fromSessionId,
246 name: fromName,
247 offer: [],
248 accepted: false
249 },
250 b: {
251 characterId: toId,
252 entityId: toEntityId,
253 sessionId,
254 name: toName,
255 offer: [],
256 accepted: false
257 }
258 };
259 this.sessions.set(session.a.characterId, session);
260 this.sessions.set(session.b.characterId, session);
261 return { events: this.#openEvents(session) };
262 }
263
264 setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now())
265 {
266 void now;
267 const side = this.#requireSide(characterId);
268 const slotIndex = bagSlotIndex | 0;
269 const qty = Math.max(1, quantity | 0 || 1);
270 const bag = this.#bagOf(side.characterId);
271 const slot = bag?.inventory?.[slotIndex];
272 if (!slot || stackQuantity(slot.quantity) < qty)
273 { throw userError("That item is not available."); }
274 if (!itemDefinition(slot.itemId))
275 { throw userError("That item cannot be traded."); }
276
277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
278 if (existing >= 0)
279 { side.self.offer[existing].quantity = qty; }
280 else
281 { side.self.offer.push({ bagSlotIndex: slotIndex, quantity: qty }); }
282
283 this.#clearAccepts(side.session);
284 return { events: this.#stateEvents(side.session) };
285 }
286
287 removeOffer (sessionId, characterId, bagSlotIndex, now = Date.now())
288 {
289 void now;
290 const side = this.#requireSide(characterId);
291 const slotIndex = bagSlotIndex | 0;
292 side.self.offer = side.self.offer.filter((line) => line.bagSlotIndex !== slotIndex);
293 this.#clearAccepts(side.session);
294 return { events: this.#stateEvents(side.session) };
295 }
296
297 accept (sessionId, characterId, now = Date.now())
298 {
299 void now;
300 const side = this.#requireSide(characterId);
301 if (side.self.accepted)
302 {
303 side.self.accepted = false;
304 return { events: this.#stateEvents(side.session) };
305 }
306 if (!this.#partnersAdjacent(side.session))
307 { throw userError("You need to stand next to each other to trade."); }
308 this.#assertOffersValid(side.session);
309 side.self.accepted = true;
310 if (side.self.accepted && side.partner.accepted)
311 { return this.#tryComplete(side.session); }
312 return { events: this.#stateEvents(side.session) };
313 }
314
315 cancel (sessionId, characterId, now = Date.now())
316 {
317 void now;
318 const side = this.#requireSide(characterId);
319 return { events: this.#closeSession(side.session, null) };
320 }
321
322 #tryComplete (session)
323 {
324 const bagA = this.#bagOf(session.a.characterId);
325 const bagB = this.#bagOf(session.b.characterId);
326 if (!bagA?.inventory || !bagB?.inventory)
327 { throw userError("Trade failed."); }
328
329 const stacksA = resolveOfferStacks(bagA.inventory, session.a.offer);
330 const stacksB = resolveOfferStacks(bagB.inventory, session.b.offer);
331 if (!stacksA || !stacksB)
332 {
333 this.#clearAccepts(session);
334 return {
335 events: [
336 ...this.#stateEvents(session),
337 {
338 type: "toast",
339 characterId: session.a.characterId,
340 message: "An offered item is no longer available."
341 },
342 {
343 type: "toast",
344 characterId: session.b.characterId,
345 message: "An offered item is no longer available."
346 }
347 ]
348 };
349 }
350
351 const shortA = inventorySlotsShortAfterTrade(bagA.inventory, session.a.offer, stacksB);
352 const shortB = inventorySlotsShortAfterTrade(bagB.inventory, session.b.offer, stacksA);
353 if (shortA > 0 || shortB > 0)
354 {
355 this.#clearAccepts(session);
356 const events = [...this.#stateEvents(session)];
357 if (shortA > 0)
358 {
359 events.push({
360 type: "toast",
361 characterId: session.a.characterId,
362 message: `You need ${shortA} more free inventory slots.`
363 });
364 events.push({
365 type: "toast",
366 characterId: session.b.characterId,
367 message: `${session.a.name} needs ${shortA} more free inventory slots.`
368 });
369 }
370 if (shortB > 0)
371 {
372 events.push({
373 type: "toast",
374 characterId: session.b.characterId,
375 message: `You need ${shortB} more free inventory slots.`
376 });
377 events.push({
378 type: "toast",
379 characterId: session.a.characterId,
380 message: `${session.b.name} needs ${shortB} more free inventory slots.`
381 });
382 }
383 return { events };
384 }
385
386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
388 const takeLines = (inv, lines) =>
389 {
390 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 for (const line of ordered)
392 {
393 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 if (!taken.ok)
395 { throw userError("Trade failed."); }
396 inv = taken.slots;
397 }
398 return inv;
399 };
400 invA = takeLines(invA, session.a.offer);
401 invB = takeLines(invB, session.b.offer);
402
403 for (const stack of stacksB)
404 {
405 const inserted = insertStack(invA, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
406 if (!inserted.ok)
407 { throw userError("Trade failed."); }
408 invA = inserted.slots;
409 }
410 for (const stack of stacksA)
411 {
412 const inserted = insertStack(invB, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
413 if (!inserted.ok)
414 { throw userError("Trade failed."); }
415 invB = inserted.slots;
416 }
417
418 bagA.inventory = invA;
419 bagB.inventory = invB;
420 this.#persistBag(session.a.characterId, bagA);
421 this.#persistBag(session.b.characterId, bagB);
422
423 const events = this.#closeSession(session, null);
424 events.push(
425 {
426 type: "toast",
427 characterId: session.a.characterId,
428 message: "Trade complete."
429 },
430 {
431 type: "toast",
432 characterId: session.b.characterId,
433 message: "Trade complete."
434 }
435 );
436 return { events };
437 }
438
439 #assertOffersValid (session)
440 {
441 const bagA = this.#bagOf(session.a.characterId);
442 const bagB = this.#bagOf(session.b.characterId);
443 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
444 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
445 { throw userError("An offered item is no longer available."); }
446 }
447
448 #clearAccepts (session)
449 {
450 session.a.accepted = false;
451 session.b.accepted = false;
452 }
453
454 #requireSide (characterId)
455 {
456 const id = characterId | 0;
457 const session = this.sessions.get(id);
458 if (!session)
459 { throw userError("You are not trading."); }
460 const self = session.a.characterId === id ? session.a : session.b;
461 const partner = session.a.characterId === id ? session.b : session.a;
462 return { session, self, partner, characterId: id };
463 }
464
465 #openEvents (session)
466 {
467 return [
468 {
469 type: "trade-open",
470 characterId: session.a.characterId,
471 partnerCharacterId: session.b.characterId,
472 partnerEntityId: session.b.entityId,
473 partnerName: session.b.name,
474 ...this.#publicStateFor(session, session.a)
475 },
476 {
477 type: "trade-open",
478 characterId: session.b.characterId,
479 partnerCharacterId: session.a.characterId,
480 partnerEntityId: session.a.entityId,
481 partnerName: session.a.name,
482 ...this.#publicStateFor(session, session.b)
483 }
484 ];
485 }
486
487 #stateEvents (session)
488 {
489 return [
490 {
491 type: "trade-state",
492 characterId: session.a.characterId,
493 ...this.#publicStateFor(session, session.a)
494 },
495 {
496 type: "trade-state",
497 characterId: session.b.characterId,
498 ...this.#publicStateFor(session, session.b)
499 }
500 ];
501 }
502
503 #publicStateFor (session, self)
504 {
505 const partner = session.a === self ? session.b : session.a;
506 const selfBag = this.#bagOf(self.characterId);
507 const partnerBag = this.#bagOf(partner.characterId);
508 return {
509 youAccepted: !!self.accepted,
510 theyAccepted: !!partner.accepted,
511 yourOffer: this.#publicOffer(selfBag?.inventory, self.offer),
512 theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer)
513 };
514 }
515
516 #publicOffer (inventory, offer)
517 {
518 const lines = [];
519 for (const line of offer ?? [])
520 {
521 const slot = inventory?.[line.bagSlotIndex];
522 if (!slot)
523 { continue; }
524 const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));
525 const stack = { itemId: slot.itemId, quantity: qty, instance: slot.instance ?? null };
526 lines.push({
527 bagSlotIndex: line.bagSlotIndex | 0,
528 quantity: qty,
529 itemId: slot.itemId,
530 instance: slot.instance ?? null,
531 displayName: itemDisplayName(stack)
532 });
533 }
534 return lines;
535 }
536
537 #closeSession (session, toastMessage)
538 {
539 this.sessions.delete(session.a.characterId);
540 this.sessions.delete(session.b.characterId);
541 const events = [
542 { type: "trade-closed", characterId: session.a.characterId },
543 { type: "trade-closed", characterId: session.b.characterId }
544 ];
545 if (toastMessage)
546 {
547 events.push(
548 { type: "toast", characterId: session.a.characterId, message: toastMessage },
549 { type: "toast", characterId: session.b.characterId, message: toastMessage }
550 );
551 }
552 return events;
553 }
554
555 #resolvePlayerTarget (entityId)
556 {
557 for (const [characterId, id] of this.simulation.characterEntities.entries())
558 {
559 if ((id | 0) !== (entityId | 0))
560 { continue; }
561 const row = this.stateDb.getCharacter(characterId);
562 const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player";
563 return { characterId: characterId | 0, entityId: id | 0, name };
564 }
565 return null;
566 }
567
568 #positionOf (entityId)
569 {
570 const pos = this.simulation.positionOf(entityId);
571 if (!pos || pos.tileX == null)
572 { return null; }
573 return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 };
574 }
575
576 #entitiesAdjacent (entityIdA, entityIdB)
577 {
578 const a = this.#positionOf(entityIdA);
579 const b = this.#positionOf(entityIdB);
580 if (!a || !b)
581 { return false; }
582 return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY)
583 || (a.tileX === b.tileX && a.tileY === b.tileY);
584 }
585
586 #partnersAdjacent (session)
587 {
588 return this.#entitiesAdjacent(session.a.entityId, session.b.entityId);
589 }
590
591 #bagOf (characterId)
592 {
593 const onlineId = this.simulation.characterEntities.get(characterId | 0);
594 return onlineId
595 ? this.simulation.bagOf(onlineId)
596 : this.stateDb.getBag(characterId);
597 }
598
599 #persistBag (characterId, bag)
600 {
601 this.stateDb.saveBag(characterId, bag);
602 const onlineId = this.simulation.characterEntities.get(characterId | 0);
603 if (onlineId)
604 {
605 this.simulation.applyBag?.(onlineId, bag);
606 this.simulation.pushInventory?.(characterId, bag);
607 }
608 }
609}
server/tests/trade.test.js added +302 −0
@@ -0,0 +1,302 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { ItemId } from "../../shared/definitions/items.js";
4 import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
5 import {
6 inventorySlotsShortAfterTrade,
7 resolveOfferStacks
8 } from "../../shared/trade/space.js";
9 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11 function apple (qty)
12 {
13 return { itemId: ItemId.apple, quantity: qty };
14 }
15
16 function stick (qty = 1)
17 {
18 return { itemId: ItemId.stick, quantity: qty };
19 }
20
21 function openTrade (harness, fromSession, fromChar, toSession, toEntityId)
22 {
23 harness.simulation.enqueue(fromSession, {
24 type: "trade-request",
25 characterId: fromChar.character_id,
26 targetEntityId: toEntityId
27 });
28 const req = harness.simulation.step();
29 const invite = req.events.find((event) => event.type === "trade-invite");
30 assert.ok(invite, JSON.stringify(req.events));
31 harness.simulation.enqueue(toSession, {
32 type: "trade-respond-invite",
33 characterId: invite.characterId,
34 inviteId: invite.inviteId,
35 accept: true
36 });
37 const open = harness.simulation.step();
38 assert.equal(open.events.filter((event) => event.type === "trade-open").length, 2, JSON.stringify(open.events));
39 return invite;
40 }
41
42 test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>
43 {
44 const slots = emptySlots();
45 for (let i = 0; i < INVENTORY_SLOTS; i++)
46 { slots[i] = stick(1); }
47 assert.equal(
48 inventorySlotsShortAfterTrade(slots, [{ bagSlotIndex: 0, quantity: 1 }], [apple(1)]),
49 0
50 );
51 assert.equal(
52 inventorySlotsShortAfterTrade(slots, [], [apple(1)]),
53 1
54 );
55 });
56
57 test("resolveOfferStacks rejects missing quantities", () =>
58 {
59 const slots = emptySlots();
60 slots[0] = apple(3);
61 assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
62 assert.deepEqual(
63 resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]),
64 [{ itemId: ItemId.apple, quantity: 2, instance: null, origins: undefined }]
65 );
66 });
67
68 test("players can complete a 1-for-1 trade while adjacent", () =>
69 {
70 const harness = makeSimulation({ workerCount: 1 });
71 try
72 {
73 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });
74 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });
75 const bagA = emptySlots();
76 bagA[0] = apple(5);
77 const bagB = emptySlots();
78 bagB[0] = stick(1);
79 harness.stateDb.saveBag(a.character_id, {
80 inventory: bagA,
81 equipment: emptyEquipment(),
82 vault: [],
83 vaultReserved: []
84 });
85 harness.stateDb.saveBag(b.character_id, {
86 inventory: bagB,
87 equipment: emptyEquipment(),
88 vault: [],
89 vaultReserved: []
90 });
91 const aId = harness.simulation.spawnCharacter(1, a);
92 const bId = harness.simulation.spawnCharacter(2, b);
93 harness.simulation.step();
94
95 openTrade(harness, 1, a, 2, bId);
96
97 harness.simulation.enqueue(1, {
98 type: "trade-offer-set",
99 characterId: a.character_id,
100 bagSlotIndex: 0,
101 quantity: 2
102 });
103 harness.simulation.enqueue(2, {
104 type: "trade-offer-set",
105 characterId: b.character_id,
106 bagSlotIndex: 0,
107 quantity: 1
108 });
109 harness.simulation.step();
110
111 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
112 harness.simulation.step();
113 harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
114 const done = harness.simulation.step();
115 assert.ok(done.events.some((event) => event.type === "trade-closed"));
116 assert.ok(done.events.some((event) =>
117 event.type === "toast" && event.message === "Trade complete."));
118
119 const invA = harness.simulation.bagOf(aId).inventory;
120 const invB = harness.simulation.bagOf(bId).inventory;
121 assert.equal(invA.find((slot) => slot?.itemId === ItemId.stick)?.quantity, 1);
122 assert.equal(invA.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 3);
123 assert.equal(invB.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 2);
124 assert.equal(invB.some((slot) => slot?.itemId === ItemId.stick), false);
125 }
126 finally
127 { harness.close(); }
128 });
129
130 test("reject blocks the requester for one minute", () =>
131 {
132 const harness = makeSimulation({ workerCount: 1, now: 5_000 });
133 try
134 {
135 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Ask" });
136 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Block" });
137 harness.simulation.spawnCharacter(1, a);
138 const bId = harness.simulation.spawnCharacter(2, b);
139 harness.simulation.step();
140
141 harness.simulation.enqueue(1, {
142 type: "trade-request",
143 characterId: a.character_id,
144 targetEntityId: bId
145 });
146 const req = harness.simulation.step();
147 const invite = req.events.find((event) => event.type === "trade-invite");
148 assert.ok(invite);
149
150 harness.simulation.enqueue(2, {
151 type: "trade-respond-invite",
152 characterId: b.character_id,
153 inviteId: invite.inviteId,
154 accept: false
155 });
156 harness.simulation.step();
157
158 harness.simulation.enqueue(1, {
159 type: "trade-request",
160 characterId: a.character_id,
161 targetEntityId: bId
162 });
163 const blocked = harness.simulation.step();
164 assert.ok(blocked.events.some((event) =>
165 event.type === "command-error"
166 && /declined a recent trade request/i.test(event.message)));
167
168 harness.setNow(5_000 + 60_000);
169 harness.simulation.enqueue(1, {
170 type: "trade-request",
171 characterId: a.character_id,
172 targetEntityId: bId
173 });
174 const again = harness.simulation.step();
175 assert.ok(again.events.some((event) => event.type === "trade-invite"));
176 }
177 finally
178 { harness.close(); }
179 });
180
181 test("full inventory without give slots fails with slot toast and resets accepts", () =>
182 {
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Full" });
187 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Giver" });
188 const bagA = emptySlots();
189 for (let i = 0; i < INVENTORY_SLOTS; i++)
190 { bagA[i] = stick(1); }
191 const bagB = emptySlots();
192 bagB[0] = apple(1);
193 harness.stateDb.saveBag(a.character_id, {
194 inventory: bagA,
195 equipment: emptyEquipment(),
196 vault: [],
197 vaultReserved: []
198 });
199 harness.stateDb.saveBag(b.character_id, {
200 inventory: bagB,
201 equipment: emptyEquipment(),
202 vault: [],
203 vaultReserved: []
204 });
205 harness.simulation.spawnCharacter(1, a);
206 const bId = harness.simulation.spawnCharacter(2, b);
207 harness.simulation.step();
208
209 openTrade(harness, 2, b, 1, harness.simulation.characterEntities.get(a.character_id));
210
211 harness.simulation.enqueue(2, {
212 type: "trade-offer-set",
213 characterId: b.character_id,
214 bagSlotIndex: 0,
215 quantity: 1
216 });
217 harness.simulation.step();
218 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
219 harness.simulation.step();
220 harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
221 const result = harness.simulation.step();
222 assert.ok(result.events.some((event) =>
223 event.type === "toast"
224 && /need .* more free inventory slots/i.test(event.message)));
225 assert.ok(result.events.some((event) => event.type === "trade-state"));
226 assert.equal(result.events.some((event) => event.type === "trade-closed"), false);
227 const state = result.events.find((event) =>
228 event.type === "trade-state" && event.characterId === a.character_id);
229 assert.equal(state?.youAccepted, false);
230 assert.equal(state?.theyAccepted, false);
231 void bId;
232 }
233 finally
234 { harness.close(); }
235 });
236
237 test("cancel closes the trade for both players", () =>
238 {
239 const harness = makeSimulation({ workerCount: 1 });
240 try
241 {
242 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
244 harness.simulation.spawnCharacter(1, a);
245 const bId = harness.simulation.spawnCharacter(2, b);
246 harness.simulation.step();
247 openTrade(harness, 1, a, 2, bId);
248 harness.simulation.enqueue(1, { type: "trade-cancel", characterId: a.character_id });
249 const result = harness.simulation.step();
250 assert.equal(result.events.filter((event) => event.type === "trade-closed").length, 2);
251 }
252 finally
253 { harness.close(); }
254 });
255
256 test("changing an offer clears accept flags", () =>
257 {
258 const harness = makeSimulation({ workerCount: 1 });
259 try
260 {
261 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
262 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
263 const bagA = emptySlots();
264 bagA[0] = apple(4);
265 harness.stateDb.saveBag(a.character_id, {
266 inventory: bagA,
267 equipment: emptyEquipment(),
268 vault: [],
269 vaultReserved: []
270 });
271 harness.simulation.spawnCharacter(1, a);
272 const bId = harness.simulation.spawnCharacter(2, b);
273 harness.simulation.step();
274 openTrade(harness, 1, a, 2, bId);
275
276 harness.simulation.enqueue(1, {
277 type: "trade-offer-set",
278 characterId: a.character_id,
279 bagSlotIndex: 0,
280 quantity: 1
281 });
282 harness.simulation.step();
283 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
284 let state = harness.simulation.step().events.find((event) =>
285 event.type === "trade-state" && event.characterId === a.character_id);
286 assert.equal(state?.youAccepted, true);
287
288 harness.simulation.enqueue(1, {
289 type: "trade-offer-set",
290 characterId: a.character_id,
291 bagSlotIndex: 0,
292 quantity: 2
293 });
294 state = harness.simulation.step().events.find((event) =>
295 event.type === "trade-state" && event.characterId === a.character_id);
296 assert.equal(state?.youAccepted, false);
297 assert.equal(state?.theyAccepted, false);
298 void bId;
299 }
300 finally
301 { harness.close(); }
302 });
@@ -0,0 +1,302 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemId } from "../../shared/definitions/items.js";
4import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
5import {
6 inventorySlotsShortAfterTrade,
7 resolveOfferStacks
8} from "../../shared/trade/space.js";
9import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11function apple (qty)
12{
13 return { itemId: ItemId.apple, quantity: qty };
14}
15
16function stick (qty = 1)
17{
18 return { itemId: ItemId.stick, quantity: qty };
19}
20
21function openTrade (harness, fromSession, fromChar, toSession, toEntityId)
22{
23 harness.simulation.enqueue(fromSession, {
24 type: "trade-request",
25 characterId: fromChar.character_id,
26 targetEntityId: toEntityId
27 });
28 const req = harness.simulation.step();
29 const invite = req.events.find((event) => event.type === "trade-invite");
30 assert.ok(invite, JSON.stringify(req.events));
31 harness.simulation.enqueue(toSession, {
32 type: "trade-respond-invite",
33 characterId: invite.characterId,
34 inviteId: invite.inviteId,
35 accept: true
36 });
37 const open = harness.simulation.step();
38 assert.equal(open.events.filter((event) => event.type === "trade-open").length, 2, JSON.stringify(open.events));
39 return invite;
40}
41
42test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>
43{
44 const slots = emptySlots();
45 for (let i = 0; i < INVENTORY_SLOTS; i++)
46 { slots[i] = stick(1); }
47 assert.equal(
48 inventorySlotsShortAfterTrade(slots, [{ bagSlotIndex: 0, quantity: 1 }], [apple(1)]),
49 0
50 );
51 assert.equal(
52 inventorySlotsShortAfterTrade(slots, [], [apple(1)]),
53 1
54 );
55});
56
57test("resolveOfferStacks rejects missing quantities", () =>
58{
59 const slots = emptySlots();
60 slots[0] = apple(3);
61 assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
62 assert.deepEqual(
63 resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]),
64 [{ itemId: ItemId.apple, quantity: 2, instance: null, origins: undefined }]
65 );
66});
67
68test("players can complete a 1-for-1 trade while adjacent", () =>
69{
70 const harness = makeSimulation({ workerCount: 1 });
71 try
72 {
73 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });
74 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });
75 const bagA = emptySlots();
76 bagA[0] = apple(5);
77 const bagB = emptySlots();
78 bagB[0] = stick(1);
79 harness.stateDb.saveBag(a.character_id, {
80 inventory: bagA,
81 equipment: emptyEquipment(),
82 vault: [],
83 vaultReserved: []
84 });
85 harness.stateDb.saveBag(b.character_id, {
86 inventory: bagB,
87 equipment: emptyEquipment(),
88 vault: [],
89 vaultReserved: []
90 });
91 const aId = harness.simulation.spawnCharacter(1, a);
92 const bId = harness.simulation.spawnCharacter(2, b);
93 harness.simulation.step();
94
95 openTrade(harness, 1, a, 2, bId);
96
97 harness.simulation.enqueue(1, {
98 type: "trade-offer-set",
99 characterId: a.character_id,
100 bagSlotIndex: 0,
101 quantity: 2
102 });
103 harness.simulation.enqueue(2, {
104 type: "trade-offer-set",
105 characterId: b.character_id,
106 bagSlotIndex: 0,
107 quantity: 1
108 });
109 harness.simulation.step();
110
111 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
112 harness.simulation.step();
113 harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
114 const done = harness.simulation.step();
115 assert.ok(done.events.some((event) => event.type === "trade-closed"));
116 assert.ok(done.events.some((event) =>
117 event.type === "toast" && event.message === "Trade complete."));
118
119 const invA = harness.simulation.bagOf(aId).inventory;
120 const invB = harness.simulation.bagOf(bId).inventory;
121 assert.equal(invA.find((slot) => slot?.itemId === ItemId.stick)?.quantity, 1);
122 assert.equal(invA.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 3);
123 assert.equal(invB.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 2);
124 assert.equal(invB.some((slot) => slot?.itemId === ItemId.stick), false);
125 }
126 finally
127 { harness.close(); }
128});
129
130test("reject blocks the requester for one minute", () =>
131{
132 const harness = makeSimulation({ workerCount: 1, now: 5_000 });
133 try
134 {
135 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Ask" });
136 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Block" });
137 harness.simulation.spawnCharacter(1, a);
138 const bId = harness.simulation.spawnCharacter(2, b);
139 harness.simulation.step();
140
141 harness.simulation.enqueue(1, {
142 type: "trade-request",
143 characterId: a.character_id,
144 targetEntityId: bId
145 });
146 const req = harness.simulation.step();
147 const invite = req.events.find((event) => event.type === "trade-invite");
148 assert.ok(invite);
149
150 harness.simulation.enqueue(2, {
151 type: "trade-respond-invite",
152 characterId: b.character_id,
153 inviteId: invite.inviteId,
154 accept: false
155 });
156 harness.simulation.step();
157
158 harness.simulation.enqueue(1, {
159 type: "trade-request",
160 characterId: a.character_id,
161 targetEntityId: bId
162 });
163 const blocked = harness.simulation.step();
164 assert.ok(blocked.events.some((event) =>
165 event.type === "command-error"
166 && /declined a recent trade request/i.test(event.message)));
167
168 harness.setNow(5_000 + 60_000);
169 harness.simulation.enqueue(1, {
170 type: "trade-request",
171 characterId: a.character_id,
172 targetEntityId: bId
173 });
174 const again = harness.simulation.step();
175 assert.ok(again.events.some((event) => event.type === "trade-invite"));
176 }
177 finally
178 { harness.close(); }
179});
180
181test("full inventory without give slots fails with slot toast and resets accepts", () =>
182{
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Full" });
187 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Giver" });
188 const bagA = emptySlots();
189 for (let i = 0; i < INVENTORY_SLOTS; i++)
190 { bagA[i] = stick(1); }
191 const bagB = emptySlots();
192 bagB[0] = apple(1);
193 harness.stateDb.saveBag(a.character_id, {
194 inventory: bagA,
195 equipment: emptyEquipment(),
196 vault: [],
197 vaultReserved: []
198 });
199 harness.stateDb.saveBag(b.character_id, {
200 inventory: bagB,
201 equipment: emptyEquipment(),
202 vault: [],
203 vaultReserved: []
204 });
205 harness.simulation.spawnCharacter(1, a);
206 const bId = harness.simulation.spawnCharacter(2, b);
207 harness.simulation.step();
208
209 openTrade(harness, 2, b, 1, harness.simulation.characterEntities.get(a.character_id));
210
211 harness.simulation.enqueue(2, {
212 type: "trade-offer-set",
213 characterId: b.character_id,
214 bagSlotIndex: 0,
215 quantity: 1
216 });
217 harness.simulation.step();
218 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
219 harness.simulation.step();
220 harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
221 const result = harness.simulation.step();
222 assert.ok(result.events.some((event) =>
223 event.type === "toast"
224 && /need .* more free inventory slots/i.test(event.message)));
225 assert.ok(result.events.some((event) => event.type === "trade-state"));
226 assert.equal(result.events.some((event) => event.type === "trade-closed"), false);
227 const state = result.events.find((event) =>
228 event.type === "trade-state" && event.characterId === a.character_id);
229 assert.equal(state?.youAccepted, false);
230 assert.equal(state?.theyAccepted, false);
231 void bId;
232 }
233 finally
234 { harness.close(); }
235});
236
237test("cancel closes the trade for both players", () =>
238{
239 const harness = makeSimulation({ workerCount: 1 });
240 try
241 {
242 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
244 harness.simulation.spawnCharacter(1, a);
245 const bId = harness.simulation.spawnCharacter(2, b);
246 harness.simulation.step();
247 openTrade(harness, 1, a, 2, bId);
248 harness.simulation.enqueue(1, { type: "trade-cancel", characterId: a.character_id });
249 const result = harness.simulation.step();
250 assert.equal(result.events.filter((event) => event.type === "trade-closed").length, 2);
251 }
252 finally
253 { harness.close(); }
254});
255
256test("changing an offer clears accept flags", () =>
257{
258 const harness = makeSimulation({ workerCount: 1 });
259 try
260 {
261 const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
262 const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
263 const bagA = emptySlots();
264 bagA[0] = apple(4);
265 harness.stateDb.saveBag(a.character_id, {
266 inventory: bagA,
267 equipment: emptyEquipment(),
268 vault: [],
269 vaultReserved: []
270 });
271 harness.simulation.spawnCharacter(1, a);
272 const bId = harness.simulation.spawnCharacter(2, b);
273 harness.simulation.step();
274 openTrade(harness, 1, a, 2, bId);
275
276 harness.simulation.enqueue(1, {
277 type: "trade-offer-set",
278 characterId: a.character_id,
279 bagSlotIndex: 0,
280 quantity: 1
281 });
282 harness.simulation.step();
283 harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
284 let state = harness.simulation.step().events.find((event) =>
285 event.type === "trade-state" && event.characterId === a.character_id);
286 assert.equal(state?.youAccepted, true);
287
288 harness.simulation.enqueue(1, {
289 type: "trade-offer-set",
290 characterId: a.character_id,
291 bagSlotIndex: 0,
292 quantity: 2
293 });
294 state = harness.simulation.step().events.find((event) =>
295 event.type === "trade-state" && event.characterId === a.character_id);
296 assert.equal(state?.youAccepted, false);
297 assert.equal(state?.theyAccepted, false);
298 void bId;
299 }
300 finally
301 { harness.close(); }
302});
shared/protocol/constants.js +12 −1
@@ -285,6 +285,17 @@ export const MessageType = Object.freeze({
285 285 requestQuests: "REQUEST_QUESTS",
286 286 questsSnapshot: "QUESTS_SNAPSHOT",
287 287 questStepComplete: "QUEST_STEP_COMPLETE",
288 jewelryTeleport: "JEWELRY_TELEPORT"
288 jewelryTeleport: "JEWELRY_TELEPORT",
289 tradeRequest: "TRADE_REQUEST",
290 tradeRespondInvite: "TRADE_RESPOND_INVITE",
291 tradeInvite: "TRADE_INVITE",
292 tradeInviteExpired: "TRADE_INVITE_EXPIRED",
293 tradeOpen: "TRADE_OPEN",
294 tradeState: "TRADE_STATE",
295 tradeOfferSet: "TRADE_OFFER_SET",
296 tradeOfferRemove: "TRADE_OFFER_REMOVE",
297 tradeAccept: "TRADE_ACCEPT",
298 tradeCancel: "TRADE_CANCEL",
299 tradeClosed: "TRADE_CLOSED"
289 300 });
290 301
@@ -285,6 +285,17 @@ export const MessageType = Object.freeze({
285 requestQuests: "REQUEST_QUESTS",
285 requestQuests: "REQUEST_QUESTS",
286 questsSnapshot: "QUESTS_SNAPSHOT",
286 questsSnapshot: "QUESTS_SNAPSHOT",
287 questStepComplete: "QUEST_STEP_COMPLETE",
287 questStepComplete: "QUEST_STEP_COMPLETE",
288 jewelryTeleport: "JEWELRY_TELEPORT"
288 jewelryTeleport: "JEWELRY_TELEPORT",
289 tradeRequest: "TRADE_REQUEST",
290 tradeRespondInvite: "TRADE_RESPOND_INVITE",
291 tradeInvite: "TRADE_INVITE",
292 tradeInviteExpired: "TRADE_INVITE_EXPIRED",
293 tradeOpen: "TRADE_OPEN",
294 tradeState: "TRADE_STATE",
295 tradeOfferSet: "TRADE_OFFER_SET",
296 tradeOfferRemove: "TRADE_OFFER_REMOVE",
297 tradeAccept: "TRADE_ACCEPT",
298 tradeCancel: "TRADE_CANCEL",
299 tradeClosed: "TRADE_CLOSED"
289});
300});
290
301
shared/trade/space.js added +78 −0
@@ -0,0 +1,78 @@
1 import {
2 cloneStack,
3 insertStack,
4 stackQuantity,
5 takeFromSlot,
6 INVENTORY_SLOTS
7 } from "../items/inventory.js";
8 import { itemDefinition } from "../definitions/items.js";
9
10 /**
11 * How many additional empty bag slots a player would need after giving
12 * `giveLines` and receiving `receiveStacks`. 0 = swap fits.
13 *
14 * @param {Array} inventorySlots
15 * @param {Array<{ bagSlotIndex: number, quantity: number }>} giveLines
16 * @param {Array} receiveStacks stacks the partner is offering (item payloads)
17 */
18 export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiveStacks)
19 {
20 let next = (inventorySlots ?? []).map((slot) => cloneStack(slot));
21 while (next.length < INVENTORY_SLOTS)
22 { next.push(null); }
23
24 const gives = [...(giveLines ?? [])]
25 .map((line) => ({
26 bagSlotIndex: line.bagSlotIndex | 0,
27 quantity: Math.max(1, line.quantity | 0 || 1)
28 }))
29 .sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
30
31 for (const line of gives)
32 {
33 const taken = takeFromSlot(next, line.bagSlotIndex, line.quantity);
34 if (!taken.ok)
35 { return INVENTORY_SLOTS; }
36 next = taken.slots;
37 }
38
39 for (const stack of receiveStacks ?? [])
40 {
41 if (!stack)
42 { continue; }
43 const def = itemDefinition(stack.itemId);
44 if (!def)
45 { return INVENTORY_SLOTS; }
46 const inserted = insertStack(next, cloneStack(stack), def);
47 if (!inserted.ok || (inserted.remainder | 0) > 0)
48 {
49 const empty = next.filter((slot) => !slot).length;
50 const needApprox = Math.max(1, Math.ceil(
51 stackQuantity(stack.quantity) / Math.max(1, def.maxStackSize | 0 || 1)
52 ));
53 return Math.max(1, needApprox - empty);
54 }
55 next = inserted.slots;
56 }
57 return 0;
58 }
59
60 /** Snapshot offer lines as transferable stacks from a bag (or null if invalid). */
61 export function resolveOfferStacks (inventorySlots, offerLines)
62 {
63 const stacks = [];
64 for (const line of offerLines ?? [])
65 {
66 const slot = inventorySlots?.[line.bagSlotIndex | 0];
67 const qty = Math.max(1, line.quantity | 0 || 1);
68 if (!slot || stackQuantity(slot.quantity) < qty)
69 { return null; }
70 stacks.push({
71 itemId: slot.itemId,
72 quantity: qty,
73 instance: slot.instance ? structuredClone(slot.instance) : null,
74 origins: slot.origins ? structuredClone(slot.origins) : undefined
75 });
76 }
77 return stacks;
78 }
@@ -0,0 +1,78 @@
1import {
2 cloneStack,
3 insertStack,
4 stackQuantity,
5 takeFromSlot,
6 INVENTORY_SLOTS
7} from "../items/inventory.js";
8import { itemDefinition } from "../definitions/items.js";
9
10/**
11 * How many additional empty bag slots a player would need after giving
12 * `giveLines` and receiving `receiveStacks`. 0 = swap fits.
13 *
14 * @param {Array} inventorySlots
15 * @param {Array<{ bagSlotIndex: number, quantity: number }>} giveLines
16 * @param {Array} receiveStacks stacks the partner is offering (item payloads)
17 */
18export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiveStacks)
19{
20 let next = (inventorySlots ?? []).map((slot) => cloneStack(slot));
21 while (next.length < INVENTORY_SLOTS)
22 { next.push(null); }
23
24 const gives = [...(giveLines ?? [])]
25 .map((line) => ({
26 bagSlotIndex: line.bagSlotIndex | 0,
27 quantity: Math.max(1, line.quantity | 0 || 1)
28 }))
29 .sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
30
31 for (const line of gives)
32 {
33 const taken = takeFromSlot(next, line.bagSlotIndex, line.quantity);
34 if (!taken.ok)
35 { return INVENTORY_SLOTS; }
36 next = taken.slots;
37 }
38
39 for (const stack of receiveStacks ?? [])
40 {
41 if (!stack)
42 { continue; }
43 const def = itemDefinition(stack.itemId);
44 if (!def)
45 { return INVENTORY_SLOTS; }
46 const inserted = insertStack(next, cloneStack(stack), def);
47 if (!inserted.ok || (inserted.remainder | 0) > 0)
48 {
49 const empty = next.filter((slot) => !slot).length;
50 const needApprox = Math.max(1, Math.ceil(
51 stackQuantity(stack.quantity) / Math.max(1, def.maxStackSize | 0 || 1)
52 ));
53 return Math.max(1, needApprox - empty);
54 }
55 next = inserted.slots;
56 }
57 return 0;
58}
59
60/** Snapshot offer lines as transferable stacks from a bag (or null if invalid). */
61export function resolveOfferStacks (inventorySlots, offerLines)
62{
63 const stacks = [];
64 for (const line of offerLines ?? [])
65 {
66 const slot = inventorySlots?.[line.bagSlotIndex | 0];
67 const qty = Math.max(1, line.quantity | 0 || 1);
68 if (!slot || stackQuantity(slot.quantity) < qty)
69 { return null; }
70 stacks.push({
71 itemId: slot.itemId,
72 quantity: qty,
73 instance: slot.instance ? structuredClone(slot.instance) : null,
74 origins: slot.origins ? structuredClone(slot.origins) : undefined
75 });
76 }
77 return stacks;
78}