Skip to content
FMFallout Multiplayer Scripting APIScripting guides and API
GuideMaintainer authored

A shopkeeper and player trades

Put a vendor NPC behind a counter, sell from a container whose stock and prices only the server holds, charge for every item taken, and let two players trade with a server-checked offer.

Fallout 4’s own barter menu belongs to each player’s game, so a server cannot set its prices or keep its stock. You will build a shop that the server owns from end to end: a vendor who stands behind his counter, a container that opens on the server’s stock, caps charged for each item taken and paid for each item sold, and a way for two players to trade with each other that neither can cheat.

This is the trade feature of the default gamemode, rebuilt step by step.

  • Turning an NPC into a fixture: frozen, unhurtable, his own greeting replaced by yours.
  • Showing a place with a Checkpoint ring and watching it with a Zone.
  • Opening a container from a server decision, through the client’s References.openContainer.
  • The four container events, in the order they fire, and which one can refuse.
  • Moving items and caps between two players without trusting either of them.
trading-post/
package.json
tsconfig.json
src/server/
index.ts imports
stock.ts what the shop sells, and for how much
vendor.ts the NPC, his ring and his zone
shop.ts charging and paying through the container
offers.ts /offer, /accept, /decline between players
src/client/
index.ts opens the shop, shows the hint
ui/
hint.html "[E] Trade with the vendor"

The vendor’s inventory is not his. It lives in a Map on the server, and a placed container stands in for it while a customer is browsing:

  1. The player activates the vendor. The server hears npcActivate.
  2. The server tells that player’s game to open the shop’s container.
  3. containerOpen fires. The server fills the container with the current stock.
  4. The player takes or puts items. inventoryChange asks first, and the server refuses what they cannot afford. containerChange then reports what the container holds now.
  5. The server compares before and after, charges or pays caps, and updates its stock.
  6. containerClose fires. The server empties the container again.

Only one player can hold a container at a time, so the stock never changes under a buyer.

Prices are per item, in caps. The shop buys back at half price, and pays nothing for what it does not sell itself:

src/server/stock.ts
export interface Ware {
count: number;
price: number;
}
/** By base object form ID. This map is the whole shop. */
export const stock = new Map<number, Ware>([
[0x4d1f2, { count: 10, price: 12 }], // duct tape
[0x23736, { count: 5, price: 40 }], // stimpak
[0x1f276, { count: 200, price: 2 }], // 10mm rounds
]);
export const priceOf = (form: number): number => stock.get(form)?.price ?? 0;
export const buybackOf = (form: number): number => Math.floor(priceOf(form) / 2);
/** What the container should hold right now. */
export function stockItems(): { form: number; count: number }[] {
return [...stock]
.filter(([, ware]) => ware.count > 0)
.map(([form, ware]) => ({ form, count: ware.count }));
}
/** Rows to counts, summing duplicate forms. */
export function countsOf(items: readonly { form: number; count: number }[]): Map<number, number> {
const counts = new Map<number, number>();
for (const item of items) counts.set(item.form, (counts.get(item.form) ?? 0) + item.count);
return counts;
}

A settler, spawned once, then turned into part of the furniture. Each call below is replicated to every player’s copy of him:

