Merge branch 'feature/player-trade'
@@ -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">Quantity243
<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>@@ -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);@@ -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";24
import { initContextMenu } from "./contextMenu.js";24
import { initContextMenu } from "./contextMenu.js";25
import { initDeath } from "./death.js";25
import { initDeath } from "./death.js";26
import { initToasts } from "./toasts.js";26
import { initToasts } from "./toasts.js";27
import { initTrade } from "./trade.js";27
import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";28
import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";28
import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";29
import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";29
import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";30
import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";@@ -80,6 +81,7 @@ let statusEffectsUi;80
let contextMenu;81
let contextMenu;81
let death;82
let death;82
let toasts;83
let toasts;84
let trade;83
let questsUi;85
let questsUi;84
let dialogueUi;86
let dialogueUi;85
let shop;87
let 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
invite1907
};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;@@ -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} status132
*/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
applyRestartStatus156
};157
}151
}@@ -0,0 +1,392 @@
1
import {
2
itemAssetPathForStack,
3
itemDescription,
4
itemDisplayName,
5
itemOriginSummary,
6
formatQuantity
7
} from "/shared/definitions/items.js";
8
import { applyItemIcon } from "../render/potionIcon.js";
9
import { isAdjacentTile } from "/shared/navigation/adjacency.js";
10
11
/**
12
* Player-to-player trade UI + invite toasts.
13
*/
14
export function initTrade ({
15
socket,
16
MessageType,
17
toasts,
18
getLocalEntity,
19
getEntity,
20
approachAdjacentTile,
21
clearPendingActions,
22
setPendingTradeAccept,
23
resolveSpriteUrl,
24
resolveImage,
25
ensureBagOpen,
26
onTradeOpenChanged
27
})
28
{
29
const backdrop = document.getElementById("trade-backdrop");
30
const panel = document.getElementById("trade-panel");
31
const partnerEl = document.getElementById("trade-partner");
32
const giveGrid = document.getElementById("trade-give-grid");
33
const receiveGrid = document.getElementById("trade-receive-grid");
34
const acceptBtn = document.getElementById("trade-accept");
35
const cancelBtn = document.getElementById("trade-cancel");
36
const statusEl = document.getElementById("trade-status");
37
const qtyBackdrop = document.getElementById("trade-qty-backdrop");
38
const qtyPanel = document.getElementById("trade-qty-panel");
39
const qtyName = document.getElementById("trade-qty-name");
40
const qtyInput = document.getElementById("trade-qty-input");
41
const qtyConfirm = document.getElementById("trade-qty-confirm");
42
const qtyClose = document.getElementById("trade-qty-close");
43
44
let open = false;
45
let partnerName = "";
46
let partnerEntityId = null;
47
let youAccepted = false;
48
let theyAccepted = false;
49
/** @type {any[]} */
50
let yourOffer = [];
51
/** @type {any[]} */
52
let theirOffer = [];
53
/** @type {Map<string, { dismiss: () => void }>} */
54
const inviteToasts = new Map();
55
let pendingQty = null;
56
57
function isBlocking ()
58
{
59
return open || !!(qtyPanel && !qtyPanel.hidden);
60
}
61
62
function isOpen ()
63
{
64
return open;
65
}
66
67
function listSoftClaims ()
68
{
69
if (!open)
70
{ return []; }
71
return yourOffer.map((line) => ({
72
itemId: line.itemId,
73
quantity: line.quantity,
74
instance: line.instance ?? null
75
}));
76
}
77
78
function closeQty ()
79
{
80
pendingQty = null;
81
if (qtyPanel)
82
{ qtyPanel.hidden = true; }
83
if (qtyBackdrop)
84
{ qtyBackdrop.hidden = true; }
85
}
86
87
function closeTradeUi ()
88
{
89
open = false;
90
closeQty();
91
if (panel)
92
{ panel.hidden = true; }
93
if (backdrop)
94
{ backdrop.hidden = true; }
95
partnerEntityId = null;
96
partnerName = "";
97
youAccepted = false;
98
theyAccepted = false;
99
yourOffer = [];
100
theirOffer = [];
101
onTradeOpenChanged?.(false);
102
}
103
104
function renderOfferGrid (el, lines, { theirs = false } = {})
105
{
106
if (!el)
107
{ return; }
108
el.replaceChildren();
109
if (!lines.length)
110
{
111
const empty = document.createElement("p");
112
empty.className = "hint";
113
empty.textContent = theirs ? "Nothing yet." : "Click bag items to offer them.";
114
el.append(empty);
115
return;
116
}
117
for (const line of lines)
118
{
119
const btn = document.createElement("button");
120
btn.type = "button";
121
btn.className = "item-slot";
122
const stack = {
123
itemId: line.itemId,
124
quantity: line.quantity,
125
instance: line.instance ?? null,
126
origins: line.origins ?? undefined
127
};
128
const base = `${line.displayName ?? itemDisplayName(stack)}${
129
line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""
130
}`;
131
const origin = itemOriginSummary(stack);
132
const desc = line.description || itemDescription(stack);
133
btn.title = [base, origin, desc].filter(Boolean).join("\n");
134
applyItemIcon(btn, stack, {
135
resolveSpriteUrl,
136
resolveImage,
137
pathForStack: itemAssetPathForStack
138
});
139
if (line.quantity > 1)
140
{
141
const qty = document.createElement("span");
142
qty.className = "qty";
143
qty.textContent = formatQuantity(line.quantity);
144
btn.append(qty);
145
}
146
if (!theirs && !youAccepted)
147
{
148
btn.addEventListener("click", () =>
149
{
150
socket.send({
151
type: MessageType.tradeOfferRemove,
152
bagSlotIndex: line.bagSlotIndex
153
});
154
});
155
}
156
else
157
{ btn.disabled = true; }
158
el.append(btn);
159
}
160
}
161
162
function render ()
163
{
164
if (!open)
165
{ return; }
166
if (partnerEl)
167
{ partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; }
168
renderOfferGrid(giveGrid, yourOffer, { theirs: false });
169
renderOfferGrid(receiveGrid, theirOffer, { theirs: true });
170
if (acceptBtn)
171
{
172
acceptBtn.textContent = youAccepted ? "Accepted" : "Accept";
173
acceptBtn.classList.toggle("active", !!youAccepted);
174
acceptBtn.disabled = false;
175
}
176
if (statusEl)
177
{
178
if (youAccepted && theyAccepted)
179
{ statusEl.textContent = "Confirming…"; }
180
else if (theyAccepted)
181
{ statusEl.textContent = `${partnerName} has accepted.`; }
182
else if (youAccepted)
183
{ statusEl.textContent = "Waiting for them to accept…"; }
184
else
185
{ statusEl.textContent = ""; }
186
}
187
}
188
189
function applyState (message)
190
{
191
youAccepted = !!message.youAccepted;
192
theyAccepted = !!message.theyAccepted;
193
yourOffer = message.yourOffer ?? [];
194
theirOffer = message.theirOffer ?? [];
195
render();
196
onTradeOpenChanged?.(true);
197
}
198
199
function openTrade (message)
200
{
201
open = true;
202
partnerName = message.partnerName ?? "Player";
203
partnerEntityId = message.partnerEntityId | 0;
204
if (panel)
205
{ panel.hidden = false; }
206
if (backdrop)
207
{ backdrop.hidden = false; }
208
ensureBagOpen?.();
209
applyState(message);
210
}
211
212
function requestTrade (targetEntityId)
213
{
214
clearPendingActions?.();
215
socket.send({
216
type: MessageType.tradeRequest,
217
targetEntityId: targetEntityId | 0
218
});
219
}
220
221
function respondAccept (invite)
222
{
223
const local = getLocalEntity?.();
224
const partner = getEntity?.(invite.fromEntityId);
225
if (!local || !partner)
226
{
227
socket.send({
228
type: MessageType.tradeRespondInvite,
229
inviteId: invite.inviteId,
230
accept: true
231
});
232
return;
233
}
234
if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY)
235
|| (local.tileX === partner.tileX && local.tileY === partner.tileY))
236
{
237
socket.send({
238
type: MessageType.tradeRespondInvite,
239
inviteId: invite.inviteId,
240
accept: true
241
});
242
return;
243
}
244
setPendingTradeAccept?.(invite);
245
approachAdjacentTile?.(partner.tileX, partner.tileY);
246
}
247
248
function showInvite (message)
249
{
250
const inviteId = message.inviteId;
251
inviteToasts.get(inviteId)?.dismiss?.();
252
const fromName = message.fromName || "Someone";
253
const handle = toasts?.show?.(
254
`${fromName} wishes to trade with you`,
255
{
256
durationMs: Math.max(1000, (message.expiresAt | 0) - Date.now()) || 60_000,
257
actions: [
258
{
259
label: "Accept",
260
onClick: () =>
261
{
262
inviteToasts.delete(inviteId);
263
respondAccept(message);
264
}
265
},
266
{
267
label: "Reject",
268
onClick: () =>
269
{
270
inviteToasts.delete(inviteId);
271
socket.send({
272
type: MessageType.tradeRespondInvite,
273
inviteId,
274
accept: false
275
});
276
}
277
}
278
]
279
}
280
);
281
if (handle)
282
{ inviteToasts.set(inviteId, handle); }
283
}
284
285
function offerBagSlot (slotIndex, slot)
286
{
287
if (!open || youAccepted || !slot)
288
{ return false; }
289
const maxQty = Math.max(1, slot.quantity | 0 || 1);
290
if (maxQty <= 1)
291
{
292
socket.send({
293
type: MessageType.tradeOfferSet,
294
bagSlotIndex: slotIndex,
295
quantity: 1
296
});
297
return true;
298
}
299
pendingQty = { bagSlotIndex: slotIndex, maxQty, name: itemDisplayName(slot) };
300
if (qtyName)
301
{ qtyName.textContent = pendingQty.name; }
302
if (qtyInput)
303
{
304
qtyInput.min = "1";
305
qtyInput.max = String(maxQty);
306
qtyInput.value = String(maxQty);
307
}
308
if (qtyPanel)
309
{ qtyPanel.hidden = false; }
310
if (qtyBackdrop)
311
{ qtyBackdrop.hidden = false; }
312
qtyInput?.focus();
313
qtyInput?.select();
314
return true;
315
}
316
317
acceptBtn?.addEventListener("click", () =>
318
{
319
socket.send({ type: MessageType.tradeAccept });
320
});
321
cancelBtn?.addEventListener("click", () =>
322
{
323
socket.send({ type: MessageType.tradeCancel });
324
});
325
backdrop?.addEventListener("click", () =>
326
{
327
socket.send({ type: MessageType.tradeCancel });
328
});
329
qtyClose?.addEventListener("click", () => closeQty());
330
qtyBackdrop?.addEventListener("click", () => closeQty());
331
qtyConfirm?.addEventListener("click", () =>
332
{
333
if (!pendingQty)
334
{ return; }
335
const qty = Math.max(1, Math.min(pendingQty.maxQty, qtyInput?.valueAsNumber || 1));
336
socket.send({
337
type: MessageType.tradeOfferSet,
338
bagSlotIndex: pendingQty.bagSlotIndex,
339
quantity: qty
340
});
341
closeQty();
342
});
343
344
return {
345
isBlocking,
346
isOpen,
347
listSoftClaims,
348
requestTrade,
349
offerBagSlot,
350
inventoryLocked: () => (open && youAccepted) || !!(qtyPanel && !qtyPanel.hidden),
351
flushPendingAccept (invite)
352
{
353
socket.send({
354
type: MessageType.tradeRespondInvite,
355
inviteId: invite.inviteId,
356
accept: true
357
});
358
},
359
handleMessage (message)
360
{
361
if (message.type === MessageType.tradeInvite)
362
{
363
showInvite(message);
364
return true;
365
}
366
if (message.type === MessageType.tradeInviteExpired)
367
{
368
inviteToasts.get(message.inviteId)?.dismiss?.();
369
inviteToasts.delete(message.inviteId);
370
return true;
371
}
372
if (message.type === MessageType.tradeOpen)
373
{
374
openTrade(message);
375
return true;
376
}
377
if (message.type === MessageType.tradeState)
378
{
379
if (open)
380
{ applyState(message); }
381
return true;
382
}
383
if (message.type === MessageType.tradeClosed)
384
{
385
closeTradeUi();
386
return true;
387
}
388
return false;
389
},
390
close: closeTradeUi
391
};
392
}
@@ -0,0 +1,392 @@1
import {2
itemAssetPathForStack,3
itemDescription,4
itemDisplayName,5
itemOriginSummary,6
formatQuantity7
} from "/shared/definitions/items.js";8
import { applyItemIcon } from "../render/potionIcon.js";9
import { isAdjacentTile } from "/shared/navigation/adjacency.js";10
11
/**12
* Player-to-player trade UI + invite toasts.13
*/14
export function initTrade ({15
socket,16
MessageType,17
toasts,18
getLocalEntity,19
getEntity,20
approachAdjacentTile,21
clearPendingActions,22
setPendingTradeAccept,23
resolveSpriteUrl,24
resolveImage,25
ensureBagOpen,26
onTradeOpenChanged27
})28
{29
const backdrop = document.getElementById("trade-backdrop");30
const panel = document.getElementById("trade-panel");31
const partnerEl = document.getElementById("trade-partner");32
const giveGrid = document.getElementById("trade-give-grid");33
const receiveGrid = document.getElementById("trade-receive-grid");34
const acceptBtn = document.getElementById("trade-accept");35
const cancelBtn = document.getElementById("trade-cancel");36
const statusEl = document.getElementById("trade-status");37
const qtyBackdrop = document.getElementById("trade-qty-backdrop");38
const qtyPanel = document.getElementById("trade-qty-panel");39
const qtyName = document.getElementById("trade-qty-name");40
const qtyInput = document.getElementById("trade-qty-input");41
const qtyConfirm = document.getElementById("trade-qty-confirm");42
const qtyClose = document.getElementById("trade-qty-close");43
44
let open = false;45
let partnerName = "";46
let partnerEntityId = null;47
let youAccepted = false;48
let theyAccepted = false;49
/** @type {any[]} */50
let yourOffer = [];51
/** @type {any[]} */52
let theirOffer = [];53
/** @type {Map<string, { dismiss: () => void }>} */54
const inviteToasts = new Map();55
let pendingQty = null;56
57
function isBlocking ()58
{59
return open || !!(qtyPanel && !qtyPanel.hidden);60
}61
62
function isOpen ()63
{64
return open;65
}66
67
function listSoftClaims ()68
{69
if (!open)70
{ return []; }71
return yourOffer.map((line) => ({72
itemId: line.itemId,73
quantity: line.quantity,74
instance: line.instance ?? null75
}));76
}77
78
function closeQty ()79
{80
pendingQty = null;81
if (qtyPanel)82
{ qtyPanel.hidden = true; }83
if (qtyBackdrop)84
{ qtyBackdrop.hidden = true; }85
}86
87
function closeTradeUi ()88
{89
open = false;90
closeQty();91
if (panel)92
{ panel.hidden = true; }93
if (backdrop)94
{ backdrop.hidden = true; }95
partnerEntityId = null;96
partnerName = "";97
youAccepted = false;98
theyAccepted = false;99
yourOffer = [];100
theirOffer = [];101
onTradeOpenChanged?.(false);102
}103
104
function renderOfferGrid (el, lines, { theirs = false } = {})105
{106
if (!el)107
{ return; }108
el.replaceChildren();109
if (!lines.length)110
{111
const empty = document.createElement("p");112
empty.className = "hint";113
empty.textContent = theirs ? "Nothing yet." : "Click bag items to offer them.";114
el.append(empty);115
return;116
}117
for (const line of lines)118
{119
const btn = document.createElement("button");120
btn.type = "button";121
btn.className = "item-slot";122
const stack = {123
itemId: line.itemId,124
quantity: line.quantity,125
instance: line.instance ?? null,126
origins: line.origins ?? undefined127
};128
const base = `${line.displayName ?? itemDisplayName(stack)}${129
line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""130
}`;131
const origin = itemOriginSummary(stack);132
const desc = line.description || itemDescription(stack);133
btn.title = [base, origin, desc].filter(Boolean).join("\n");134
applyItemIcon(btn, stack, {135
resolveSpriteUrl,136
resolveImage,137
pathForStack: itemAssetPathForStack138
});139
if (line.quantity > 1)140
{141
const qty = document.createElement("span");142
qty.className = "qty";143
qty.textContent = formatQuantity(line.quantity);144
btn.append(qty);145
}146
if (!theirs && !youAccepted)147
{148
btn.addEventListener("click", () =>149
{150
socket.send({151
type: MessageType.tradeOfferRemove,152
bagSlotIndex: line.bagSlotIndex153
});154
});155
}156
else157
{ btn.disabled = true; }158
el.append(btn);159
}160
}161
162
function render ()163
{164
if (!open)165
{ return; }166
if (partnerEl)167
{ partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; }168
renderOfferGrid(giveGrid, yourOffer, { theirs: false });169
renderOfferGrid(receiveGrid, theirOffer, { theirs: true });170
if (acceptBtn)171
{172
acceptBtn.textContent = youAccepted ? "Accepted" : "Accept";173
acceptBtn.classList.toggle("active", !!youAccepted);174
acceptBtn.disabled = false;175
}176
if (statusEl)177
{178
if (youAccepted && theyAccepted)179
{ statusEl.textContent = "Confirming…"; }180
else if (theyAccepted)181
{ statusEl.textContent = `${partnerName} has accepted.`; }182
else if (youAccepted)183
{ statusEl.textContent = "Waiting for them to accept…"; }184
else185
{ statusEl.textContent = ""; }186
}187
}188
189
function applyState (message)190
{191
youAccepted = !!message.youAccepted;192
theyAccepted = !!message.theyAccepted;193
yourOffer = message.yourOffer ?? [];194
theirOffer = message.theirOffer ?? [];195
render();196
onTradeOpenChanged?.(true);197
}198
199
function openTrade (message)200
{201
open = true;202
partnerName = message.partnerName ?? "Player";203
partnerEntityId = message.partnerEntityId | 0;204
if (panel)205
{ panel.hidden = false; }206
if (backdrop)207
{ backdrop.hidden = false; }208
ensureBagOpen?.();209
applyState(message);210
}211
212
function requestTrade (targetEntityId)213
{214
clearPendingActions?.();215
socket.send({216
type: MessageType.tradeRequest,217
targetEntityId: targetEntityId | 0218
});219
}220
221
function respondAccept (invite)222
{223
const local = getLocalEntity?.();224
const partner = getEntity?.(invite.fromEntityId);225
if (!local || !partner)226
{227
socket.send({228
type: MessageType.tradeRespondInvite,229
inviteId: invite.inviteId,230
accept: true231
});232
return;233
}234
if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY)235
|| (local.tileX === partner.tileX && local.tileY === partner.tileY))236
{237
socket.send({238
type: MessageType.tradeRespondInvite,239
inviteId: invite.inviteId,240
accept: true241
});242
return;243
}244
setPendingTradeAccept?.(invite);245
approachAdjacentTile?.(partner.tileX, partner.tileY);246
}247
248
function showInvite (message)249
{250
const inviteId = message.inviteId;251
inviteToasts.get(inviteId)?.dismiss?.();252
const fromName = message.fromName || "Someone";253
const handle = toasts?.show?.(254
`${fromName} wishes to trade with you`,255
{256
durationMs: Math.max(1000, (message.expiresAt | 0) - Date.now()) || 60_000,257
actions: [258
{259
label: "Accept",260
onClick: () =>261
{262
inviteToasts.delete(inviteId);263
respondAccept(message);264
}265
},266
{267
label: "Reject",268
onClick: () =>269
{270
inviteToasts.delete(inviteId);271
socket.send({272
type: MessageType.tradeRespondInvite,273
inviteId,274
accept: false275
});276
}277
}278
]279
}280
);281
if (handle)282
{ inviteToasts.set(inviteId, handle); }283
}284
285
function offerBagSlot (slotIndex, slot)286
{287
if (!open || youAccepted || !slot)288
{ return false; }289
const maxQty = Math.max(1, slot.quantity | 0 || 1);290
if (maxQty <= 1)291
{292
socket.send({293
type: MessageType.tradeOfferSet,294
bagSlotIndex: slotIndex,295
quantity: 1296
});297
return true;298
}299
pendingQty = { bagSlotIndex: slotIndex, maxQty, name: itemDisplayName(slot) };300
if (qtyName)301
{ qtyName.textContent = pendingQty.name; }302
if (qtyInput)303
{304
qtyInput.min = "1";305
qtyInput.max = String(maxQty);306
qtyInput.value = String(maxQty);307
}308
if (qtyPanel)309
{ qtyPanel.hidden = false; }310
if (qtyBackdrop)311
{ qtyBackdrop.hidden = false; }312
qtyInput?.focus();313
qtyInput?.select();314
return true;315
}316
317
acceptBtn?.addEventListener("click", () =>318
{319
socket.send({ type: MessageType.tradeAccept });320
});321
cancelBtn?.addEventListener("click", () =>322
{323
socket.send({ type: MessageType.tradeCancel });324
});325
backdrop?.addEventListener("click", () =>326
{327
socket.send({ type: MessageType.tradeCancel });328
});329
qtyClose?.addEventListener("click", () => closeQty());330
qtyBackdrop?.addEventListener("click", () => closeQty());331
qtyConfirm?.addEventListener("click", () =>332
{333
if (!pendingQty)334
{ return; }335
const qty = Math.max(1, Math.min(pendingQty.maxQty, qtyInput?.valueAsNumber || 1));336
socket.send({337
type: MessageType.tradeOfferSet,338
bagSlotIndex: pendingQty.bagSlotIndex,339
quantity: qty340
});341
closeQty();342
});343
344
return {345
isBlocking,346
isOpen,347
listSoftClaims,348
requestTrade,349
offerBagSlot,350
inventoryLocked: () => (open && youAccepted) || !!(qtyPanel && !qtyPanel.hidden),351
flushPendingAccept (invite)352
{353
socket.send({354
type: MessageType.tradeRespondInvite,355
inviteId: invite.inviteId,356
accept: true357
});358
},359
handleMessage (message)360
{361
if (message.type === MessageType.tradeInvite)362
{363
showInvite(message);364
return true;365
}366
if (message.type === MessageType.tradeInviteExpired)367
{368
inviteToasts.get(message.inviteId)?.dismiss?.();369
inviteToasts.delete(message.inviteId);370
return true;371
}372
if (message.type === MessageType.tradeOpen)373
{374
openTrade(message);375
return true;376
}377
if (message.type === MessageType.tradeState)378
{379
if (open)380
{ applyState(message); }381
return true;382
}383
if (message.type === MessageType.tradeClosed)384
{385
closeTradeUi();386
return true;387
}388
return false;389
},390
close: closeTradeUi391
};392
}@@ -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 {@@ -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 | 0830
});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.accept839
});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 || 1848
});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 | 0856
});857
break;858
case MessageType.tradeAccept:859
requirePlaying(session);860
simulation.enqueue(session.id, {861
type: "trade-accept",862
characterId: session.characterId863
});864
break;865
case MessageType.tradeCancel:866
requirePlaying(session);867
simulation.enqueue(session.id, {868
type: "trade-cancel",869
characterId: session.characterId870
});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.expiresAt1696
});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.theirOffer1721
});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.theirOffer1736
});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 != null1749
const session = event.sessionId != null@@ -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";53
import { seasonIdAt } from "../../../shared/world/season.js";53
import { seasonIdAt } from "../../../shared/world/season.js";54
import { CourierService } from "../courier/service.js";54
import { CourierService } from "../courier/service.js";55
import { MarketService } from "../market/service.js";55
import { MarketService } from "../market/service.js";56
import { TradeService } from "../trade/service.js";56
import { BountyService } from "../bounty/service.js";57
import { BountyService } from "../bounty/service.js";57
import { BarberService } from "../barber/service.js";58
import { BarberService } from "../barber/service.js";58
import { findReservedChequeIndex } from "../items/bags.js";59
import { findReservedChequeIndex } from "../items/bags.js";@@ -128,6 +129,10 @@ export class Simulation128
worldDb: this.worldDb,129
worldDb: this.worldDb,129
simulation: this130
simulation: this130
});131
});132
this.trade = new TradeService({133
stateDb: this.stateDb,134
simulation: this135
});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 Simulation380
{ 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 Simulation861
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 Simulation1471
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"@@ -0,0 +1,631 @@
1
import { randomUUID } from "node:crypto";
2
import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3
import { itemDefinition, itemDescription, 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, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
11
import { assertTradeable } from "../../../shared/items/trade.js";
12
import {
13
inventorySlotsShortAfterTrade,
14
resolveOfferStacks
15
} from "../../../shared/trade/space.js";
16
17
const INVITE_MS = 60_000;
18
const REJECT_BLOCK_MS = 60_000;
19
20
function userError (message)
21
{
22
const error = new Error(message);
23
error.userFacing = true;
24
return error;
25
}
26
27
export class TradeService
28
{
29
/**
30
* @param {{ simulation: object, stateDb: object }} opts
31
*/
32
constructor ({ simulation, stateDb })
33
{
34
this.simulation = simulation;
35
this.stateDb = stateDb;
36
/** @type {Map<string, object>} */
37
this.invites = new Map();
38
/** @type {Map<string, number>} rejectorId:fromId → blockedUntil */
39
this.rejectBlocks = new Map();
40
/** @type {Map<number, object>} characterId → session */
41
this.sessions = new Map();
42
}
43
44
step (now = Date.now())
45
{
46
const events = [];
47
for (const [id, invite] of [...this.invites.entries()])
48
{
49
if (now >= invite.expiresAt)
50
{
51
this.invites.delete(id);
52
events.push({
53
type: "trade-invite-expired",
54
characterId: invite.toCharacterId,
55
inviteId: id
56
});
57
}
58
}
59
for (const [key, until] of [...this.rejectBlocks.entries()])
60
{
61
if (now >= until)
62
{ this.rejectBlocks.delete(key); }
63
}
64
for (const [characterId, session] of [...this.sessions.entries()])
65
{
66
if (!this.#partnersAdjacent(session))
67
{
68
events.push(...this.#closeSession(session, "You moved too far apart."));
69
void characterId;
70
}
71
}
72
return events;
73
}
74
75
handleCommand (sessionId, command, now = Date.now())
76
{
77
switch (command.type)
78
{
79
case "trade-request":
80
return this.request(sessionId, command.characterId, command.targetEntityId, now);
81
case "trade-respond-invite":
82
return this.respondInvite(
83
sessionId,
84
command.characterId,
85
command.inviteId,
86
!!command.accept,
87
now
88
);
89
case "trade-offer-set":
90
return this.setOffer(
91
sessionId,
92
command.characterId,
93
command.bagSlotIndex,
94
command.quantity,
95
now
96
);
97
case "trade-offer-remove":
98
return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now);
99
case "trade-accept":
100
return this.accept(sessionId, command.characterId, now);
101
case "trade-cancel":
102
return this.cancel(sessionId, command.characterId, now);
103
default:
104
return { events: [] };
105
}
106
}
107
108
onCharacterGone (characterId)
109
{
110
const events = [];
111
const id = characterId | 0;
112
for (const [inviteId, invite] of [...this.invites.entries()])
113
{
114
if (invite.fromCharacterId === id || invite.toCharacterId === id)
115
{
116
this.invites.delete(inviteId);
117
const other = invite.fromCharacterId === id
118
? invite.toCharacterId
119
: invite.fromCharacterId;
120
events.push({
121
type: "trade-invite-expired",
122
characterId: other,
123
inviteId
124
});
125
}
126
}
127
const session = this.sessions.get(id);
128
if (session)
129
{ events.push(...this.#closeSession(session, "Trade cancelled.")); }
130
return events;
131
}
132
133
request (sessionId, characterId, targetEntityId, now = Date.now())
134
{
135
const fromId = characterId | 0;
136
const fromEntityId = this.simulation.characterEntities.get(fromId);
137
if (!fromEntityId)
138
{ throw userError("You are not in the world."); }
139
if (this.sessions.has(fromId))
140
{ throw userError("You are already trading."); }
141
142
const target = this.#resolvePlayerTarget(targetEntityId | 0);
143
if (!target)
144
{ throw userError("That player is not here."); }
145
if (target.characterId === fromId)
146
{ throw userError("You cannot trade with yourself."); }
147
if (this.sessions.has(target.characterId))
148
{ throw userError("That player is already trading."); }
149
150
const blockKey = `${target.characterId}:${fromId}`;
151
const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0;
152
if (now < blockedUntil)
153
{ throw userError("That player declined a recent trade request."); }
154
155
for (const invite of this.invites.values())
156
{
157
if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId)
158
{ throw userError("You already sent a trade request."); }
159
}
160
161
const fromPos = this.#positionOf(fromEntityId);
162
const toPos = this.#positionOf(target.entityId);
163
if (!fromPos || !toPos)
164
{ throw userError("That player is not here."); }
165
166
const fromRow = this.stateDb.getCharacter(fromId);
167
const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone";
168
const inviteId = randomUUID();
169
this.invites.set(inviteId, {
170
inviteId,
171
fromCharacterId: fromId,
172
fromEntityId,
173
fromSessionId: sessionId,
174
toCharacterId: target.characterId,
175
toEntityId: target.entityId,
176
expiresAt: now + INVITE_MS
177
});
178
return {
179
events: [
180
{
181
type: "toast",
182
characterId: fromId,
183
message: `Trade request sent to ${target.name}.`
184
},
185
{
186
type: "trade-invite",
187
characterId: target.characterId,
188
inviteId,
189
fromCharacterId: fromId,
190
fromEntityId,
191
fromName,
192
expiresAt: now + INVITE_MS
193
}
194
]
195
};
196
}
197
198
respondInvite (sessionId, characterId, inviteId, accept, now = Date.now())
199
{
200
const toId = characterId | 0;
201
const invite = this.invites.get(String(inviteId ?? ""));
202
if (!invite || invite.toCharacterId !== toId)
203
{ throw userError("That trade request expired."); }
204
this.invites.delete(invite.inviteId);
205
206
if (!accept)
207
{
208
this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS);
209
const toRow = this.stateDb.getCharacter(toId);
210
const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone";
211
return {
212
events: [
213
{
214
type: "toast",
215
characterId: invite.fromCharacterId,
216
message: `${toName} declined your trade request.`
217
},
218
{
219
type: "trade-invite-expired",
220
characterId: toId,
221
inviteId: invite.inviteId
222
}
223
]
224
};
225
}
226
227
if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId))
228
{ throw userError("A trade is already open."); }
229
230
const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId);
231
const toEntityId = this.simulation.characterEntities.get(toId);
232
if (!fromEntityId || !toEntityId)
233
{ throw userError("That player is not here."); }
234
if (!this.#entitiesAdjacent(fromEntityId, toEntityId))
235
{ throw userError("You need to stand next to each other to trade."); }
236
237
const fromRow = this.stateDb.getCharacter(invite.fromCharacterId);
238
const toRow = this.stateDb.getCharacter(toId);
239
const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player";
240
const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player";
241
242
const session = {
243
a: {
244
characterId: invite.fromCharacterId,
245
entityId: fromEntityId,
246
sessionId: invite.fromSessionId,
247
name: fromName,
248
offer: [],
249
accepted: false
250
},
251
b: {
252
characterId: toId,
253
entityId: toEntityId,
254
sessionId,
255
name: toName,
256
offer: [],
257
accepted: false
258
}
259
};
260
this.sessions.set(session.a.characterId, session);
261
this.sessions.set(session.b.characterId, session);
262
return { events: this.#openEvents(session) };
263
}
264
265
setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now())
266
{
267
void now;
268
const side = this.#requireSide(characterId);
269
const slotIndex = bagSlotIndex | 0;
270
const qty = Math.max(1, quantity | 0 || 1);
271
const bag = this.#bagOf(side.characterId);
272
const slot = bag?.inventory?.[slotIndex];
273
if (!slot || stackQuantity(slot.quantity) < qty)
274
{ throw userError("That item is not available."); }
275
assertTradeable(slot, side.characterId);
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 takeOffer = (inv, lines) =>
389
{
390
const takenStacks = [];
391
const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
392
for (const line of ordered)
393
{
394
const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
395
if (!taken.ok || !taken.taken)
396
{ throw userError("Trade failed."); }
397
inv = taken.slots;
398
takenStacks.push(attachOrigins(taken.taken));
399
}
400
return { inv, takenStacks };
401
};
402
const fromA = takeOffer(invA, session.a.offer);
403
const fromB = takeOffer(invB, session.b.offer);
404
invA = fromA.inv;
405
invB = fromB.inv;
406
407
for (const stack of fromB.takenStacks)
408
{
409
const inserted = insertStack(invA, cloneStack(stack), itemDefinition(stack.itemId));
410
if (!inserted.ok)
411
{ throw userError("Trade failed."); }
412
invA = inserted.slots;
413
}
414
for (const stack of fromA.takenStacks)
415
{
416
const inserted = insertStack(invB, cloneStack(stack), itemDefinition(stack.itemId));
417
if (!inserted.ok)
418
{ throw userError("Trade failed."); }
419
invB = inserted.slots;
420
}
421
422
bagA.inventory = invA;
423
bagB.inventory = invB;
424
this.#persistBag(session.a.characterId, bagA);
425
this.#persistBag(session.b.characterId, bagB);
426
427
const events = this.#closeSession(session, null);
428
events.push(
429
{
430
type: "toast",
431
characterId: session.a.characterId,
432
message: "Trade complete."
433
},
434
{
435
type: "toast",
436
characterId: session.b.characterId,
437
message: "Trade complete."
438
}
439
);
440
return { events };
441
}
442
443
#assertOffersValid (session)
444
{
445
const bagA = this.#bagOf(session.a.characterId);
446
const bagB = this.#bagOf(session.b.characterId);
447
if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
448
|| !resolveOfferStacks(bagB?.inventory, session.b.offer))
449
{ throw userError("An offered item is no longer available."); }
450
for (const line of session.a.offer)
451
{
452
const slot = bagA.inventory?.[line.bagSlotIndex];
453
assertTradeable(slot, session.a.characterId);
454
}
455
for (const line of session.b.offer)
456
{
457
const slot = bagB.inventory?.[line.bagSlotIndex];
458
assertTradeable(slot, session.b.characterId);
459
}
460
}
461
462
#clearAccepts (session)
463
{
464
session.a.accepted = false;
465
session.b.accepted = false;
466
}
467
468
#requireSide (characterId)
469
{
470
const id = characterId | 0;
471
const session = this.sessions.get(id);
472
if (!session)
473
{ throw userError("You are not trading."); }
474
const self = session.a.characterId === id ? session.a : session.b;
475
const partner = session.a.characterId === id ? session.b : session.a;
476
return { session, self, partner, characterId: id };
477
}
478
479
#openEvents (session)
480
{
481
return [
482
{
483
type: "trade-open",
484
characterId: session.a.characterId,
485
partnerCharacterId: session.b.characterId,
486
partnerEntityId: session.b.entityId,
487
partnerName: session.b.name,
488
...this.#publicStateFor(session, session.a)
489
},
490
{
491
type: "trade-open",
492
characterId: session.b.characterId,
493
partnerCharacterId: session.a.characterId,
494
partnerEntityId: session.a.entityId,
495
partnerName: session.a.name,
496
...this.#publicStateFor(session, session.b)
497
}
498
];
499
}
500
501
#stateEvents (session)
502
{
503
return [
504
{
505
type: "trade-state",
506
characterId: session.a.characterId,
507
...this.#publicStateFor(session, session.a)
508
},
509
{
510
type: "trade-state",
511
characterId: session.b.characterId,
512
...this.#publicStateFor(session, session.b)
513
}
514
];
515
}
516
517
#publicStateFor (session, self)
518
{
519
const partner = session.a === self ? session.b : session.a;
520
const selfBag = this.#bagOf(self.characterId);
521
const partnerBag = this.#bagOf(partner.characterId);
522
return {
523
youAccepted: !!self.accepted,
524
theyAccepted: !!partner.accepted,
525
yourOffer: this.#publicOffer(selfBag?.inventory, self.offer),
526
theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer)
527
};
528
}
529
530
#publicOffer (inventory, offer)
531
{
532
const lines = [];
533
for (const line of offer ?? [])
534
{
535
const slot = inventory?.[line.bagSlotIndex];
536
if (!slot)
537
{ continue; }
538
const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));
539
const split = splitOrigins(normalizeOrigins(slot), qty);
540
const stack = attachOrigins({
541
itemId: slot.itemId,
542
quantity: qty,
543
instance: slot.instance ? structuredClone(slot.instance) : null,
544
origins: split.taken
545
});
546
lines.push({
547
bagSlotIndex: line.bagSlotIndex | 0,
548
quantity: qty,
549
itemId: slot.itemId,
550
instance: stack.instance ?? null,
551
origins: stack.origins ?? null,
552
displayName: itemDisplayName(stack),
553
description: itemDescription(stack)
554
});
555
}
556
return lines;
557
}
558
559
#closeSession (session, toastMessage)
560
{
561
this.sessions.delete(session.a.characterId);
562
this.sessions.delete(session.b.characterId);
563
const events = [
564
{ type: "trade-closed", characterId: session.a.characterId },
565
{ type: "trade-closed", characterId: session.b.characterId }
566
];
567
if (toastMessage)
568
{
569
events.push(
570
{ type: "toast", characterId: session.a.characterId, message: toastMessage },
571
{ type: "toast", characterId: session.b.characterId, message: toastMessage }
572
);
573
}
574
return events;
575
}
576
577
#resolvePlayerTarget (entityId)
578
{
579
for (const [characterId, id] of this.simulation.characterEntities.entries())
580
{
581
if ((id | 0) !== (entityId | 0))
582
{ continue; }
583
const row = this.stateDb.getCharacter(characterId);
584
const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player";
585
return { characterId: characterId | 0, entityId: id | 0, name };
586
}
587
return null;
588
}
589
590
#positionOf (entityId)
591
{
592
const pos = this.simulation.positionOf(entityId);
593
if (!pos || pos.tileX == null)
594
{ return null; }
595
return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 };
596
}
597
598
#entitiesAdjacent (entityIdA, entityIdB)
599
{
600
const a = this.#positionOf(entityIdA);
601
const b = this.#positionOf(entityIdB);
602
if (!a || !b)
603
{ return false; }
604
return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY)
605
|| (a.tileX === b.tileX && a.tileY === b.tileY);
606
}
607
608
#partnersAdjacent (session)
609
{
610
return this.#entitiesAdjacent(session.a.entityId, session.b.entityId);
611
}
612
613
#bagOf (characterId)
614
{
615
const onlineId = this.simulation.characterEntities.get(characterId | 0);
616
return onlineId
617
? this.simulation.bagOf(onlineId)
618
: this.stateDb.getBag(characterId);
619
}
620
621
#persistBag (characterId, bag)
622
{
623
this.stateDb.saveBag(characterId, bag);
624
const onlineId = this.simulation.characterEntities.get(characterId | 0);
625
if (onlineId)
626
{
627
this.simulation.applyBag?.(onlineId, bag);
628
this.simulation.pushInventory?.(characterId, bag);
629
}
630
}
631
}
@@ -0,0 +1,631 @@1
import { randomUUID } from "node:crypto";2
import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";3
import { itemDefinition, itemDescription, itemDisplayName } from "../../../shared/definitions/items.js";4
import {5
cloneStack,6
insertStack,7
stackQuantity,8
takeFromSlot9
} from "../../../shared/items/inventory.js";10
import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";11
import { assertTradeable } from "../../../shared/items/trade.js";12
import {13
inventorySlotsShortAfterTrade,14
resolveOfferStacks15
} from "../../../shared/trade/space.js";16
17
const INVITE_MS = 60_000;18
const REJECT_BLOCK_MS = 60_000;19
20
function userError (message)21
{22
const error = new Error(message);23
error.userFacing = true;24
return error;25
}26
27
export class TradeService28
{29
/**30
* @param {{ simulation: object, stateDb: object }} opts31
*/32
constructor ({ simulation, stateDb })33
{34
this.simulation = simulation;35
this.stateDb = stateDb;36
/** @type {Map<string, object>} */37
this.invites = new Map();38
/** @type {Map<string, number>} rejectorId:fromId → blockedUntil */39
this.rejectBlocks = new Map();40
/** @type {Map<number, object>} characterId → session */41
this.sessions = new Map();42
}43
44
step (now = Date.now())45
{46
const events = [];47
for (const [id, invite] of [...this.invites.entries()])48
{49
if (now >= invite.expiresAt)50
{51
this.invites.delete(id);52
events.push({53
type: "trade-invite-expired",54
characterId: invite.toCharacterId,55
inviteId: id56
});57
}58
}59
for (const [key, until] of [...this.rejectBlocks.entries()])60
{61
if (now >= until)62
{ this.rejectBlocks.delete(key); }63
}64
for (const [characterId, session] of [...this.sessions.entries()])65
{66
if (!this.#partnersAdjacent(session))67
{68
events.push(...this.#closeSession(session, "You moved too far apart."));69
void characterId;70
}71
}72
return events;73
}74
75
handleCommand (sessionId, command, now = Date.now())76
{77
switch (command.type)78
{79
case "trade-request":80
return this.request(sessionId, command.characterId, command.targetEntityId, now);81
case "trade-respond-invite":82
return this.respondInvite(83
sessionId,84
command.characterId,85
command.inviteId,86
!!command.accept,87
now88
);89
case "trade-offer-set":90
return this.setOffer(91
sessionId,92
command.characterId,93
command.bagSlotIndex,94
command.quantity,95
now96
);97
case "trade-offer-remove":98
return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now);99
case "trade-accept":100
return this.accept(sessionId, command.characterId, now);101
case "trade-cancel":102
return this.cancel(sessionId, command.characterId, now);103
default:104
return { events: [] };105
}106
}107
108
onCharacterGone (characterId)109
{110
const events = [];111
const id = characterId | 0;112
for (const [inviteId, invite] of [...this.invites.entries()])113
{114
if (invite.fromCharacterId === id || invite.toCharacterId === id)115
{116
this.invites.delete(inviteId);117
const other = invite.fromCharacterId === id118
? invite.toCharacterId119
: invite.fromCharacterId;120
events.push({121
type: "trade-invite-expired",122
characterId: other,123
inviteId124
});125
}126
}127
const session = this.sessions.get(id);128
if (session)129
{ events.push(...this.#closeSession(session, "Trade cancelled.")); }130
return events;131
}132
133
request (sessionId, characterId, targetEntityId, now = Date.now())134
{135
const fromId = characterId | 0;136
const fromEntityId = this.simulation.characterEntities.get(fromId);137
if (!fromEntityId)138
{ throw userError("You are not in the world."); }139
if (this.sessions.has(fromId))140
{ throw userError("You are already trading."); }141
142
const target = this.#resolvePlayerTarget(targetEntityId | 0);143
if (!target)144
{ throw userError("That player is not here."); }145
if (target.characterId === fromId)146
{ throw userError("You cannot trade with yourself."); }147
if (this.sessions.has(target.characterId))148
{ throw userError("That player is already trading."); }149
150
const blockKey = `${target.characterId}:${fromId}`;151
const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0;152
if (now < blockedUntil)153
{ throw userError("That player declined a recent trade request."); }154
155
for (const invite of this.invites.values())156
{157
if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId)158
{ throw userError("You already sent a trade request."); }159
}160
161
const fromPos = this.#positionOf(fromEntityId);162
const toPos = this.#positionOf(target.entityId);163
if (!fromPos || !toPos)164
{ throw userError("That player is not here."); }165
166
const fromRow = this.stateDb.getCharacter(fromId);167
const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone";168
const inviteId = randomUUID();169
this.invites.set(inviteId, {170
inviteId,171
fromCharacterId: fromId,172
fromEntityId,173
fromSessionId: sessionId,174
toCharacterId: target.characterId,175
toEntityId: target.entityId,176
expiresAt: now + INVITE_MS177
});178
return {179
events: [180
{181
type: "toast",182
characterId: fromId,183
message: `Trade request sent to ${target.name}.`184
},185
{186
type: "trade-invite",187
characterId: target.characterId,188
inviteId,189
fromCharacterId: fromId,190
fromEntityId,191
fromName,192
expiresAt: now + INVITE_MS193
}194
]195
};196
}197
198
respondInvite (sessionId, characterId, inviteId, accept, now = Date.now())199
{200
const toId = characterId | 0;201
const invite = this.invites.get(String(inviteId ?? ""));202
if (!invite || invite.toCharacterId !== toId)203
{ throw userError("That trade request expired."); }204
this.invites.delete(invite.inviteId);205
206
if (!accept)207
{208
this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS);209
const toRow = this.stateDb.getCharacter(toId);210
const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone";211
return {212
events: [213
{214
type: "toast",215
characterId: invite.fromCharacterId,216
message: `${toName} declined your trade request.`217
},218
{219
type: "trade-invite-expired",220
characterId: toId,221
inviteId: invite.inviteId222
}223
]224
};225
}226
227
if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId))228
{ throw userError("A trade is already open."); }229
230
const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId);231
const toEntityId = this.simulation.characterEntities.get(toId);232
if (!fromEntityId || !toEntityId)233
{ throw userError("That player is not here."); }234
if (!this.#entitiesAdjacent(fromEntityId, toEntityId))235
{ throw userError("You need to stand next to each other to trade."); }236
237
const fromRow = this.stateDb.getCharacter(invite.fromCharacterId);238
const toRow = this.stateDb.getCharacter(toId);239
const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player";240
const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player";241
242
const session = {243
a: {244
characterId: invite.fromCharacterId,245
entityId: fromEntityId,246
sessionId: invite.fromSessionId,247
name: fromName,248
offer: [],249
accepted: false250
},251
b: {252
characterId: toId,253
entityId: toEntityId,254
sessionId,255
name: toName,256
offer: [],257
accepted: false258
}259
};260
this.sessions.set(session.a.characterId, session);261
this.sessions.set(session.b.characterId, session);262
return { events: this.#openEvents(session) };263
}264
265
setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now())266
{267
void now;268
const side = this.#requireSide(characterId);269
const slotIndex = bagSlotIndex | 0;270
const qty = Math.max(1, quantity | 0 || 1);271
const bag = this.#bagOf(side.characterId);272
const slot = bag?.inventory?.[slotIndex];273
if (!slot || stackQuantity(slot.quantity) < qty)274
{ throw userError("That item is not available."); }275
assertTradeable(slot, side.characterId);276
277
const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);278
if (existing >= 0)279
{ side.self.offer[existing].quantity = qty; }280
else281
{ 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 takeOffer = (inv, lines) =>389
{390
const takenStacks = [];391
const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);392
for (const line of ordered)393
{394
const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);395
if (!taken.ok || !taken.taken)396
{ throw userError("Trade failed."); }397
inv = taken.slots;398
takenStacks.push(attachOrigins(taken.taken));399
}400
return { inv, takenStacks };401
};402
const fromA = takeOffer(invA, session.a.offer);403
const fromB = takeOffer(invB, session.b.offer);404
invA = fromA.inv;405
invB = fromB.inv;406
407
for (const stack of fromB.takenStacks)408
{409
const inserted = insertStack(invA, cloneStack(stack), itemDefinition(stack.itemId));410
if (!inserted.ok)411
{ throw userError("Trade failed."); }412
invA = inserted.slots;413
}414
for (const stack of fromA.takenStacks)415
{416
const inserted = insertStack(invB, cloneStack(stack), itemDefinition(stack.itemId));417
if (!inserted.ok)418
{ throw userError("Trade failed."); }419
invB = inserted.slots;420
}421
422
bagA.inventory = invA;423
bagB.inventory = invB;424
this.#persistBag(session.a.characterId, bagA);425
this.#persistBag(session.b.characterId, bagB);426
427
const events = this.#closeSession(session, null);428
events.push(429
{430
type: "toast",431
characterId: session.a.characterId,432
message: "Trade complete."433
},434
{435
type: "toast",436
characterId: session.b.characterId,437
message: "Trade complete."438
}439
);440
return { events };441
}442
443
#assertOffersValid (session)444
{445
const bagA = this.#bagOf(session.a.characterId);446
const bagB = this.#bagOf(session.b.characterId);447
if (!resolveOfferStacks(bagA?.inventory, session.a.offer)448
|| !resolveOfferStacks(bagB?.inventory, session.b.offer))449
{ throw userError("An offered item is no longer available."); }450
for (const line of session.a.offer)451
{452
const slot = bagA.inventory?.[line.bagSlotIndex];453
assertTradeable(slot, session.a.characterId);454
}455
for (const line of session.b.offer)456
{457
const slot = bagB.inventory?.[line.bagSlotIndex];458
assertTradeable(slot, session.b.characterId);459
}460
}461
462
#clearAccepts (session)463
{464
session.a.accepted = false;465
session.b.accepted = false;466
}467
468
#requireSide (characterId)469
{470
const id = characterId | 0;471
const session = this.sessions.get(id);472
if (!session)473
{ throw userError("You are not trading."); }474
const self = session.a.characterId === id ? session.a : session.b;475
const partner = session.a.characterId === id ? session.b : session.a;476
return { session, self, partner, characterId: id };477
}478
479
#openEvents (session)480
{481
return [482
{483
type: "trade-open",484
characterId: session.a.characterId,485
partnerCharacterId: session.b.characterId,486
partnerEntityId: session.b.entityId,487
partnerName: session.b.name,488
...this.#publicStateFor(session, session.a)489
},490
{491
type: "trade-open",492
characterId: session.b.characterId,493
partnerCharacterId: session.a.characterId,494
partnerEntityId: session.a.entityId,495
partnerName: session.a.name,496
...this.#publicStateFor(session, session.b)497
}498
];499
}500
501
#stateEvents (session)502
{503
return [504
{505
type: "trade-state",506
characterId: session.a.characterId,507
...this.#publicStateFor(session, session.a)508
},509
{510
type: "trade-state",511
characterId: session.b.characterId,512
...this.#publicStateFor(session, session.b)513
}514
];515
}516
517
#publicStateFor (session, self)518
{519
const partner = session.a === self ? session.b : session.a;520
const selfBag = this.#bagOf(self.characterId);521
const partnerBag = this.#bagOf(partner.characterId);522
return {523
youAccepted: !!self.accepted,524
theyAccepted: !!partner.accepted,525
yourOffer: this.#publicOffer(selfBag?.inventory, self.offer),526
theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer)527
};528
}529
530
#publicOffer (inventory, offer)531
{532
const lines = [];533
for (const line of offer ?? [])534
{535
const slot = inventory?.[line.bagSlotIndex];536
if (!slot)537
{ continue; }538
const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));539
const split = splitOrigins(normalizeOrigins(slot), qty);540
const stack = attachOrigins({541
itemId: slot.itemId,542
quantity: qty,543
instance: slot.instance ? structuredClone(slot.instance) : null,544
origins: split.taken545
});546
lines.push({547
bagSlotIndex: line.bagSlotIndex | 0,548
quantity: qty,549
itemId: slot.itemId,550
instance: stack.instance ?? null,551
origins: stack.origins ?? null,552
displayName: itemDisplayName(stack),553
description: itemDescription(stack)554
});555
}556
return lines;557
}558
559
#closeSession (session, toastMessage)560
{561
this.sessions.delete(session.a.characterId);562
this.sessions.delete(session.b.characterId);563
const events = [564
{ type: "trade-closed", characterId: session.a.characterId },565
{ type: "trade-closed", characterId: session.b.characterId }566
];567
if (toastMessage)568
{569
events.push(570
{ type: "toast", characterId: session.a.characterId, message: toastMessage },571
{ type: "toast", characterId: session.b.characterId, message: toastMessage }572
);573
}574
return events;575
}576
577
#resolvePlayerTarget (entityId)578
{579
for (const [characterId, id] of this.simulation.characterEntities.entries())580
{581
if ((id | 0) !== (entityId | 0))582
{ continue; }583
const row = this.stateDb.getCharacter(characterId);584
const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player";585
return { characterId: characterId | 0, entityId: id | 0, name };586
}587
return null;588
}589
590
#positionOf (entityId)591
{592
const pos = this.simulation.positionOf(entityId);593
if (!pos || pos.tileX == null)594
{ return null; }595
return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 };596
}597
598
#entitiesAdjacent (entityIdA, entityIdB)599
{600
const a = this.#positionOf(entityIdA);601
const b = this.#positionOf(entityIdB);602
if (!a || !b)603
{ return false; }604
return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY)605
|| (a.tileX === b.tileX && a.tileY === b.tileY);606
}607
608
#partnersAdjacent (session)609
{610
return this.#entitiesAdjacent(session.a.entityId, session.b.entityId);611
}612
613
#bagOf (characterId)614
{615
const onlineId = this.simulation.characterEntities.get(characterId | 0);616
return onlineId617
? this.simulation.bagOf(onlineId)618
: this.stateDb.getBag(characterId);619
}620
621
#persistBag (characterId, bag)622
{623
this.stateDb.saveBag(characterId, bag);624
const onlineId = this.simulation.characterEntities.get(characterId | 0);625
if (onlineId)626
{627
this.simulation.applyBag?.(onlineId, bag);628
this.simulation.pushInventory?.(characterId, bag);629
}630
}631
}@@ -0,0 +1,451 @@
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 { gatherOrigin, GatherOriginVerb } from "../../shared/items/origin.js";
6
import { canTradeStack } from "../../shared/items/trade.js";
7
import {
8
inventorySlotsShortAfterTrade,
9
resolveOfferStacks
10
} from "../../shared/trade/space.js";
11
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
12
13
function apple (qty)
14
{
15
return { itemId: ItemId.apple, quantity: qty };
16
}
17
18
function stick (qty = 1)
19
{
20
return { itemId: ItemId.stick, quantity: qty };
21
}
22
23
function openTrade (harness, fromSession, fromChar, toSession, toEntityId)
24
{
25
harness.simulation.enqueue(fromSession, {
26
type: "trade-request",
27
characterId: fromChar.character_id,
28
targetEntityId: toEntityId
29
});
30
const req = harness.simulation.step();
31
const invite = req.events.find((event) => event.type === "trade-invite");
32
assert.ok(invite, JSON.stringify(req.events));
33
harness.simulation.enqueue(toSession, {
34
type: "trade-respond-invite",
35
characterId: invite.characterId,
36
inviteId: invite.inviteId,
37
accept: true
38
});
39
const open = harness.simulation.step();
40
assert.equal(open.events.filter((event) => event.type === "trade-open").length, 2, JSON.stringify(open.events));
41
return invite;
42
}
43
44
test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>
45
{
46
const slots = emptySlots();
47
for (let i = 0; i < INVENTORY_SLOTS; i++)
48
{ slots[i] = stick(1); }
49
assert.equal(
50
inventorySlotsShortAfterTrade(slots, [{ bagSlotIndex: 0, quantity: 1 }], [apple(1)]),
51
0
52
);
53
assert.equal(
54
inventorySlotsShortAfterTrade(slots, [], [apple(1)]),
55
1
56
);
57
});
58
59
test("resolveOfferStacks rejects missing quantities and slices origins", () =>
60
{
61
const slots = emptySlots();
62
slots[0] = apple(3);
63
assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
64
const resolved = resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]);
65
assert.equal(resolved?.length, 1);
66
assert.equal(resolved[0].itemId, ItemId.apple);
67
assert.equal(resolved[0].quantity, 2);
68
assert.equal(resolved[0].origins?.reduce((sum, entry) => sum + (entry.quantity | 0), 0), 2);
69
});
70
71
test("players can complete a 1-for-1 trade while adjacent", () =>
72
{
73
const harness = makeSimulation({ workerCount: 1 });
74
try
75
{
76
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });
77
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });
78
const bagA = emptySlots();
79
bagA[0] = apple(5);
80
const bagB = emptySlots();
81
bagB[0] = stick(1);
82
harness.stateDb.saveBag(a.character_id, {
83
inventory: bagA,
84
equipment: emptyEquipment(),
85
vault: [],
86
vaultReserved: []
87
});
88
harness.stateDb.saveBag(b.character_id, {
89
inventory: bagB,
90
equipment: emptyEquipment(),
91
vault: [],
92
vaultReserved: []
93
});
94
const aId = harness.simulation.spawnCharacter(1, a);
95
const bId = harness.simulation.spawnCharacter(2, b);
96
harness.simulation.step();
97
98
openTrade(harness, 1, a, 2, bId);
99
100
harness.simulation.enqueue(1, {
101
type: "trade-offer-set",
102
characterId: a.character_id,
103
bagSlotIndex: 0,
104
quantity: 2
105
});
106
harness.simulation.enqueue(2, {
107
type: "trade-offer-set",
108
characterId: b.character_id,
109
bagSlotIndex: 0,
110
quantity: 1
111
});
112
harness.simulation.step();
113
114
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
115
harness.simulation.step();
116
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
117
const done = harness.simulation.step();
118
assert.ok(done.events.some((event) => event.type === "trade-closed"));
119
assert.ok(done.events.some((event) =>
120
event.type === "toast" && event.message === "Trade complete."));
121
122
const invA = harness.simulation.bagOf(aId).inventory;
123
const invB = harness.simulation.bagOf(bId).inventory;
124
assert.equal(invA.find((slot) => slot?.itemId === ItemId.stick)?.quantity, 1);
125
assert.equal(invA.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 3);
126
assert.equal(invB.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 2);
127
assert.equal(invB.some((slot) => slot?.itemId === ItemId.stick), false);
128
}
129
finally
130
{ harness.close(); }
131
});
132
133
test("reject blocks the requester for one minute", () =>
134
{
135
const harness = makeSimulation({ workerCount: 1, now: 5_000 });
136
try
137
{
138
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Ask" });
139
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Block" });
140
harness.simulation.spawnCharacter(1, a);
141
const bId = harness.simulation.spawnCharacter(2, b);
142
harness.simulation.step();
143
144
harness.simulation.enqueue(1, {
145
type: "trade-request",
146
characterId: a.character_id,
147
targetEntityId: bId
148
});
149
const req = harness.simulation.step();
150
const invite = req.events.find((event) => event.type === "trade-invite");
151
assert.ok(invite);
152
153
harness.simulation.enqueue(2, {
154
type: "trade-respond-invite",
155
characterId: b.character_id,
156
inviteId: invite.inviteId,
157
accept: false
158
});
159
harness.simulation.step();
160
161
harness.simulation.enqueue(1, {
162
type: "trade-request",
163
characterId: a.character_id,
164
targetEntityId: bId
165
});
166
const blocked = harness.simulation.step();
167
assert.ok(blocked.events.some((event) =>
168
event.type === "command-error"
169
&& /declined a recent trade request/i.test(event.message)));
170
171
harness.setNow(5_000 + 60_000);
172
harness.simulation.enqueue(1, {
173
type: "trade-request",
174
characterId: a.character_id,
175
targetEntityId: bId
176
});
177
const again = harness.simulation.step();
178
assert.ok(again.events.some((event) => event.type === "trade-invite"));
179
}
180
finally
181
{ harness.close(); }
182
});
183
184
test("full inventory without give slots fails with slot toast and resets accepts", () =>
185
{
186
const harness = makeSimulation({ workerCount: 1 });
187
try
188
{
189
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Full" });
190
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Giver" });
191
const bagA = emptySlots();
192
for (let i = 0; i < INVENTORY_SLOTS; i++)
193
{ bagA[i] = stick(1); }
194
const bagB = emptySlots();
195
bagB[0] = apple(1);
196
harness.stateDb.saveBag(a.character_id, {
197
inventory: bagA,
198
equipment: emptyEquipment(),
199
vault: [],
200
vaultReserved: []
201
});
202
harness.stateDb.saveBag(b.character_id, {
203
inventory: bagB,
204
equipment: emptyEquipment(),
205
vault: [],
206
vaultReserved: []
207
});
208
harness.simulation.spawnCharacter(1, a);
209
const bId = harness.simulation.spawnCharacter(2, b);
210
harness.simulation.step();
211
212
openTrade(harness, 2, b, 1, harness.simulation.characterEntities.get(a.character_id));
213
214
harness.simulation.enqueue(2, {
215
type: "trade-offer-set",
216
characterId: b.character_id,
217
bagSlotIndex: 0,
218
quantity: 1
219
});
220
harness.simulation.step();
221
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
222
harness.simulation.step();
223
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
224
const result = harness.simulation.step();
225
assert.ok(result.events.some((event) =>
226
event.type === "toast"
227
&& /need .* more free inventory slots/i.test(event.message)));
228
assert.ok(result.events.some((event) => event.type === "trade-state"));
229
assert.equal(result.events.some((event) => event.type === "trade-closed"), false);
230
const state = result.events.find((event) =>
231
event.type === "trade-state" && event.characterId === a.character_id);
232
assert.equal(state?.youAccepted, false);
233
assert.equal(state?.theyAccepted, false);
234
void bId;
235
}
236
finally
237
{ harness.close(); }
238
});
239
240
test("cancel closes the trade for both players", () =>
241
{
242
const harness = makeSimulation({ workerCount: 1 });
243
try
244
{
245
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
246
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
247
harness.simulation.spawnCharacter(1, a);
248
const bId = harness.simulation.spawnCharacter(2, b);
249
harness.simulation.step();
250
openTrade(harness, 1, a, 2, bId);
251
harness.simulation.enqueue(1, { type: "trade-cancel", characterId: a.character_id });
252
const result = harness.simulation.step();
253
assert.equal(result.events.filter((event) => event.type === "trade-closed").length, 2);
254
}
255
finally
256
{ harness.close(); }
257
});
258
259
test("changing an offer clears accept flags", () =>
260
{
261
const harness = makeSimulation({ workerCount: 1 });
262
try
263
{
264
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
265
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
266
const bagA = emptySlots();
267
bagA[0] = apple(4);
268
harness.stateDb.saveBag(a.character_id, {
269
inventory: bagA,
270
equipment: emptyEquipment(),
271
vault: [],
272
vaultReserved: []
273
});
274
harness.simulation.spawnCharacter(1, a);
275
const bId = harness.simulation.spawnCharacter(2, b);
276
harness.simulation.step();
277
openTrade(harness, 1, a, 2, bId);
278
279
harness.simulation.enqueue(1, {
280
type: "trade-offer-set",
281
characterId: a.character_id,
282
bagSlotIndex: 0,
283
quantity: 1
284
});
285
harness.simulation.step();
286
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
287
let state = harness.simulation.step().events.find((event) =>
288
event.type === "trade-state" && event.characterId === a.character_id);
289
assert.equal(state?.youAccepted, true);
290
291
harness.simulation.enqueue(1, {
292
type: "trade-offer-set",
293
characterId: a.character_id,
294
bagSlotIndex: 0,
295
quantity: 2
296
});
297
state = harness.simulation.step().events.find((event) =>
298
event.type === "trade-state" && event.characterId === a.character_id);
299
assert.equal(state?.youAccepted, false);
300
assert.equal(state?.theyAccepted, false);
301
void bId;
302
}
303
finally
304
{ harness.close(); }
305
});
306
307
test("received letters cannot be traded; authored letters can", () =>
308
{
309
const harness = makeSimulation({ workerCount: 1 });
310
try
311
{
312
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Author" });
313
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Buddy" });
314
const bagA = emptySlots();
315
bagA[0] = {
316
itemId: ItemId.letter,
317
quantity: 1,
318
instance: {
319
kind: "letter",
320
letterId: "recv-1",
321
authorCharacterId: 999,
322
authorDisplayName: "Other",
323
body: "Hi",
324
opened: true,
325
writtenAt: Date.now()
326
}
327
};
328
bagA[1] = {
329
itemId: ItemId.letter,
330
quantity: 1,
331
instance: {
332
kind: "letter",
333
letterId: "own-1",
334
authorCharacterId: a.character_id,
335
authorDisplayName: "Ann Author",
336
body: "Hello",
337
opened: true,
338
writtenAt: Date.now()
339
}
340
};
341
harness.stateDb.saveBag(a.character_id, {
342
inventory: bagA,
343
equipment: emptyEquipment(),
344
vault: [],
345
vaultReserved: []
346
});
347
harness.simulation.spawnCharacter(1, a);
348
const bId = harness.simulation.spawnCharacter(2, b);
349
harness.simulation.step();
350
openTrade(harness, 1, a, 2, bId);
351
352
harness.simulation.enqueue(1, {
353
type: "trade-offer-set",
354
characterId: a.character_id,
355
bagSlotIndex: 0,
356
quantity: 1
357
});
358
const blocked = harness.simulation.step();
359
assert.ok(blocked.events.some((event) =>
360
event.type === "command-error"
361
&& /only trade letters you wrote/i.test(event.message)));
362
363
harness.simulation.enqueue(1, {
364
type: "trade-offer-set",
365
characterId: a.character_id,
366
bagSlotIndex: 1,
367
quantity: 1
368
});
369
const allowed = harness.simulation.step();
370
assert.equal(allowed.events.some((event) => event.type === "command-error"), false, JSON.stringify(allowed.events));
371
const state = allowed.events.find((event) =>
372
event.type === "trade-state" && event.characterId === a.character_id);
373
assert.equal(state?.yourOffer?.[0]?.itemId, ItemId.letter);
374
assert.equal(state?.yourOffer?.[0]?.instance?.letterId, "own-1");
375
void bId;
376
}
377
finally
378
{ harness.close(); }
379
});
380
381
test("trade preserves item origins on partial stacks", () =>
382
{
383
const harness = makeSimulation({ workerCount: 1 });
384
try
385
{
386
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });
387
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });
388
const mined = gatherOrigin(GatherOriginVerb.mined, "Ann Alpha");
389
const bagA = emptySlots();
390
bagA[0] = {
391
itemId: ItemId.apple,
392
quantity: 5,
393
origins: [{ origin: mined, quantity: 5 }]
394
};
395
harness.stateDb.saveBag(a.character_id, {
396
inventory: bagA,
397
equipment: emptyEquipment(),
398
vault: [],
399
vaultReserved: []
400
});
401
const aId = harness.simulation.spawnCharacter(1, a);
402
const bId = harness.simulation.spawnCharacter(2, b);
403
harness.simulation.step();
404
openTrade(harness, 1, a, 2, bId);
405
406
harness.simulation.enqueue(1, {
407
type: "trade-offer-set",
408
characterId: a.character_id,
409
bagSlotIndex: 0,
410
quantity: 2
411
});
412
const offered = harness.simulation.step();
413
const preview = offered.events.find((event) =>
414
event.type === "trade-state" && event.characterId === b.character_id);
415
assert.equal(preview?.theirOffer?.[0]?.origins?.[0]?.quantity, 2);
416
assert.deepEqual(preview?.theirOffer?.[0]?.origins?.[0]?.origin, mined);
417
418
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });
419
harness.simulation.step();
420
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });
421
harness.simulation.step();
422
423
const got = harness.simulation.bagOf(bId).inventory.find((slot) => slot?.itemId === ItemId.apple);
424
assert.ok(got);
425
const received = (got.origins ?? []).find((entry) =>
426
entry.origin?.kind === mined.kind
427
&& entry.origin?.displayName === mined.displayName);
428
assert.ok(received, JSON.stringify(got.origins));
429
assert.equal(received.quantity, 2);
430
const remain = harness.simulation.bagOf(aId).inventory.find((slot) => slot?.itemId === ItemId.apple);
431
assert.equal(remain?.quantity, 3);
432
assert.deepEqual(remain?.origins, [{ origin: mined, quantity: 3 }]);
433
}
434
finally
435
{ harness.close(); }
436
});
437
438
test("canTradeStack allows normal goods and authored letters only", () =>
439
{
440
assert.equal(canTradeStack({ itemId: ItemId.apple, quantity: 1 }, 1), true);
441
assert.equal(canTradeStack({
442
itemId: ItemId.letter,
443
quantity: 1,
444
instance: { kind: "letter", authorCharacterId: 1, body: "Hi" }
445
}, 1), true);
446
assert.equal(canTradeStack({
447
itemId: ItemId.letter,
448
quantity: 1,
449
instance: { kind: "letter", authorCharacterId: 99, body: "Hi" }
450
}, 1), false);
451
});
@@ -0,0 +1,451 @@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 { gatherOrigin, GatherOriginVerb } from "../../shared/items/origin.js";6
import { canTradeStack } from "../../shared/items/trade.js";7
import {8
inventorySlotsShortAfterTrade,9
resolveOfferStacks10
} from "../../shared/trade/space.js";11
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";12
13
function apple (qty)14
{15
return { itemId: ItemId.apple, quantity: qty };16
}17
18
function stick (qty = 1)19
{20
return { itemId: ItemId.stick, quantity: qty };21
}22
23
function openTrade (harness, fromSession, fromChar, toSession, toEntityId)24
{25
harness.simulation.enqueue(fromSession, {26
type: "trade-request",27
characterId: fromChar.character_id,28
targetEntityId: toEntityId29
});30
const req = harness.simulation.step();31
const invite = req.events.find((event) => event.type === "trade-invite");32
assert.ok(invite, JSON.stringify(req.events));33
harness.simulation.enqueue(toSession, {34
type: "trade-respond-invite",35
characterId: invite.characterId,36
inviteId: invite.inviteId,37
accept: true38
});39
const open = harness.simulation.step();40
assert.equal(open.events.filter((event) => event.type === "trade-open").length, 2, JSON.stringify(open.events));41
return invite;42
}43
44
test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>45
{46
const slots = emptySlots();47
for (let i = 0; i < INVENTORY_SLOTS; i++)48
{ slots[i] = stick(1); }49
assert.equal(50
inventorySlotsShortAfterTrade(slots, [{ bagSlotIndex: 0, quantity: 1 }], [apple(1)]),51
052
);53
assert.equal(54
inventorySlotsShortAfterTrade(slots, [], [apple(1)]),55
156
);57
});58
59
test("resolveOfferStacks rejects missing quantities and slices origins", () =>60
{61
const slots = emptySlots();62
slots[0] = apple(3);63
assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);64
const resolved = resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]);65
assert.equal(resolved?.length, 1);66
assert.equal(resolved[0].itemId, ItemId.apple);67
assert.equal(resolved[0].quantity, 2);68
assert.equal(resolved[0].origins?.reduce((sum, entry) => sum + (entry.quantity | 0), 0), 2);69
});70
71
test("players can complete a 1-for-1 trade while adjacent", () =>72
{73
const harness = makeSimulation({ workerCount: 1 });74
try75
{76
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });77
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });78
const bagA = emptySlots();79
bagA[0] = apple(5);80
const bagB = emptySlots();81
bagB[0] = stick(1);82
harness.stateDb.saveBag(a.character_id, {83
inventory: bagA,84
equipment: emptyEquipment(),85
vault: [],86
vaultReserved: []87
});88
harness.stateDb.saveBag(b.character_id, {89
inventory: bagB,90
equipment: emptyEquipment(),91
vault: [],92
vaultReserved: []93
});94
const aId = harness.simulation.spawnCharacter(1, a);95
const bId = harness.simulation.spawnCharacter(2, b);96
harness.simulation.step();97
98
openTrade(harness, 1, a, 2, bId);99
100
harness.simulation.enqueue(1, {101
type: "trade-offer-set",102
characterId: a.character_id,103
bagSlotIndex: 0,104
quantity: 2105
});106
harness.simulation.enqueue(2, {107
type: "trade-offer-set",108
characterId: b.character_id,109
bagSlotIndex: 0,110
quantity: 1111
});112
harness.simulation.step();113
114
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });115
harness.simulation.step();116
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });117
const done = harness.simulation.step();118
assert.ok(done.events.some((event) => event.type === "trade-closed"));119
assert.ok(done.events.some((event) =>120
event.type === "toast" && event.message === "Trade complete."));121
122
const invA = harness.simulation.bagOf(aId).inventory;123
const invB = harness.simulation.bagOf(bId).inventory;124
assert.equal(invA.find((slot) => slot?.itemId === ItemId.stick)?.quantity, 1);125
assert.equal(invA.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 3);126
assert.equal(invB.find((slot) => slot?.itemId === ItemId.apple)?.quantity, 2);127
assert.equal(invB.some((slot) => slot?.itemId === ItemId.stick), false);128
}129
finally130
{ harness.close(); }131
});132
133
test("reject blocks the requester for one minute", () =>134
{135
const harness = makeSimulation({ workerCount: 1, now: 5_000 });136
try137
{138
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Ask" });139
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Block" });140
harness.simulation.spawnCharacter(1, a);141
const bId = harness.simulation.spawnCharacter(2, b);142
harness.simulation.step();143
144
harness.simulation.enqueue(1, {145
type: "trade-request",146
characterId: a.character_id,147
targetEntityId: bId148
});149
const req = harness.simulation.step();150
const invite = req.events.find((event) => event.type === "trade-invite");151
assert.ok(invite);152
153
harness.simulation.enqueue(2, {154
type: "trade-respond-invite",155
characterId: b.character_id,156
inviteId: invite.inviteId,157
accept: false158
});159
harness.simulation.step();160
161
harness.simulation.enqueue(1, {162
type: "trade-request",163
characterId: a.character_id,164
targetEntityId: bId165
});166
const blocked = harness.simulation.step();167
assert.ok(blocked.events.some((event) =>168
event.type === "command-error"169
&& /declined a recent trade request/i.test(event.message)));170
171
harness.setNow(5_000 + 60_000);172
harness.simulation.enqueue(1, {173
type: "trade-request",174
characterId: a.character_id,175
targetEntityId: bId176
});177
const again = harness.simulation.step();178
assert.ok(again.events.some((event) => event.type === "trade-invite"));179
}180
finally181
{ harness.close(); }182
});183
184
test("full inventory without give slots fails with slot toast and resets accepts", () =>185
{186
const harness = makeSimulation({ workerCount: 1 });187
try188
{189
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Full" });190
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Giver" });191
const bagA = emptySlots();192
for (let i = 0; i < INVENTORY_SLOTS; i++)193
{ bagA[i] = stick(1); }194
const bagB = emptySlots();195
bagB[0] = apple(1);196
harness.stateDb.saveBag(a.character_id, {197
inventory: bagA,198
equipment: emptyEquipment(),199
vault: [],200
vaultReserved: []201
});202
harness.stateDb.saveBag(b.character_id, {203
inventory: bagB,204
equipment: emptyEquipment(),205
vault: [],206
vaultReserved: []207
});208
harness.simulation.spawnCharacter(1, a);209
const bId = harness.simulation.spawnCharacter(2, b);210
harness.simulation.step();211
212
openTrade(harness, 2, b, 1, harness.simulation.characterEntities.get(a.character_id));213
214
harness.simulation.enqueue(2, {215
type: "trade-offer-set",216
characterId: b.character_id,217
bagSlotIndex: 0,218
quantity: 1219
});220
harness.simulation.step();221
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });222
harness.simulation.step();223
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });224
const result = harness.simulation.step();225
assert.ok(result.events.some((event) =>226
event.type === "toast"227
&& /need .* more free inventory slots/i.test(event.message)));228
assert.ok(result.events.some((event) => event.type === "trade-state"));229
assert.equal(result.events.some((event) => event.type === "trade-closed"), false);230
const state = result.events.find((event) =>231
event.type === "trade-state" && event.characterId === a.character_id);232
assert.equal(state?.youAccepted, false);233
assert.equal(state?.theyAccepted, false);234
void bId;235
}236
finally237
{ harness.close(); }238
});239
240
test("cancel closes the trade for both players", () =>241
{242
const harness = makeSimulation({ workerCount: 1 });243
try244
{245
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });246
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });247
harness.simulation.spawnCharacter(1, a);248
const bId = harness.simulation.spawnCharacter(2, b);249
harness.simulation.step();250
openTrade(harness, 1, a, 2, bId);251
harness.simulation.enqueue(1, { type: "trade-cancel", characterId: a.character_id });252
const result = harness.simulation.step();253
assert.equal(result.events.filter((event) => event.type === "trade-closed").length, 2);254
}255
finally256
{ harness.close(); }257
});258
259
test("changing an offer clears accept flags", () =>260
{261
const harness = makeSimulation({ workerCount: 1 });262
try263
{264
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });265
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });266
const bagA = emptySlots();267
bagA[0] = apple(4);268
harness.stateDb.saveBag(a.character_id, {269
inventory: bagA,270
equipment: emptyEquipment(),271
vault: [],272
vaultReserved: []273
});274
harness.simulation.spawnCharacter(1, a);275
const bId = harness.simulation.spawnCharacter(2, b);276
harness.simulation.step();277
openTrade(harness, 1, a, 2, bId);278
279
harness.simulation.enqueue(1, {280
type: "trade-offer-set",281
characterId: a.character_id,282
bagSlotIndex: 0,283
quantity: 1284
});285
harness.simulation.step();286
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });287
let state = harness.simulation.step().events.find((event) =>288
event.type === "trade-state" && event.characterId === a.character_id);289
assert.equal(state?.youAccepted, true);290
291
harness.simulation.enqueue(1, {292
type: "trade-offer-set",293
characterId: a.character_id,294
bagSlotIndex: 0,295
quantity: 2296
});297
state = harness.simulation.step().events.find((event) =>298
event.type === "trade-state" && event.characterId === a.character_id);299
assert.equal(state?.youAccepted, false);300
assert.equal(state?.theyAccepted, false);301
void bId;302
}303
finally304
{ harness.close(); }305
});306
307
test("received letters cannot be traded; authored letters can", () =>308
{309
const harness = makeSimulation({ workerCount: 1 });310
try311
{312
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Author" });313
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Buddy" });314
const bagA = emptySlots();315
bagA[0] = {316
itemId: ItemId.letter,317
quantity: 1,318
instance: {319
kind: "letter",320
letterId: "recv-1",321
authorCharacterId: 999,322
authorDisplayName: "Other",323
body: "Hi",324
opened: true,325
writtenAt: Date.now()326
}327
};328
bagA[1] = {329
itemId: ItemId.letter,330
quantity: 1,331
instance: {332
kind: "letter",333
letterId: "own-1",334
authorCharacterId: a.character_id,335
authorDisplayName: "Ann Author",336
body: "Hello",337
opened: true,338
writtenAt: Date.now()339
}340
};341
harness.stateDb.saveBag(a.character_id, {342
inventory: bagA,343
equipment: emptyEquipment(),344
vault: [],345
vaultReserved: []346
});347
harness.simulation.spawnCharacter(1, a);348
const bId = harness.simulation.spawnCharacter(2, b);349
harness.simulation.step();350
openTrade(harness, 1, a, 2, bId);351
352
harness.simulation.enqueue(1, {353
type: "trade-offer-set",354
characterId: a.character_id,355
bagSlotIndex: 0,356
quantity: 1357
});358
const blocked = harness.simulation.step();359
assert.ok(blocked.events.some((event) =>360
event.type === "command-error"361
&& /only trade letters you wrote/i.test(event.message)));362
363
harness.simulation.enqueue(1, {364
type: "trade-offer-set",365
characterId: a.character_id,366
bagSlotIndex: 1,367
quantity: 1368
});369
const allowed = harness.simulation.step();370
assert.equal(allowed.events.some((event) => event.type === "command-error"), false, JSON.stringify(allowed.events));371
const state = allowed.events.find((event) =>372
event.type === "trade-state" && event.characterId === a.character_id);373
assert.equal(state?.yourOffer?.[0]?.itemId, ItemId.letter);374
assert.equal(state?.yourOffer?.[0]?.instance?.letterId, "own-1");375
void bId;376
}377
finally378
{ harness.close(); }379
});380
381
test("trade preserves item origins on partial stacks", () =>382
{383
const harness = makeSimulation({ workerCount: 1 });384
try385
{386
const a = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ann", lastName: "Alpha" });387
const b = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Bob", lastName: "Beta" });388
const mined = gatherOrigin(GatherOriginVerb.mined, "Ann Alpha");389
const bagA = emptySlots();390
bagA[0] = {391
itemId: ItemId.apple,392
quantity: 5,393
origins: [{ origin: mined, quantity: 5 }]394
};395
harness.stateDb.saveBag(a.character_id, {396
inventory: bagA,397
equipment: emptyEquipment(),398
vault: [],399
vaultReserved: []400
});401
const aId = harness.simulation.spawnCharacter(1, a);402
const bId = harness.simulation.spawnCharacter(2, b);403
harness.simulation.step();404
openTrade(harness, 1, a, 2, bId);405
406
harness.simulation.enqueue(1, {407
type: "trade-offer-set",408
characterId: a.character_id,409
bagSlotIndex: 0,410
quantity: 2411
});412
const offered = harness.simulation.step();413
const preview = offered.events.find((event) =>414
event.type === "trade-state" && event.characterId === b.character_id);415
assert.equal(preview?.theirOffer?.[0]?.origins?.[0]?.quantity, 2);416
assert.deepEqual(preview?.theirOffer?.[0]?.origins?.[0]?.origin, mined);417
418
harness.simulation.enqueue(1, { type: "trade-accept", characterId: a.character_id });419
harness.simulation.step();420
harness.simulation.enqueue(2, { type: "trade-accept", characterId: b.character_id });421
harness.simulation.step();422
423
const got = harness.simulation.bagOf(bId).inventory.find((slot) => slot?.itemId === ItemId.apple);424
assert.ok(got);425
const received = (got.origins ?? []).find((entry) =>426
entry.origin?.kind === mined.kind427
&& entry.origin?.displayName === mined.displayName);428
assert.ok(received, JSON.stringify(got.origins));429
assert.equal(received.quantity, 2);430
const remain = harness.simulation.bagOf(aId).inventory.find((slot) => slot?.itemId === ItemId.apple);431
assert.equal(remain?.quantity, 3);432
assert.deepEqual(remain?.origins, [{ origin: mined, quantity: 3 }]);433
}434
finally435
{ harness.close(); }436
});437
438
test("canTradeStack allows normal goods and authored letters only", () =>439
{440
assert.equal(canTradeStack({ itemId: ItemId.apple, quantity: 1 }, 1), true);441
assert.equal(canTradeStack({442
itemId: ItemId.letter,443
quantity: 1,444
instance: { kind: "letter", authorCharacterId: 1, body: "Hi" }445
}, 1), true);446
assert.equal(canTradeStack({447
itemId: ItemId.letter,448
quantity: 1,449
instance: { kind: "letter", authorCharacterId: 99, body: "Hi" }450
}, 1), false);451
});