Tighten P2P trade: letter authorship, untradeable flag, preserve origins.
@@ -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 @@1
import {1
import {2
itemAssetPathForStack,2
itemAssetPathForStack,3
itemDescription,3
itemDisplayName,4
itemDisplayName,5
itemOriginSummary,4
formatQuantity6
formatQuantity5
} from "/shared/definitions/items.js";7
} from "/shared/definitions/items.js";6
import { applyItemIcon } from "../render/potionIcon.js";8
import { 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 ?? null125
instance: line.instance ?? null,126
origins: line.origins ?? undefined125
};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,@@ -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 @@1
import { randomUUID } from "node:crypto";1
import { randomUUID } from "node:crypto";2
import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";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
import {4
import {5
cloneStack,5
cloneStack,6
insertStack,6
insertStack,7
stackQuantity,7
stackQuantity,8
takeFromSlot8
takeFromSlot9
} from "../../../shared/items/inventory.js";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
import {12
import {12
inventorySlotsShortAfterTrade,13
inventorySlotsShortAfterTrade,13
resolveOfferStacks14
resolveOfferStacks@@ -271,8 +272,7 @@ export class TradeService271
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 TradeService385
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 TradeService443
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 TradeService522
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.taken545
});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;@@ -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";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { ItemId } from "../../shared/definitions/items.js";3
import { ItemId } from "../../shared/definitions/items.js";4
import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.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";5
import {7
import {6
inventorySlotsShortAfterTrade,8
inventorySlotsShortAfterTrade,7
resolveOfferStacks9
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
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
68
test("players can complete a 1-for-1 trade while adjacent", () =>71
test("players can complete a 1-for-1 trade while adjacent", () =>@@ -300,3 +303,149 @@ test("changing an offer clears accept flags", () =>300
finally303
finally301
{ harness.close(); }304
{ harness.close(); }302
});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
});