src/server/vendor.ts
const kSpot = new Vector3(-80468, 88474, 7730); // Sanctuary, by the bridge
const kHeading = Math.PI; // facing south
const kShopRadius = 450;
/** DialogueGenericCitizens' hello: a line every settler voice has. */
const kHello = 0xd101e;
let vendor: Npc | null = null;
let shopZone = 0;
export const vendorNpc = (): Npc | null => vendor;
export function openVendor(): void {
if (vendor !== null) return;
try {
vendor = Npc.spawn("WorkshopNPCMale", kSpot, { heading: kHeading });
} catch (error) {
console.error(`no vendor: ${String(error)}`);
return;
}
if (vendor === null) return;
vendor.setName("Shopkeeper"); // the crosshair says this, not "Settler"
vendor.setInvulnerable(true); // shots pass through him
vendor.setActivationBlocked(true); // no greeting or dialogue; npcActivate still fires
vendor.setRestrained(true); // stands at his counter, head still free to turn
Blip.create({ entity: vendor, label: "Shop", kind: "custom" });
TextLabel.create({ entity: vendor, text: "Shop", color: 0x12ff15ff, range: 800 });
// A flat green ring around the counter, so players see where the shop is...
Checkpoint.create({ position: kSpot, radius: 120, height: 0, color: 0x12ff1590, range: 1500 });
// ...and a zone over the same floor, so the server knows who walked in.
shopZone = Zone.create({ center: kSpot, radius: kShopRadius, height: 400, name: "Shop" });
}
Events.on("zoneEnter", (player: Player, zone: number) => {
if (zone !== shopZone) return;
player.emit("hud:notify", JSON.stringify("The Shopkeeper trades here: talk to him to buy and sell"));
vendor?.say(kHello);
});

A Checkpoint and a Zone are two halves of one idea. The checkpoint is purely visual and the server never hears about it again. The zone draws nothing, and raises zoneEnter and zoneLeave from the positions players’ games report. Give them the same center and radius and the ring means what it shows.

setActivationBlocked(true) is what makes the vendor yours. The game no longer starts his dialogue when a player presses Activate on him, but npcActivate is still raised, so your script decides what that button does.

The server cannot open a menu in somebody’s game by itself; it asks that game to. On the server:

src/server/shop.ts
import { buybackOf, countsOf, priceOf, stock, stockItems } from "./stock.js";
import { openVendor, vendorNpc } from "./vendor.js";
/** Loot_Prewar_Suitcase_Clothes in Sanctuary, standing in as the shop's till. */
export const kShopContainer = 0xae137;
const report = (player: Player, text: string): void => {
Chat.sendToPlayer(player, text, { author: "Shop" });
};
Events.on("playerReady", (player: Player) => {
openVendor();
const vendor = vendorNpc();
// Each game needs to know which body is the vendor, to show the hint in step 7.
if (vendor !== null) player.emit("trade:vendor", JSON.stringify(vendor.id));
});
Events.on("npcActivate", (player: Player, npc: Npc) => {
const vendor = vendorNpc();
if (vendor === null || npc.id !== vendor.id) return;
player.emit("trade:openShop", JSON.stringify(kShopContainer));
vendor.lookAt(player); // he watches his customer
});

And in that player’s game:

src/client/index.ts
// client
Events.on("trade:openShop", (payload: unknown) => {
if (typeof payload === "number") References.openContainer(payload);
});

References.openContainer opens the container menu wherever the player stands, without its lock or its animation. It does not bypass the server: containerOpen still runs first, exactly as if the player had walked up and opened the suitcase themselves.

Now the four container events. Keep a snapshot of what the container held per shopper, so each change can be priced against it:

