import { randomUUID } from "node:crypto"; import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; import { itemDefinition, itemDescription, itemDisplayName } from "../../../shared/definitions/items.js"; import { cloneStack, insertStack, stackQuantity, takeFromSlot } from "../../../shared/items/inventory.js"; import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js"; import { assertTradeable } from "../../../shared/items/trade.js"; import { inventorySlotsShortAfterTrade, resolveOfferStacks } from "../../../shared/trade/space.js"; const INVITE_MS = 60_000; const REJECT_BLOCK_MS = 60_000; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } export class TradeService { /** * @param {{ simulation: object, stateDb: object }} opts */ constructor ({ simulation, stateDb }) { this.simulation = simulation; this.stateDb = stateDb; /** @type {Map} */ this.invites = new Map(); /** @type {Map} rejectorId:fromId → blockedUntil */ this.rejectBlocks = new Map(); /** @type {Map} characterId → session */ this.sessions = new Map(); } step (now = Date.now()) { const events = []; for (const [id, invite] of [...this.invites.entries()]) { if (now >= invite.expiresAt) { this.invites.delete(id); events.push({ type: "trade-invite-expired", characterId: invite.toCharacterId, inviteId: id }); } } for (const [key, until] of [...this.rejectBlocks.entries()]) { if (now >= until) { this.rejectBlocks.delete(key); } } for (const [characterId, session] of [...this.sessions.entries()]) { if (!this.#partnersAdjacent(session)) { events.push(...this.#closeSession(session, "You moved too far apart.")); void characterId; } } return events; } handleCommand (sessionId, command, now = Date.now()) { switch (command.type) { case "trade-request": return this.request(sessionId, command.characterId, command.targetEntityId, now); case "trade-respond-invite": return this.respondInvite( sessionId, command.characterId, command.inviteId, !!command.accept, now ); case "trade-offer-set": return this.setOffer( sessionId, command.characterId, command.bagSlotIndex, command.quantity, now ); case "trade-offer-remove": return this.removeOffer(sessionId, command.characterId, command.bagSlotIndex, now); case "trade-accept": return this.accept(sessionId, command.characterId, now); case "trade-cancel": return this.cancel(sessionId, command.characterId, now); default: return { events: [] }; } } onCharacterGone (characterId) { const events = []; const id = characterId | 0; for (const [inviteId, invite] of [...this.invites.entries()]) { if (invite.fromCharacterId === id || invite.toCharacterId === id) { this.invites.delete(inviteId); const other = invite.fromCharacterId === id ? invite.toCharacterId : invite.fromCharacterId; events.push({ type: "trade-invite-expired", characterId: other, inviteId }); } } const session = this.sessions.get(id); if (session) { events.push(...this.#closeSession(session, "Trade cancelled.")); } return events; } request (sessionId, characterId, targetEntityId, now = Date.now()) { const fromId = characterId | 0; const fromEntityId = this.simulation.characterEntities.get(fromId); if (!fromEntityId) { throw userError("You are not in the world."); } if (this.sessions.has(fromId)) { throw userError("You are already trading."); } const target = this.#resolvePlayerTarget(targetEntityId | 0); if (!target) { throw userError("That player is not here."); } if (target.characterId === fromId) { throw userError("You cannot trade with yourself."); } if (this.sessions.has(target.characterId)) { throw userError("That player is already trading."); } const blockKey = `${target.characterId}:${fromId}`; const blockedUntil = this.rejectBlocks.get(blockKey) ?? 0; if (now < blockedUntil) { throw userError("That player declined a recent trade request."); } for (const invite of this.invites.values()) { if (invite.fromCharacterId === fromId && invite.toCharacterId === target.characterId) { throw userError("You already sent a trade request."); } } const fromPos = this.#positionOf(fromEntityId); const toPos = this.#positionOf(target.entityId); if (!fromPos || !toPos) { throw userError("That player is not here."); } const fromRow = this.stateDb.getCharacter(fromId); const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Someone"; const inviteId = randomUUID(); this.invites.set(inviteId, { inviteId, fromCharacterId: fromId, fromEntityId, fromSessionId: sessionId, toCharacterId: target.characterId, toEntityId: target.entityId, expiresAt: now + INVITE_MS }); return { events: [ { type: "toast", characterId: fromId, message: `Trade request sent to ${target.name}.` }, { type: "trade-invite", characterId: target.characterId, inviteId, fromCharacterId: fromId, fromEntityId, fromName, expiresAt: now + INVITE_MS } ] }; } respondInvite (sessionId, characterId, inviteId, accept, now = Date.now()) { const toId = characterId | 0; const invite = this.invites.get(String(inviteId ?? "")); if (!invite || invite.toCharacterId !== toId) { throw userError("That trade request expired."); } this.invites.delete(invite.inviteId); if (!accept) { this.rejectBlocks.set(`${toId}:${invite.fromCharacterId}`, now + REJECT_BLOCK_MS); const toRow = this.stateDb.getCharacter(toId); const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Someone"; return { events: [ { type: "toast", characterId: invite.fromCharacterId, message: `${toName} declined your trade request.` }, { type: "trade-invite-expired", characterId: toId, inviteId: invite.inviteId } ] }; } if (this.sessions.has(invite.fromCharacterId) || this.sessions.has(toId)) { throw userError("A trade is already open."); } const fromEntityId = this.simulation.characterEntities.get(invite.fromCharacterId); const toEntityId = this.simulation.characterEntities.get(toId); if (!fromEntityId || !toEntityId) { throw userError("That player is not here."); } if (!this.#entitiesAdjacent(fromEntityId, toEntityId)) { throw userError("You need to stand next to each other to trade."); } const fromRow = this.stateDb.getCharacter(invite.fromCharacterId); const toRow = this.stateDb.getCharacter(toId); const fromName = `${fromRow?.first_name ?? ""} ${fromRow?.last_name ?? ""}`.trim() || "Player"; const toName = `${toRow?.first_name ?? ""} ${toRow?.last_name ?? ""}`.trim() || "Player"; const session = { a: { characterId: invite.fromCharacterId, entityId: fromEntityId, sessionId: invite.fromSessionId, name: fromName, offer: [], accepted: false }, b: { characterId: toId, entityId: toEntityId, sessionId, name: toName, offer: [], accepted: false } }; this.sessions.set(session.a.characterId, session); this.sessions.set(session.b.characterId, session); return { events: this.#openEvents(session) }; } setOffer (sessionId, characterId, bagSlotIndex, quantity, now = Date.now()) { void now; const side = this.#requireSide(characterId); const slotIndex = bagSlotIndex | 0; const qty = Math.max(1, quantity | 0 || 1); const bag = this.#bagOf(side.characterId); const slot = bag?.inventory?.[slotIndex]; if (!slot || stackQuantity(slot.quantity) < qty) { throw userError("That item is not available."); } assertTradeable(slot, side.characterId); const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex); if (existing >= 0) { side.self.offer[existing].quantity = qty; } else { side.self.offer.push({ bagSlotIndex: slotIndex, quantity: qty }); } this.#clearAccepts(side.session); return { events: this.#stateEvents(side.session) }; } removeOffer (sessionId, characterId, bagSlotIndex, now = Date.now()) { void now; const side = this.#requireSide(characterId); const slotIndex = bagSlotIndex | 0; side.self.offer = side.self.offer.filter((line) => line.bagSlotIndex !== slotIndex); this.#clearAccepts(side.session); return { events: this.#stateEvents(side.session) }; } accept (sessionId, characterId, now = Date.now()) { void now; const side = this.#requireSide(characterId); if (side.self.accepted) { side.self.accepted = false; return { events: this.#stateEvents(side.session) }; } if (!this.#partnersAdjacent(side.session)) { throw userError("You need to stand next to each other to trade."); } this.#assertOffersValid(side.session); side.self.accepted = true; if (side.self.accepted && side.partner.accepted) { return this.#tryComplete(side.session); } return { events: this.#stateEvents(side.session) }; } cancel (sessionId, characterId, now = Date.now()) { void now; const side = this.#requireSide(characterId); return { events: this.#closeSession(side.session, null) }; } #tryComplete (session) { const bagA = this.#bagOf(session.a.characterId); const bagB = this.#bagOf(session.b.characterId); if (!bagA?.inventory || !bagB?.inventory) { throw userError("Trade failed."); } const stacksA = resolveOfferStacks(bagA.inventory, session.a.offer); const stacksB = resolveOfferStacks(bagB.inventory, session.b.offer); if (!stacksA || !stacksB) { this.#clearAccepts(session); return { events: [ ...this.#stateEvents(session), { type: "toast", characterId: session.a.characterId, message: "An offered item is no longer available." }, { type: "toast", characterId: session.b.characterId, message: "An offered item is no longer available." } ] }; } const shortA = inventorySlotsShortAfterTrade(bagA.inventory, session.a.offer, stacksB); const shortB = inventorySlotsShortAfterTrade(bagB.inventory, session.b.offer, stacksA); if (shortA > 0 || shortB > 0) { this.#clearAccepts(session); const events = [...this.#stateEvents(session)]; if (shortA > 0) { events.push({ type: "toast", characterId: session.a.characterId, message: `You need ${shortA} more free inventory slots.` }); events.push({ type: "toast", characterId: session.b.characterId, message: `${session.a.name} needs ${shortA} more free inventory slots.` }); } if (shortB > 0) { events.push({ type: "toast", characterId: session.b.characterId, message: `You need ${shortB} more free inventory slots.` }); events.push({ type: "toast", characterId: session.a.characterId, message: `${session.b.name} needs ${shortB} more free inventory slots.` }); } return { events }; } let invA = bagA.inventory.map((slot) => cloneStack(slot)); let invB = bagB.inventory.map((slot) => cloneStack(slot)); const takeOffer = (inv, lines) => { const takenStacks = []; const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex); for (const line of ordered) { const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity); if (!taken.ok || !taken.taken) { throw userError("Trade failed."); } inv = taken.slots; takenStacks.push(attachOrigins(taken.taken)); } return { inv, takenStacks }; }; const fromA = takeOffer(invA, session.a.offer); const fromB = takeOffer(invB, session.b.offer); invA = fromA.inv; invB = fromB.inv; for (const stack of fromB.takenStacks) { const inserted = insertStack(invA, cloneStack(stack), itemDefinition(stack.itemId)); if (!inserted.ok) { throw userError("Trade failed."); } invA = inserted.slots; } for (const stack of fromA.takenStacks) { const inserted = insertStack(invB, cloneStack(stack), itemDefinition(stack.itemId)); if (!inserted.ok) { throw userError("Trade failed."); } invB = inserted.slots; } bagA.inventory = invA; bagB.inventory = invB; this.#persistBag(session.a.characterId, bagA); this.#persistBag(session.b.characterId, bagB); const events = this.#closeSession(session, null); events.push( { type: "toast", characterId: session.a.characterId, message: "Trade complete." }, { type: "toast", characterId: session.b.characterId, message: "Trade complete." } ); return { events }; } #assertOffersValid (session) { const bagA = this.#bagOf(session.a.characterId); const bagB = this.#bagOf(session.b.characterId); if (!resolveOfferStacks(bagA?.inventory, session.a.offer) || !resolveOfferStacks(bagB?.inventory, session.b.offer)) { throw userError("An offered item is no longer available."); } for (const line of session.a.offer) { const slot = bagA.inventory?.[line.bagSlotIndex]; assertTradeable(slot, session.a.characterId); } for (const line of session.b.offer) { const slot = bagB.inventory?.[line.bagSlotIndex]; assertTradeable(slot, session.b.characterId); } } #clearAccepts (session) { session.a.accepted = false; session.b.accepted = false; } #requireSide (characterId) { const id = characterId | 0; const session = this.sessions.get(id); if (!session) { throw userError("You are not trading."); } const self = session.a.characterId === id ? session.a : session.b; const partner = session.a.characterId === id ? session.b : session.a; return { session, self, partner, characterId: id }; } #openEvents (session) { return [ { type: "trade-open", characterId: session.a.characterId, partnerCharacterId: session.b.characterId, partnerEntityId: session.b.entityId, partnerName: session.b.name, ...this.#publicStateFor(session, session.a) }, { type: "trade-open", characterId: session.b.characterId, partnerCharacterId: session.a.characterId, partnerEntityId: session.a.entityId, partnerName: session.a.name, ...this.#publicStateFor(session, session.b) } ]; } #stateEvents (session) { return [ { type: "trade-state", characterId: session.a.characterId, ...this.#publicStateFor(session, session.a) }, { type: "trade-state", characterId: session.b.characterId, ...this.#publicStateFor(session, session.b) } ]; } #publicStateFor (session, self) { const partner = session.a === self ? session.b : session.a; const selfBag = this.#bagOf(self.characterId); const partnerBag = this.#bagOf(partner.characterId); return { youAccepted: !!self.accepted, theyAccepted: !!partner.accepted, yourOffer: this.#publicOffer(selfBag?.inventory, self.offer), theirOffer: this.#publicOffer(partnerBag?.inventory, partner.offer) }; } #publicOffer (inventory, offer) { const lines = []; for (const line of offer ?? []) { const slot = inventory?.[line.bagSlotIndex]; if (!slot) { continue; } const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1)); const split = splitOrigins(normalizeOrigins(slot), qty); const stack = attachOrigins({ itemId: slot.itemId, quantity: qty, instance: slot.instance ? structuredClone(slot.instance) : null, origins: split.taken }); lines.push({ bagSlotIndex: line.bagSlotIndex | 0, quantity: qty, itemId: slot.itemId, instance: stack.instance ?? null, origins: stack.origins ?? null, displayName: itemDisplayName(stack), description: itemDescription(stack) }); } return lines; } #closeSession (session, toastMessage) { this.sessions.delete(session.a.characterId); this.sessions.delete(session.b.characterId); const events = [ { type: "trade-closed", characterId: session.a.characterId }, { type: "trade-closed", characterId: session.b.characterId } ]; if (toastMessage) { events.push( { type: "toast", characterId: session.a.characterId, message: toastMessage }, { type: "toast", characterId: session.b.characterId, message: toastMessage } ); } return events; } #resolvePlayerTarget (entityId) { for (const [characterId, id] of this.simulation.characterEntities.entries()) { if ((id | 0) !== (entityId | 0)) { continue; } const row = this.stateDb.getCharacter(characterId); const name = `${row?.first_name ?? ""} ${row?.last_name ?? ""}`.trim() || "Player"; return { characterId: characterId | 0, entityId: id | 0, name }; } return null; } #positionOf (entityId) { const pos = this.simulation.positionOf(entityId); if (!pos || pos.tileX == null) { return null; } return { tileX: pos.tileX | 0, tileY: pos.tileY | 0 }; } #entitiesAdjacent (entityIdA, entityIdB) { const a = this.#positionOf(entityIdA); const b = this.#positionOf(entityIdB); if (!a || !b) { return false; } return isAdjacentTile(a.tileX, a.tileY, b.tileX, b.tileY) || (a.tileX === b.tileX && a.tileY === b.tileY); } #partnersAdjacent (session) { return this.#entitiesAdjacent(session.a.entityId, session.b.entityId); } #bagOf (characterId) { const onlineId = this.simulation.characterEntities.get(characterId | 0); return onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId | 0); if (onlineId) { this.simulation.applyBag?.(onlineId, bag); this.simulation.pushInventory?.(characterId, bag); } } }