BlueGit

timfa questward

Tighten P2P trade: letter authorship, untradeable flag, preserve origins.

timfa Tim Falken · pushed by timfa

Authored 2026-09-04 · 2 months ago

Hash
6b2570b648e92332bcf5709e30b31a30f5d426a5
Parent
7d92c5d5
6 files changed +255 −27
client/src/play/trade.js +10 −2
@@ -1,6 +1,8 @@
1 1 import {
2 2 itemAssetPathForStack,
3 itemDescription,
3 4 itemDisplayName,
5 itemOriginSummary,
4 6 formatQuantity
5 7 } from "/shared/definitions/items.js";
6 8 import { applyItemIcon } from "../render/potionIcon.js";
@@ -117,12 +119,18 @@ export function initTrade ({
117 119 const btn = document.createElement("button");
118 120 btn.type = "button";
119 121 btn.className = "item-slot";
120 btn.title = `${line.displayName ?? "Item"}${line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""}`;
121 122 const stack = {
122 123 itemId: line.itemId,
123 124 quantity: line.quantity,
124 instance: line.instance ?? null
125 instance: line.instance ?? null,
126 origins: line.origins ?? undefined
125 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");
126 134 applyItemIcon(btn, stack, {
127 135 resolveSpriteUrl,
128 136 resolveImage,
@@ -1,6 +1,8 @@
1import {
1import {
2 itemAssetPathForStack,
2 itemAssetPathForStack,
3 itemDescription,
3 itemDisplayName,
4 itemDisplayName,
5 itemOriginSummary,
4 formatQuantity
6 formatQuantity
5} from "/shared/definitions/items.js";
7} from "/shared/definitions/items.js";
6import { applyItemIcon } from "../render/potionIcon.js";
8import { applyItemIcon } from "../render/potionIcon.js";
@@ -117,12 +119,18 @@ export function initTrade ({
117 const btn = document.createElement("button");
119 const btn = document.createElement("button");
118 btn.type = "button";
120 btn.type = "button";
119 btn.className = "item-slot";
121 btn.className = "item-slot";
120 btn.title = `${line.displayName ?? "Item"}${line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : ""}`;
121 const stack = {
122 const stack = {
122 itemId: line.itemId,
123 itemId: line.itemId,
123 quantity: line.quantity,
124 quantity: line.quantity,
124 instance: line.instance ?? null
125 instance: line.instance ?? null,
126 origins: line.origins ?? undefined
125 };
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");
126 applyItemIcon(btn, stack, {
134 applyItemIcon(btn, stack, {
127 resolveSpriteUrl,
135 resolveSpriteUrl,
128 resolveImage,
136 resolveImage,
server/src/trade/service.js +38 −16
@@ -1,13 +1,14 @@
1 1 import { randomUUID } from "node:crypto";
2 2 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
3 import { itemDefinition, itemDescription, itemDisplayName } from "../../../shared/definitions/items.js";
4 4 import {
5 5 cloneStack,
6 6 insertStack,
7 7 stackQuantity,
8 8 takeFromSlot
9 9 } from "../../../shared/items/inventory.js";
10 import { attachOrigins } from "../../../shared/items/origin.js";
10 import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
11 import { assertTradeable } from "../../../shared/items/trade.js";
11 12 import {
12 13 inventorySlotsShortAfterTrade,
13 14 resolveOfferStacks
@@ -271,8 +272,7 @@ export class TradeService
271 272 const slot = bag?.inventory?.[slotIndex];
272 273 if (!slot || stackQuantity(slot.quantity) < qty)
273 274 { throw userError("That item is not available."); }
274 if (!itemDefinition(slot.itemId))
275 { throw userError("That item cannot be traded."); }
275 assertTradeable(slot, side.characterId);
276 276
277 277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
278 278 if (existing >= 0)
@@ -385,31 +385,35 @@ export class TradeService
385 385
386 386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
387 387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
388 const takeLines = (inv, lines) =>
388 const takeOffer = (inv, lines) =>
389 389 {
390 const takenStacks = [];
390 391 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 392 for (const line of ordered)
392 393 {
393 394 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 if (!taken.ok)
395 if (!taken.ok || !taken.taken)
395 396 { throw userError("Trade failed."); }
396 397 inv = taken.slots;
398 takenStacks.push(attachOrigins(taken.taken));
397 399 }
398 return inv;
400 return { inv, takenStacks };
399 401 };
400 invA = takeLines(invA, session.a.offer);
401 invB = takeLines(invB, session.b.offer);
402 const fromA = takeOffer(invA, session.a.offer);
403 const fromB = takeOffer(invB, session.b.offer);
404 invA = fromA.inv;
405 invB = fromB.inv;
402 406
403 for (const stack of stacksB)
407 for (const stack of fromB.takenStacks)
404 408 {
405 const inserted = insertStack(invA, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
409 const inserted = insertStack(invA, cloneStack(stack), itemDefinition(stack.itemId));
406 410 if (!inserted.ok)
407 411 { throw userError("Trade failed."); }
408 412 invA = inserted.slots;
409 413 }
410 for (const stack of stacksA)
414 for (const stack of fromA.takenStacks)
411 415 {
412 const inserted = insertStack(invB, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
416 const inserted = insertStack(invB, cloneStack(stack), itemDefinition(stack.itemId));
413 417 if (!inserted.ok)
414 418 { throw userError("Trade failed."); }
415 419 invB = inserted.slots;
@@ -443,6 +447,16 @@ export class TradeService
443 447 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
444 448 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
445 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 }
446 460 }
447 461
448 462 #clearAccepts (session)
@@ -522,13 +536,21 @@ export class TradeService
522 536 if (!slot)
523 537 { continue; }
524 538 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 };
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 });
526 546 lines.push({
527 547 bagSlotIndex: line.bagSlotIndex | 0,
528 548 quantity: qty,
529 549 itemId: slot.itemId,
530 instance: slot.instance ?? null,
531 displayName: itemDisplayName(stack)
550 instance: stack.instance ?? null,
551 origins: stack.origins ?? null,
552 displayName: itemDisplayName(stack),
553 description: itemDescription(stack)
532 554 });
533 555 }
534 556 return lines;
@@ -1,13 +1,14 @@
1import { randomUUID } from "node:crypto";
1import { randomUUID } from "node:crypto";
2import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
2import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
3import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
3import { itemDefinition, itemDescription, itemDisplayName } from "../../../shared/definitions/items.js";
4import {
4import {
5 cloneStack,
5 cloneStack,
6 insertStack,
6 insertStack,
7 stackQuantity,
7 stackQuantity,
8 takeFromSlot
8 takeFromSlot
9} from "../../../shared/items/inventory.js";
9} from "../../../shared/items/inventory.js";
10import { attachOrigins } from "../../../shared/items/origin.js";
10import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
11import { assertTradeable } from "../../../shared/items/trade.js";
11import {
12import {
12 inventorySlotsShortAfterTrade,
13 inventorySlotsShortAfterTrade,
13 resolveOfferStacks
14 resolveOfferStacks
@@ -271,8 +272,7 @@ export class TradeService
271 const slot = bag?.inventory?.[slotIndex];
272 const slot = bag?.inventory?.[slotIndex];
272 if (!slot || stackQuantity(slot.quantity) < qty)
273 if (!slot || stackQuantity(slot.quantity) < qty)
273 { throw userError("That item is not available."); }
274 { throw userError("That item is not available."); }
274 if (!itemDefinition(slot.itemId))
275 assertTradeable(slot, side.characterId);
275 { throw userError("That item cannot be traded."); }
276
276
277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
277 const existing = side.self.offer.findIndex((line) => line.bagSlotIndex === slotIndex);
278 if (existing >= 0)
278 if (existing >= 0)
@@ -385,31 +385,35 @@ export class TradeService
385
385
386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
386 let invA = bagA.inventory.map((slot) => cloneStack(slot));
387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
387 let invB = bagB.inventory.map((slot) => cloneStack(slot));
388 const takeLines = (inv, lines) =>
388 const takeOffer = (inv, lines) =>
389 {
389 {
390 const takenStacks = [];
390 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 const ordered = [...lines].sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);
391 for (const line of ordered)
392 for (const line of ordered)
392 {
393 {
393 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 const taken = takeFromSlot(inv, line.bagSlotIndex, line.quantity);
394 if (!taken.ok)
395 if (!taken.ok || !taken.taken)
395 { throw userError("Trade failed."); }
396 { throw userError("Trade failed."); }
396 inv = taken.slots;
397 inv = taken.slots;
398 takenStacks.push(attachOrigins(taken.taken));
397 }
399 }
398 return inv;
400 return { inv, takenStacks };
399 };
401 };
400 invA = takeLines(invA, session.a.offer);
402 const fromA = takeOffer(invA, session.a.offer);
401 invB = takeLines(invB, session.b.offer);
403 const fromB = takeOffer(invB, session.b.offer);
404 invA = fromA.inv;
405 invB = fromB.inv;
402
406
403 for (const stack of stacksB)
407 for (const stack of fromB.takenStacks)
404 {
408 {
405 const inserted = insertStack(invA, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
409 const inserted = insertStack(invA, cloneStack(stack), itemDefinition(stack.itemId));
406 if (!inserted.ok)
410 if (!inserted.ok)
407 { throw userError("Trade failed."); }
411 { throw userError("Trade failed."); }
408 invA = inserted.slots;
412 invA = inserted.slots;
409 }
413 }
410 for (const stack of stacksA)
414 for (const stack of fromA.takenStacks)
411 {
415 {
412 const inserted = insertStack(invB, attachOrigins(cloneStack(stack)), itemDefinition(stack.itemId));
416 const inserted = insertStack(invB, cloneStack(stack), itemDefinition(stack.itemId));
413 if (!inserted.ok)
417 if (!inserted.ok)
414 { throw userError("Trade failed."); }
418 { throw userError("Trade failed."); }
415 invB = inserted.slots;
419 invB = inserted.slots;
@@ -443,6 +447,16 @@ export class TradeService
443 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
447 if (!resolveOfferStacks(bagA?.inventory, session.a.offer)
444 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
448 || !resolveOfferStacks(bagB?.inventory, session.b.offer))
445 { throw userError("An offered item is no longer available."); }
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 }
446 }
460 }
447
461
448 #clearAccepts (session)
462 #clearAccepts (session)
@@ -522,13 +536,21 @@ export class TradeService
522 if (!slot)
536 if (!slot)
523 { continue; }
537 { continue; }
524 const qty = Math.min(stackQuantity(slot.quantity), Math.max(1, line.quantity | 0 || 1));
538 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 };
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 });
526 lines.push({
546 lines.push({
527 bagSlotIndex: line.bagSlotIndex | 0,
547 bagSlotIndex: line.bagSlotIndex | 0,
528 quantity: qty,
548 quantity: qty,
529 itemId: slot.itemId,
549 itemId: slot.itemId,
530 instance: slot.instance ?? null,
550 instance: stack.instance ?? null,
531 displayName: itemDisplayName(stack)
551 origins: stack.origins ?? null,
552 displayName: itemDisplayName(stack),
553 description: itemDescription(stack)
532 });
554 });
533 }
555 }
534 return lines;
556 return lines;
server/tests/trade.test.js +154 −5
@@ -2,6 +2,8 @@ import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { ItemId } from "../../shared/definitions/items.js";
4 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";
5 7 import {
6 8 inventorySlotsShortAfterTrade,
7 9 resolveOfferStacks
@@ -54,15 +56,16 @@ test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>
54 56 );
55 57 });
56 58
57 test("resolveOfferStacks rejects missing quantities", () =>
59 test("resolveOfferStacks rejects missing quantities and slices origins", () =>
58 60 {
59 61 const slots = emptySlots();
60 62 slots[0] = apple(3);
61 63 assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
62 assert.deepEqual(
63 resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]),
64 [{ itemId: ItemId.apple, quantity: 2, instance: null, origins: undefined }]
65 );
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);
66 69 });
67 70
68 71 test("players can complete a 1-for-1 trade while adjacent", () =>
@@ -300,3 +303,149 @@ test("changing an offer clears accept flags", () =>
300 303 finally
301 304 { harness.close(); }
302 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 });
@@ -2,6 +2,8 @@ import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { ItemId } from "../../shared/definitions/items.js";
3import { ItemId } from "../../shared/definitions/items.js";
4import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
4import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
5import { gatherOrigin, GatherOriginVerb } from "../../shared/items/origin.js";
6import { canTradeStack } from "../../shared/items/trade.js";
5import {
7import {
6 inventorySlotsShortAfterTrade,
8 inventorySlotsShortAfterTrade,
7 resolveOfferStacks
9 resolveOfferStacks
@@ -54,15 +56,16 @@ test("inventorySlotsShortAfterTrade accounts for freed give slots", () =>
54 );
56 );
55});
57});
56
58
57test("resolveOfferStacks rejects missing quantities", () =>
59test("resolveOfferStacks rejects missing quantities and slices origins", () =>
58{
60{
59 const slots = emptySlots();
61 const slots = emptySlots();
60 slots[0] = apple(3);
62 slots[0] = apple(3);
61 assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
63 assert.equal(resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 4 }]), null);
62 assert.deepEqual(
64 const resolved = resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]);
63 resolveOfferStacks(slots, [{ bagSlotIndex: 0, quantity: 2 }]),
65 assert.equal(resolved?.length, 1);
64 [{ itemId: ItemId.apple, quantity: 2, instance: null, origins: undefined }]
66 assert.equal(resolved[0].itemId, ItemId.apple);
65 );
67 assert.equal(resolved[0].quantity, 2);
68 assert.equal(resolved[0].origins?.reduce((sum, entry) => sum + (entry.quantity | 0), 0), 2);
66});
69});
67
70
68test("players can complete a 1-for-1 trade while adjacent", () =>
71test("players can complete a 1-for-1 trade while adjacent", () =>
@@ -300,3 +303,149 @@ test("changing an offer clears accept flags", () =>
300 finally
303 finally
301 { harness.close(); }
304 { harness.close(); }
302});
305});
306
307test("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
381test("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
438test("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});
shared/definitions/items.js +2 −0
@@ -130,6 +130,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
130 130 defaultState: "letter-opened",
131 131 marketplaceSellable: false,
132 132 marketplaceSellBlockedReason: "Letters cannot be sold on the marketplace."
133 // Letters are not `untradeable`: P2P trade uses authorship rules in shared/items/trade.js
134 // (same spirit as private ground letters). Use `untradeable: true` for future bound/quest items.
133 135 }),
134 136 [ItemId.apple]: Object.freeze({
135 137 itemId: ItemId.apple,
@@ -130,6 +130,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
130 defaultState: "letter-opened",
130 defaultState: "letter-opened",
131 marketplaceSellable: false,
131 marketplaceSellable: false,
132 marketplaceSellBlockedReason: "Letters cannot be sold on the marketplace."
132 marketplaceSellBlockedReason: "Letters cannot be sold on the marketplace."
133 // Letters are not `untradeable`: P2P trade uses authorship rules in shared/items/trade.js
134 // (same spirit as private ground letters). Use `untradeable: true` for future bound/quest items.
133 }),
135 }),
134 [ItemId.apple]: Object.freeze({
136 [ItemId.apple]: Object.freeze({
135 itemId: ItemId.apple,
137 itemId: ItemId.apple,
shared/items/trade.js added +42 −0
@@ -0,0 +1,42 @@
1 import { itemDefinition } from "../definitions/items.js";
2 import { canTransferLetterToOtherPlayers, isLetterStack } from "./letters.js";
3
4 /**
5 * Player-to-player trade eligibility.
6 * Rule of thumb: if it can be dropped and another player can pick it up, it is tradeable.
7 * Letters use their own authorship rules (same as ground privacy); do not set `untradeable` on letters.
8 * Future quest/bound items may set `def.untradeable = true`.
9 *
10 * @param {object|null|undefined} stack
11 * @param {number} characterId offering player
12 */
13 export function canTradeStack (stack, characterId)
14 {
15 if (!stack)
16 { return false; }
17 const def = itemDefinition(stack.itemId);
18 if (!def)
19 { return false; }
20 if (def.untradeable === true)
21 { return false; }
22 if (!canTransferLetterToOtherPlayers(stack, characterId))
23 { return false; }
24 return true;
25 }
26
27 /** @throws {Error & { userFacing?: boolean }} */
28 export function assertTradeable (stack, characterId)
29 {
30 if (canTradeStack(stack, characterId))
31 { return; }
32 const def = itemDefinition(stack?.itemId);
33 const error = new Error(
34 def?.untradeable === true
35 ? (def.untradeableBlockedReason || "That item cannot be traded.")
36 : (isLetterStack(stack)
37 ? "You can only trade letters you wrote."
38 : "That item cannot be traded.")
39 );
40 error.userFacing = true;
41 throw error;
42 }
@@ -0,0 +1,42 @@
1import { itemDefinition } from "../definitions/items.js";
2import { canTransferLetterToOtherPlayers, isLetterStack } from "./letters.js";
3
4/**
5 * Player-to-player trade eligibility.
6 * Rule of thumb: if it can be dropped and another player can pick it up, it is tradeable.
7 * Letters use their own authorship rules (same as ground privacy); do not set `untradeable` on letters.
8 * Future quest/bound items may set `def.untradeable = true`.
9 *
10 * @param {object|null|undefined} stack
11 * @param {number} characterId offering player
12 */
13export function canTradeStack (stack, characterId)
14{
15 if (!stack)
16 { return false; }
17 const def = itemDefinition(stack.itemId);
18 if (!def)
19 { return false; }
20 if (def.untradeable === true)
21 { return false; }
22 if (!canTransferLetterToOtherPlayers(stack, characterId))
23 { return false; }
24 return true;
25}
26
27/** @throws {Error & { userFacing?: boolean }} */
28export function assertTradeable (stack, characterId)
29{
30 if (canTradeStack(stack, characterId))
31 { return; }
32 const def = itemDefinition(stack?.itemId);
33 const error = new Error(
34 def?.untradeable === true
35 ? (def.untradeableBlockedReason || "That item cannot be traded.")
36 : (isLetterStack(stack)
37 ? "You can only trade letters you wrote."
38 : "That item cannot be traded.")
39 );
40 error.userFacing = true;
41 throw error;
42}
shared/trade/space.js +9 −4
@@ -6,6 +6,7 @@ import {
6 6 INVENTORY_SLOTS
7 7 } from "../items/inventory.js";
8 8 import { itemDefinition } from "../definitions/items.js";
9 import { attachOrigins, normalizeOrigins, splitOrigins } from "../items/origin.js";
9 10
10 11 /**
11 12 * How many additional empty bag slots a player would need after giving
@@ -57,7 +58,10 @@ export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiv
57 58 return 0;
58 59 }
59 60
60 /** Snapshot offer lines as transferable stacks from a bag (or null if invalid). */
61 /**
62 * Snapshot offer lines as transferable stacks from a bag (or null if invalid).
63 * Origins are sliced to the offered quantity (same as takeFromSlot).
64 */
61 65 export function resolveOfferStacks (inventorySlots, offerLines)
62 66 {
63 67 const stacks = [];
@@ -67,12 +71,13 @@ export function resolveOfferStacks (inventorySlots, offerLines)
67 71 const qty = Math.max(1, line.quantity | 0 || 1);
68 72 if (!slot || stackQuantity(slot.quantity) < qty)
69 73 { return null; }
70 stacks.push({
74 const split = splitOrigins(normalizeOrigins(slot), qty);
75 stacks.push(attachOrigins({
71 76 itemId: slot.itemId,
72 77 quantity: qty,
73 78 instance: slot.instance ? structuredClone(slot.instance) : null,
74 origins: slot.origins ? structuredClone(slot.origins) : undefined
75 });
79 origins: split.taken
80 }));
76 81 }
77 82 return stacks;
78 83 }
@@ -6,6 +6,7 @@ import {
6 INVENTORY_SLOTS
6 INVENTORY_SLOTS
7} from "../items/inventory.js";
7} from "../items/inventory.js";
8import { itemDefinition } from "../definitions/items.js";
8import { itemDefinition } from "../definitions/items.js";
9import { attachOrigins, normalizeOrigins, splitOrigins } from "../items/origin.js";
9
10
10/**
11/**
11 * How many additional empty bag slots a player would need after giving
12 * How many additional empty bag slots a player would need after giving
@@ -57,7 +58,10 @@ export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiv
57 return 0;
58 return 0;
58}
59}
59
60
60/** Snapshot offer lines as transferable stacks from a bag (or null if invalid). */
61/**
62 * Snapshot offer lines as transferable stacks from a bag (or null if invalid).
63 * Origins are sliced to the offered quantity (same as takeFromSlot).
64 */
61export function resolveOfferStacks (inventorySlots, offerLines)
65export function resolveOfferStacks (inventorySlots, offerLines)
62{
66{
63 const stacks = [];
67 const stacks = [];
@@ -67,12 +71,13 @@ export function resolveOfferStacks (inventorySlots, offerLines)
67 const qty = Math.max(1, line.quantity | 0 || 1);
71 const qty = Math.max(1, line.quantity | 0 || 1);
68 if (!slot || stackQuantity(slot.quantity) < qty)
72 if (!slot || stackQuantity(slot.quantity) < qty)
69 { return null; }
73 { return null; }
70 stacks.push({
74 const split = splitOrigins(normalizeOrigins(slot), qty);
75 stacks.push(attachOrigins({
71 itemId: slot.itemId,
76 itemId: slot.itemId,
72 quantity: qty,
77 quantity: qty,
73 instance: slot.instance ? structuredClone(slot.instance) : null,
78 instance: slot.instance ? structuredClone(slot.instance) : null,
74 origins: slot.origins ? structuredClone(slot.origins) : undefined
79 origins: split.taken
75 });
80 }));
76 }
81 }
77 return stacks;
82 return stacks;
78}
83}