src/server/shop.ts
import { buybackOf, countsOf, priceOf, stock, stockItems } from "./stock.js";
import { openVendor, vendorNpc } from "./vendor.js";
export const kShopContainer = 0xae137;
const report = (player: Player, text: string): void => {
Chat.sendToPlayer(player, text, { author: "Shop" });
};
/** Who is in the shop, and what it held when they last moved something. */
const shoppers = new Map<number, Map<number, number>>();
Events.on("playerReady", (player: Player) => {
openVendor();
const vendor = vendorNpc();
if (vendor !== null) player.emit("trade:vendor", JSON.stringify(vendor.id));
});
Events.on("npcActivate", (player: Player, npc: Npc) => {
const vendor = vendorNpc();
if (vendor === null || npc.id !== vendor.id) return;
player.emit("trade:openShop", JSON.stringify(kShopContainer));
vendor.lookAt(player);
});
// 1. Fill the till with the server's stock as they open it.
Events.on("containerOpen", (player: Player, ref: number) => {
if (ref !== kShopContainer) return;
Objects.setContainer(ref, stockItems());
shoppers.set(player.id, countsOf(stockItems()));
report(player, `You have ${player.getCaps()} caps.`);
});
// 2. Before a transfer lands: refuse what they cannot pay for.
Events.on("inventoryChange", (player: Player, changes: InventoryDelta[]) => {
if (!shoppers.has(player.id)) return;
let cost = 0;
for (const change of changes) {
if (change.from !== kShopContainer) continue;
// Taken from the shop costs the full price; put into it earns the buyback.
cost += change.delta > 0 ? change.delta * priceOf(change.form) : change.delta * buybackOf(change.form);
}
if (cost > player.getCaps()) {
report(player, `That costs ${cost} caps. You have ${player.getCaps()}.`);
return false;
}
});
// 3. After: the container's new contents. Price the difference.
Events.on("containerChange", (player: Player, ref: number, items: InventoryItem[]) => {
const before = shoppers.get(player.id);
if (ref !== kShopContainer || before === undefined) return;
const after = countsOf(items);
let caps = player.getCaps();
for (const form of new Set([...before.keys(), ...after.keys()])) {
const moved = (after.get(form) ?? 0) - (before.get(form) ?? 0);
if (moved === 0) continue;
// Fewer in the shop: bought. More: sold to it.
caps += moved < 0 ? moved * priceOf(form) : moved * buybackOf(form);
const ware = stock.get(form);
if (ware !== undefined) ware.count = after.get(form) ?? 0;
else stock.set(form, { count: after.get(form) ?? 0, price: 0 });
}
player.setCaps(Math.max(0, caps));
shoppers.set(player.id, after);
});
// 4. Empty the till between customers.
Events.on("containerClose", (player: Player, ref: number) => {
if (ref !== kShopContainer || !shoppers.delete(player.id)) return;
Objects.setContainer(ref, []);
vendorNpc()?.lookAt(null);
});
Events.on("playerDisconnect", (player: Player) => {
shoppers.delete(player.id);
});

Why two events for one transfer:

Event When Can refuse Use it for
inventoryChange Before the server accepts the player’s change Yes: their game and the container both revert Saying no
containerChange After, with the container’s full contents No Bookkeeping

Refusing inventoryChange is the only refusal you need. The container is reverted together with the player’s pockets, so there is nothing to undo by hand. containerChange only ever sees transfers that were allowed.

The second half of the feature has no container at all. /offer <player> <item> <count> <caps> proposes a sale, /accept on the other side completes it, and the server moves everything itself:

src/server/offers.ts
interface Offer {
seller: number;
form: number;
count: number;
caps: number;
}
/** One pending offer per buyer; a new one replaces it. */
const offers = new Map<number, Offer>();
const kTradeRange = 500;
const near = (a: Player, b: Player): boolean => a.position.distance(b.position) <= kTradeRange;
const tell = (player: Player, text: string): void => Chat.sendToPlayer(player, text, { author: "Trade" });
function offer(seller: Player, args: string[]): void {
const [who, formText, countText, capsText] = args;
const buyer = Player.all().find((p) => p.nickname === who || String(p.id) === who);
const form = formText !== undefined ? parseInt(formText.replace(/^0x/i, ""), 16) : NaN;
const count = Number(countText);
const caps = Number(capsText);
if (!buyer || buyer.id === seller.id || !Number.isInteger(form) || !(count >= 1) || !(caps >= 0)) {
tell(seller, "/offer <player> <item> <count> <caps>");
return;
}
if (!near(seller, buyer)) return tell(seller, `${buyer.nickname} is too far away.`);
if (seller.getItemCount(form) < count) return tell(seller, "You do not have that many.");
offers.set(buyer.id, { seller: seller.id, form, count, caps });
tell(buyer, `${seller.nickname} offers ${count} of ${form.toString(16)} for ${caps} caps: /accept or /decline`);
}
function accept(buyer: Player): void {
const pending = offers.get(buyer.id);
const seller = pending && Player.getById(pending.seller);
offers.delete(buyer.id);
if (!pending || !seller) return tell(buyer, "Nobody has offered you anything.");
// Check both ends again: either may have spent, dropped or walked away since.
if (!near(buyer, seller) || seller.getItemCount(pending.form) < pending.count || buyer.getCaps() < pending.caps) {
tell(buyer, "The trade fell through.");
tell(seller, `The trade with ${buyer.nickname} fell through.`);
return;
}
seller.removeItem(pending.form, pending.count);
buyer.giveItem(pending.form, pending.count);
buyer.setCaps(buyer.getCaps() - pending.caps);
seller.setCaps(seller.getCaps() + pending.caps);
tell(buyer, "Done.");
tell(seller, "Done.");
}
Events.on("playerCommand", (player: Player, command: string, args: string[]) => {
if (command === "offer") offer(player, args);
else if (command === "accept") accept(player);
else if (command === "decline" && offers.delete(player.id)) tell(player, "Offer declined.");
});
Events.on("playerDisconnect", (player: Player) => {
offers.delete(player.id);
});

