BlueGit

timfa questward

Files

questward / server / src / trade / service.js

service.js

service.js 16.8 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
4import {
5 cloneStack,
6 insertStack,
7 stackQuantity,
8 takeFromSlot
9} from "../../../shared/items/inventory.js";
10import { attachOrigins } from "../../../shared/items/origin.js";
11import {
12 inventorySlotsShortAfterTrade,
13 resolveOfferStacks
14} from "../../../shared/trade/space.js";
15
16const INVITE_MS = 60_000;
17const REJECT_BLOCK_MS = 60_000;
18
19function userError (message)
20{
21 const error = new Error(message);
22 error.userFacing = true;
23 return error;
24}
25
26export class TradeService
27{
28 /**
29 * @param {{ simulation: object, stateDb: object }} opts
30 */
31 constructor ({ simulation, stateDb })
32 {
33 this.simulation = simulation;
34 this.stateDb = stateDb;
35 /** @type {Map<string, object>} */
36 this.invites = new Map();
37 /** @type {Map<string, number>} rejectorId:fromId → blockedUntil */
38 this.rejectBlocks = new Map();
39 /** @type {Map<number, object>} characterId → session */
40 this.sessions = new Map();
41 }
42
43 step (now = Date.now())
44 {
45 const events = [];
46 for (const [id, invite] of [...this.invites.entries()])
47 {
48 if (now >= invite.expiresAt)
49 {
50 this.invites.delete(id);
51 events.push({
52 type: "trade-invite-expired",
53 characterId: invite.toCharacterId,
54 inviteId: id
55 });
56 }
57 }
58 for (const [key, until] of [...this.rejectBlocks.entries()])
59 {
60 if (now >= until)
61 { this.rejectBlocks.delete(key); }
62 }
63 for (const [characterId, session] of [...this.sessions.entries()])
64 {
65 if (!this.#partnersAdjacent(session))
66 {
67 events.push(...this.#closeSession(session, "You moved too far apart."));
68 void characterId;
69 }
70 }
71 return events;
72 }
73
74 handleCommand (sessionId, command, now = Date.now())
75 {
76 switch (command.type)
77 {
78 case "trade-request":
79 return this.request(sessionId, command.characterId, command.targetEntityId, now);
80 case "trade-respond-invite":
81 return this.respondInvite(
82 sessionId,
83 command.characterId,
84 command.inviteId,
85 !!command.accept,
86 now
87 );
88 case "trade-offer-set":
89 return this.setOffer(
90 sessionId,
91 command.characterId,
92 command.bagSlotIndex,
93 command.quantity,
94 now
95 );
96 case "trade-offer-remove":
97 return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now);
98 case "trade-accept":
99 return this.accept(sessionId, command.characterId, now);
100 case "trade-cancel":
101 return this.cancel(sessionId, command.characterId, now);
102 default:
103 return { events: [] };
104 }
105 }
106
107 onCharacterGone (characterId)
108 {
109 const events = [];
110 const id = characterId | 0;
111 for (const [inviteId, invite] of [...this.invites.entries()])
112 {
113 if (invite.fromCharacterId === id || invite.toCharacterId === id)
114 {
115 this.invites.delete(inviteId);
116 const other = invite.fromCharacterId === id
117 ? invite.toCharacterId
118 : invite.fromCharacterId;
119 events.push({
120 type: "trade-invite-expired",
121 characterId: other,
122 inviteId
123 });
124 }
125 }
126 const session = this.sessions.get(id);
127 if (session)
128 { events.push(...this.#closeSession(session, "Trade cancelled.")); }
129 return events;
130 }
131
132 request (sessionId, characterId, targetEntityId, now = Date.now())
133 {
134 const fromId = characterId | 0;
135 const fromEntityId = this.simulation.characterEntities.get(fromId);
136 if (!fromEntityId)
137 { throw userError("You are not in the world."); }
138 if (this.sessions.has(fromId))
139 { throw userError("You are already trading."); }
140
141 const target = this.#resolvePlayerTarget(targetEntityId | 0);
142 if (!target)
143 { throw userError("That player is not here."); }
144 if (target.characterId === fromId)
145 { throw userError("You cannot trade with yourself."); }
146 if (this.sessions.has(target.characterId))
147 { throw userError("That player is already trading."); }
148
149 const blockKey = `${target.characterId}:${fromId}`;
150 const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0;
151 if (now < blockedUntil)
152 { throw userError("That player declined a recent trade request."); }
153
154 for (const invite of this.invites.values())
155 {
156 if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId)
157 { throw userError("You already sent a trade request."); }
158 }
159
160 const fromPos = this.#positionOf(fromEntityId);
161 const toPos = this.#positionOf(target.entityId);
162 if (!fromPos || !toPos)
163 { throw userError("That player is not here."); }
164
165 const fromRow = this.stateDb.getCharacter(fromId);
166 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone";
167 const inviteId = randomUUID();
168 this.invites.set(inviteId, {
169 inviteId,
170 fromCharacterId: fromId,
171 fromEntityId,
172 fromSessionId: sessionId,
173 toCharacterId: target.characterId,
174 toEntityId: target.entityId,
175 expiresAt: now + INVITE_MS
176 });
177 return {
178 events: [
179 {
180 type: "toast",
181 characterId: fromId,
182 message: `Trade request sent to ${target.name}.`
183 },
184 {
185 type: "trade-invite",
186 characterId: target.characterId,
187 inviteId,
188 fromCharacterId: fromId,
189 fromEntityId,
190 fromName,
191 expiresAt: now + INVITE_MS
192 }
193 ]
194 };
195 }
196
197 respondInvite (sessionId, characterId, inviteId, accept, now = Date.now())
198 {
199 const toId = characterId | 0;
200 const invite = this.invites.get(String(inviteId ?? ""));
201 if (!invite || invite.toCharacterId !== toId)
202 { throw userError("That trade request expired."); }
203 this.invites.delete(invite.inviteId);
204
205 if (!accept)
206 {
207 this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS);
208 const toRow = this.stateDb.getCharacter(toId);
209 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone";
210 return {
211 events: [
212 {
213 type: "toast",
214 characterId: invite.fromCharacterId,
215 message: `${toName} declined your trade request.`
216 },
217 {
218 type: "trade-invite-expired",
219 characterId: toId,
220 inviteId: invite.inviteId
221 }
222 ]
223 };
224 }
225
226 if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId))
227 { throw userError("A trade is already open."); }
228
229 const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId);
230 const toEntityId = this.simulation.characterEntities.get(toId);
231 if (!fromEntityId || !toEntityId)
232 { throw userError("That player is not here."); }
233 if (!this.#entitiesAdjacent(fromEntityId, toEntityId))
234 { throw userError("You need to stand next to each other to trade."); }
235
236 const fromRow = this.stateDb.getCharacter(invite.fromCharacterId);
237 const toRow = this.stateDb.getCharacter(toId);
238 const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player";
239 const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player";
240
241 const session = {
242 a: {
243 characterId: invite.fromCharacterId,
244 entityId: fromEntityId,
245 sessionId: invite.fromSessionId,
246 name: fromName,
247 offer: [],
248 accepted: false
249 },
250 b: {
251 characterId: toId,
252 entityId: toEntityId,
253 sessionId,
254 name: toName,
255 offer: [],
256 accepted: false
257 }
258 };
259 this.sessions.set(session.a.characterId, session);
260 this.sessions.set(session.b.characterId, session);
261 return { events: this.#openEvents(session) };
262 }
263
264 setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now())
265 {
266 void now;
267 const side = this.#requireSide(characterId);
268 const slotIndex = bagSlotIndex | 0;
269 const qty = Math.max(1, quantity | 0 || 1);
270 const bag = this.#bagOf(side.characterId);
271 const slot = bag?.inventory?.[slotIndex];
272 if (!slot || stackQuantity(slot.quantity) < qty)
273 { throw userError("That item is not available."); }
274 if (!itemDefinition(slot.itemId))
275 { throw userError("That item cannot be traded."); }
276
277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
278 if (existing >= 0)
279 { side.self.offer[existing].quantity = qty; }
280 else
281 { side.self.offer.push({ bagSlotIndex: slotIndex, quantity: qty }); }
282
283 this.#clearAccepts(side.session);
284 return { events: this.#stateEvents(side.session) };
285 }
286
287 removeOffer (sessionId, characterId, bagSlotIndex, now = Date.now())
288 {
289 void now;
290 const side = this.#requireSide(characterId);
291 const slotIndex = bagSlotIndex | 0;
292 side.self.offer = side.self.offer.filter((line) => line.bagSlotIndex !== slotIndex);
293 this.#clearAccepts(side.session);
294 return { events: this.#stateEvents(side.session) };
295 }
296
297 accept (sessionId, characterId, now = Date.now())
298 {
299 void now;
300 const side = this.#requireSide(characterId);
301 if (side.self.accepted)
302 {
303 side.self.accepted = false;
304 return { events: this.#stateEvents(side.session) };
305 }
306 if (!this.#partnersAdjacent(side.session))
307 { throw userError("You need to stand next to each other to trade."); }
308 this.#assertOffersValid(side.session);
309 side.self.accepted = true;
310 if (side.self.accepted && side.partner.accepted)
311 { return this.#tryComplete(side.session); }
312 return { events: this.#stateEvents(side.session) };
313 }
314
315 cancel (sessionId, characterId, now = Date.now())
316 {
317 void now;
318 const side = this.#requireSide(characterId);
319 return { events: this.#closeSession(side.session, null) };
320 }
321
322 #tryComplete (session)
323 {
324 const bagA = this.#bagOf(session.a.characterId);
325 const bagB = this.#bagOf(session.b.characterId);
326 if (!bagA?.inventory || !bagB?.inventory)
327 { throw userError("Trade failed."); }
328
329 const stacksA = resolveOfferStacks(bagA.inventory, session.a.offer);
330 const stacksB = resolveOfferStacks(bagB.inventory, session.b.offer);
331 if (!stacksA || !stacksB)
332 {
333 this.#clearAccepts(session);
334 return {
335 events: [
336 ...this.#stateEvents(session),
337 {
338 type: "toast",
339 characterId: session.a.characterId,
340 message: "An offered item is no longer available."
341 },
342 {
343 type: "toast",
344 characterId: session.b.characterId,
345 message: "An offered item is no longer available."
346 }
347 ]
348 };
349 }
350
351 const shortA = inventorySlotsShortAfterTrade(bagA.inventory, session.a.offer, stacksB);
352 const shortB = inventorySlotsShortAfterTrade(bagB.inventory, session.b.offer, stacksA);
353 if (shortA > 0 || shortB > 0)
354 {
355 this.#clearAccepts(session);
356 const events = [...this.#stateEvents(session)];
357 if (shortA > 0)
358 {
359 events.push({
360 type: "toast",
361 characterId: session.a.characterId,
362 message: `You need ${shortA} more free inventory slots.`
363 });
364 events.push({
365 type: "toast",
366 characterId: session.b.characterId,
367 message: `${session.a.name} needs ${shortA} more free inventory slots.`
368 });
369 }
370 if (shortB > 0)
371 {
372 events.push({
373 type: "toast",
374 characterId: session.b.characterId,
375 message: `You need ${shortB} more free inventory slots.`
376 });
377 events.push({
378 type: "toast",
379 characterId: session.a.characterId,
380 message: `${session.b.name} needs ${shortB} more free inventory slots.`
381 });
382 }
383 return { events };
384 }
385
386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
388 const takeLines = (inv, lines) =>
389 {
390 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 for (const line of ordered)
392 {
393 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 if (!taken.ok)
395 { throw userError("Trade failed."); }
396 inv = taken.slots;
397 }
398 return inv;
399 };
400 invA = takeLines(invA, session.a.offer);
401 invB = takeLines(invB, session.b.offer);
402
403 for (const stack of stacksB)
404 {
405 const inserted = insertStack(invA, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
406 if (!inserted.ok)
407 { throw userError("Trade failed."); }
408 invA = inserted.slots;
409 }
410 for (const stack of stacksA)
411 {
412 const inserted = insertStack(invB, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
413 if (!inserted.ok)
414 { throw userError("Trade failed."); }
415 invB = inserted.slots;
416 }
417
418 bagA.inventory = invA;
419 bagB.inventory = invB;
420 this.#persistBag(session.a.characterId, bagA);
421 this.#persistBag(session.b.characterId, bagB);
422
423 const events = this.#closeSession(session, null);
424 events.push(
425 {
426 type: "toast",
427 characterId: session.a.characterId,
428 message: "Trade complete."
429 },
430 {
431 type: "toast",
432 characterId: session.b.characterId,
433 message: "Trade complete."
434 }
435 );
436 return { events };
437 }
438
439 #assertOffersValid (session)
440 {
441 const bagA = this.#bagOf(session.a.characterId);
442 const bagB = this.#bagOf(session.b.characterId);
443 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
444 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
445 { throw userError("An offered item is no longer available."); }
446 }
447
448 #clearAccepts (session)
449 {
450 session.a.accepted = false;
451 session.b.accepted = false;
452 }
453
454 #requireSide (characterId)
455 {
456 const id = characterId | 0;
457 const session = this.sessions.get(id);
458 if (!session)
459 { throw userError("You are not trading."); }
460 const self = session.a.characterId === id ? session.a : session.b;
461 const partner = session.a.characterId === id ? session.b : session.a;
462 return { session, self, partner, characterId: id };
463 }
464
465 #openEvents (session)
466 {
467 return [
468 {
469 type: "trade-open",
470 characterId: session.a.characterId,
471 partnerCharacterId: session.b.characterId,
472 partnerEntityId: session.b.entityId,
473 partnerName: session.b.name,
474 ...this.#publicStateFor(session, session.a)
475 },
476 {
477 type: "trade-open",
478 characterId: session.b.characterId,
479 partnerCharacterId: session.a.characterId,
480 partnerEntityId: session.a.entityId,
481 partnerName: session.a.name,
482 ...this.#publicStateFor(session, session.b)
483 }
484 ];
485 }
486
487 #stateEvents (session)
488 {
489 return [
490 {
491 type: "trade-state",
492 characterId: session.a.characterId,
493 ...this.#publicStateFor(session, session.a)
494 },
495 {
496 type: "trade-state",
497 characterId: session.b.characterId,
498 ...this.#publicStateFor(session, session.b)
499 }
500 ];
501 }
502
503 #publicStateFor (session, self)
504 {
505 const partner = session.a === self ? session.b : session.a;
506 const selfBag = this.#bagOf(self.characterId);
507 const partnerBag = this.#bagOf(partner.characterId);
508 return {
509 youAccepted: !!self.accepted,
510 theyAccepted: !!partner.accepted,
511 yourOffer: this.#publicOffer(selfBag?.inventory, self.offer),
512 theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer)
513 };
514 }
515
516 #publicOffer (inventory, offer)
517 {
518 const lines = [];
519 for (const line of offer ?? [])
520 {
521 const slot = inventory?.[line.bagSlotIndex];
522 if (!slot)
523 { continue; }
524 const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));
525 const stack = { itemId: slot.itemId, quantity: qty, instance: slot.instance ?? null };
526 lines.push({
527 bagSlotIndex: line.bagSlotIndex | 0,
528 quantity: qty,
529 itemId: slot.itemId,
530 instance: slot.instance ?? null,
531 displayName: itemDisplayName(stack)
532 });
533 }
534 return lines;
535 }
536
537 #closeSession (session, toastMessage)
538 {
539 this.sessions.delete(session.a.characterId);
540 this.sessions.delete(session.b.characterId);
541 const events = [
542 { type: "trade-closed", characterId: session.a.characterId },
543 { type: "trade-closed", characterId: session.b.characterId }
544 ];
545 if (toastMessage)
546 {
547 events.push(
548 { type: "toast", characterId: session.a.characterId, message: toastMessage },
549 { type: "toast", characterId: session.b.characterId, message: toastMessage }
550 );
551 }
552 return events;
553 }
554
555 #resolvePlayerTarget (entityId)
556 {
557 for (const [characterId, id] of this.simulation.characterEntities.entries())
558 {
559 if ((id | 0) !== (entityId | 0))
560 { continue; }
561 const row = this.stateDb.getCharacter(characterId);
562 const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player";
563 return { characterId: characterId | 0, entityId: id | 0, name };
564 }
565 return null;
566 }
567
568 #positionOf (entityId)
569 {
570 const pos = this.simulation.positionOf(entityId);
571 if (!pos || pos.tileX == null)
572 { return null; }
573 return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 };
574 }
575
576 #entitiesAdjacent (entityIdA, entityIdB)
577 {
578 const a = this.#positionOf(entityIdA);
579 const b = this.#positionOf(entityIdB);
580 if (!a || !b)
581 { return false; }
582 return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY)
583 || (a.tileX === b.tileX && a.tileY === b.tileY);
584 }
585
586 #partnersAdjacent (session)
587 {
588 return this.#entitiesAdjacent(session.a.entityId, session.b.entityId);
589 }
590
591 #bagOf (characterId)
592 {
593 const onlineId = this.simulation.characterEntities.get(characterId | 0);
594 return onlineId
595 ? this.simulation.bagOf(onlineId)
596 : this.stateDb.getBag(characterId);
597 }
598
599 #persistBag (characterId, bag)
600 {
601 this.stateDb.saveBag(characterId, bag);
602 const onlineId = this.simulation.characterEntities.get(characterId | 0);
603 if (onlineId)
604 {
605 this.simulation.applyBag?.(onlineId, bag);
606 this.simulation.pushInventory?.(characterId, bag);
607 }
608 }
609}