BlueGit

timfa questward

Files

questward / server / src / trade / service.js

service.js

service.js 17.5 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3import { itemDefinition, itemDescription, itemDisplayName } from "../../../shared/definitions/items.js";
4import {
5 cloneStack,
6 insertStack,
7 stackQuantity,
8 takeFromSlot
9} from "../../../shared/items/inventory.js";
10import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
11import { assertTradeable } from "../../../shared/items/trade.js";
12import {
13 inventorySlotsShortAfterTrade,
14 resolveOfferStacks
15} from "../../../shared/trade/space.js";
16
17const INVITE_MS = 60_000;
18const REJECT_BLOCK_MS = 60_000;
19
20function userError (message)
21{
22 const error = new Error(message);
23 error.userFacing = true;
24 return error;
25}
26
27export 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}