The whole design rests on the second check in accept. An offer is a promise made in the past. By the time the buyer types /accept, the seller may have sold the same stimpaks to someone else, and the buyer may have spent their caps. Validate at the moment of the transfer, not the moment of the offer.

Your own writes (removeItem, giveItem, setCaps) never raise inventoryChange, so the shop rules in step 5 do not see this trade, and an audit log built on inventoryChange will not either. Log it here if you need it.

With his greeting blocked, the game’s own prompt over the vendor still reads as a conversation. A small browser view next to the crosshair fixes that. The page is two spans:

ui/hint.html (body)
<div id="hint"><span id="key"></span><span id="text"></span></div>

Its script reads its first state from the address, so it is right before the client can reach it:

// ui/hint.js, running in the page.
const query = new URLSearchParams(location.search);
document.getElementById("key").textContent = query.get("key") || "";
document.getElementById("text").textContent = query.get("text") || "";

The client opens the view when the vendor comes under the crosshair, and closes it when he leaves. crosshairChange hands you the network ID of the body under the crosshair, the same ID the server knows him by:

src/client/hint.ts
// client
let vendorEntity = 0;
let hintView = 0;
Events.on("trade:vendor", (payload: unknown) => {
vendorEntity = typeof payload === "number" ? payload : 0;
});
Events.on("crosshairChange", (_ref: number, _previous: number, entity: number | null) => {
const aimedAtVendor = vendorEntity !== 0 && entity === vendorEntity;
if (aimedAtVendor && hintView === 0) {
// Key.getLabel follows the player's keyboard layout.
const key = encodeURIComponent(Key.getLabel("E"));
const text = encodeURIComponent("Trade with the vendor");
hintView = Web.createView(`fw://resources/trading-post/ui/hint.html?key=${key}&text=${text}`, {
zIndex: 6,
visible: true,
focus: false, // an overlay: the player keeps control
});
} else if (!aimedAtVendor && hintView !== 0) {
Web.destroyView(hintView);
hintView = 0;
}
});

With no size, a view covers the whole screen and the page positions its content itself. Add ui/** to files in the manifest so players download it.

  1. Build and load:

    Server console
    refresh
    ensure trading-post
  2. /tp sanctuary and walk to the bridge. A green ring and a “Shop” label mark the counter, and your HUD says who trades there as you step in.

  3. Look at the Shopkeeper: the hint appears beside the crosshair. Press Activate.

  4. Take a stimpak with fewer than 40 caps. It snaps back into the suitcase.

  5. /caps 500 (from the default gamemode) and take three. You are charged 120.

  6. Close and reopen: the stock is down by three.

  7. With a second player, /offer <them> 23736 1 30 and /accept on their side.

  • Several shops. Key stock and shoppers by container, and give each vendor his own.
  • Prices that move. Raise price a little on every purchase and let it decay on a timer.
  • Persistence. The stock lives in memory and resets on reload. Save the map with the approach in Save characters and the world.