Menu
Sign inDownload

Example: Where to buy

A real add-on on UEX data: the pack's own colours, a ready-made page, the game's location.

Our published Where to buy add-on, whole: search anything to buy, the closest place and the best price. Every bit of UEX's data comes from UEX data (depends and api.call); this add-on keeps what's its own: where the player is (from the game when its telemetry says, else a place they type), which seller is nearest, and its screens, drawn in the button pack's own colours so they read on any pack, a small tile that opens a panel and a big tile that is the panel, and a ready-made page.

manifest.json

{
 "author": "Comms Array",
 "name": "wheretobuy",
 "package": "commsarray_wheretobuy",
 "title": "Where to buy",
 "tier": "official",
 "api": 1,
 "api_version": "1.4",
 "games": [
  "starcitizen"
 ],
 "widgets": [
  "where_to_buy"
 ],
 "pad_js": "pad_wheretobuy.js",
 "depends": {
  "uex": ">=1.0"
 },
 "permissions": [
  "pad.widgets",
  "state.live",
  "uses.uex.status",
  "uses.uex.search",
  "uses.uex.offers",
  "uses.uex.places",
  "uses.uex.place_from_game",
  "uses.uex.distances"
 ],
 "pages": [
  {
   "title": "Where to buy",
   "desc": "Search anything: the closest place that sells it and the best price",
   "cols": 24,
   "widgets": [
    {
     "type": "where_to_buy",
     "label": "Where to buy",
     "x": 0,
     "y": 0,
     "w": 24,
     "h": 12
    }
   ]
  }
 ],
 "description": "Search anything you can buy: the closest place that sells it and the best price, with every place that has it. Prices from UEX. Uses the game's location when it gives one, else you pick where you are.",
 "version": "2.0.1"
}

commsarray_wheretobuy/__init__.py

"""Where to buy (a Comms Array add-on): search what you want, see the closest place that sells it and the best price.

Wiring only: the add-on is addon.WhereToBuy (pad requests, where you are, keeping UEX's data); UEX in uex.py, places in
places.py, search and the answers in finder.py; the pad widget in pad_wheretobuy.js.
"""
from .addon import WhereToBuy

__version__ = "2.0.1"
__all__ = ["WhereToBuy", "create"]


def create(api):
    return WhereToBuy(api)

commsarray_wheretobuy/addon.py

"""Where to buy (a Comms Array add-on): search what you want, see the closest place that sells it and the best price.

It never talks to UEX itself: everything comes from the UEX data add-on (`"depends": {"uex": ">=1.0"}`), which keeps
one cache, one request budget and one key for every add-on that uses UEX (operator, 30 Nov 2026). This add-on does
what's its own: where the player is, which seller is nearest, and its pad screens.

Where you are: from the game when its telemetry gives a location (its place names, matched by UEX data), else the place
the player picked; the pick list hides while the game says.

Pad requests (body "op"):
  status          -> {ready, loading, error, age_s, location: {source: "game" | "pick" | None, name, place}, places?}
  pick {place}    -> remember the player's place (a places id, "" to clear)
  search {q}      -> {results: [{key, kind, name, places, from, unit}]}
  where {key}     -> {name, unit, rows, closest, best} (finder.where)
"""
from __future__ import annotations

import json
import time
from pathlib import Path

from . import finder

PLACES_S = 10 * 60                      # ask UEX data for the places again this often (they change with patches)


class WhereToBuy:
    def __init__(self, api):
        self.api = api
        self.settings_file = Path(getattr(api, "data_dir", None) or ".") / "settings.json"
        self.pick = ""
        self.game_path: list[str] = []      # the game's location names, system first (empty: the game doesn't say)
        self.places: list[dict] = []
        self.places_at = 0.0
        self.matched: dict[tuple, dict | None] = {}     # a game path -> what UEX data matched it to
        try:
            self.pick = str(json.loads(self.settings_file.read_text(encoding="utf-8")).get("place") or "")
        except (OSError, ValueError, AttributeError):
            pass

    def _save(self):
        try:
            self.settings_file.parent.mkdir(parents=True, exist_ok=True)
            self.settings_file.write_text(json.dumps({"place": self.pick}), encoding="utf-8")
        except OSError:
            pass

    # ---- UEX data ----------------------------------------------------------------------------------------------
    async def _uex(self, fn: str, body: dict | None = None) -> tuple[dict | None, str]:
        """One call to UEX data: (its answer, "") or (None, why not)."""
        try:
            return await self.api.call("uex", fn, body or {}), ""
        except Exception as e:                  # noqa: BLE001 - AddonError (refused, not running, timed out) and friends
            b = getattr(e, "body", None) or {}
            if b.get("status") == "addon_not_running":
                return None, "UEX data isn't running: it comes with Where to buy (Add-ons tab)"
            return None, b.get("message") or b.get("status") or str(e) or "UEX data didn't answer"

    async def _places(self) -> list[dict]:
        if not self.places or time.time() - self.places_at > PLACES_S:
            r, _ = await self._uex("places")
            if r and isinstance(r.get("places"), list):
                self.places, self.places_at, self.matched = r["places"], time.time(), {}
        return self.places

    # ---- where you are ---------------------------------------------------------------------------------------
    def on_state(self, state: dict):
        """The game's location path, when its telemetry has one (Star Citizen 5.0.202+: player.location.path)."""
        loc = ((state or {}).get("player") or {}).get("location") or {}
        self.game_path = [str(p.get("name") or "") for p in loc.get("path") or [] if isinstance(p, dict)]

    async def anchor(self) -> tuple[dict | None, str | None]:
        """(where the player is, which source): the game first, else the pick."""
        if self.game_path:
            k = tuple(self.game_path)
            if k not in self.matched:
                r, err = await self._uex("place_from_game", {"path": self.game_path})
                if err:
                    return None, None
                self.matched[k] = (r or {}).get("anchor")
            if self.matched[k]:
                return self.matched[k], "game"
        p = next((x for x in await self._places() if x["id"] == self.pick), None) if self.pick else None
        if not p:
            return None, None
        return {"place": p["id"], "moon": p.get("moon_id"), "planet": p.get("planet_id"), "system": p.get("system_id"),
                "name": p["name"], "terminal": p.get("terminal")}, "pick"

    # ---- the pad ---------------------------------------------------------------------------------------------
    async def handle_pad(self, device: dict, body: dict):
        op = body.get("op")
        if op == "status":
            s, err = await self._uex("status")
            s = s or {}
            places = await self._places() if s.get("ready") else []
            a, source = await self.anchor() if s.get("ready") else (None, None)
            ready = bool(s.get("ready")) and bool(places)
            out = {"ready": ready, "loading": bool(s.get("loading")) or (not err and not ready and not s.get("error")),
                   "error": err or s.get("error") or "", "age_s": s.get("age_s"),
                   "location": {"source": source, "name": (a or {}).get("name"), "place": (a or {}).get("place")}}
            if source != "game":                 # the pick list only while the game doesn't say where you are
                out["places"] = [{"id": p["id"], "name": p["name"], "system": p["system"], "near": p["near"]} for p in places]
            return out, 200
        if op == "pick":
            place = str(body.get("place") or "")
            if place and not any(p["id"] == place for p in await self._places()):
                return {"status": "bad_place"}, 400
            self.pick = place
            self._save()
            return {"status": "ok"}, 200
        if op == "search":
            r, err = await self._uex("search", {"q": str(body.get("q") or "")[:60]})
            return ({"results": r.get("results") or []}, 200) if r else ({"results": [], "message": err}, 200)
        if op == "where":
            r, err = await self._uex("offers", {"key": str(body.get("key") or "")[:40]})
            if not r:
                return {"status": "unknown", "message": err}, 404
            a, _ = await self.anchor()
            ids = finder.to_measure(finder.rows_of(r, a), a)
            gm = {}
            if ids:                              # one call; UEX data keeps each distance a week
                d, _ = await self._uex("distances", {"origin": a["terminal"], "to": ids})
                gm = (d or {}).get("gm") or {}
            return finder.where(r, a, gm), 200
        return {"status": "bad_request"}, 400

commsarray_wheretobuy/finder.py

"""The closest place that sells it and the best price, from UEX data's offers.

Closest: the nearest group first (nearness.tier: here, this moon, this planet, this system, elsewhere), and within it
UEX's terminal-to-terminal distance for the 3 cheapest (one call to UEX data, which keeps them a week); otherwise the
cheapest of the group. Best price: the lowest anywhere.
"""
from __future__ import annotations

from . import nearness as N

MEASURE = 3                             # distances asked for at most, per lookup (easy on UEX)


def rows_of(answer: dict, anchor: dict | None) -> list[dict]:
    rows = []
    for o in answer.get("offers") or []:
        rows.append({"terminal": o.get("where") or "", "shop": o.get("shop") or "", "place": o.get("place") or "",
                     "near": o.get("near") or "", "system": o.get("system") or "", "price": float(o.get("price") or 0),
                     "updated": o.get("updated") or 0, "tier": N.tier(anchor, o), "gm": None, "_t": o.get("terminal")})
    return rows


def to_measure(rows: list[dict], anchor: dict | None) -> list[int]:
    """The terminals worth a distance: the cheapest few of the nearest group, when the player isn't at one of them."""
    if not rows or not anchor or not anchor.get("terminal"):
        return []
    near = min(r["tier"] for r in rows)
    if near == 0:
        return []
    return [r["_t"] for r in sorted((r for r in rows if r["tier"] == near), key=lambda r: r["price"])[:MEASURE]]


ELSEWHERE = "Elsewhere"


def by_system(rows: list[dict]) -> list[dict]:
    """The rows under a header per system, for the full list (a player's suggestion, operator 1 Dec 2026): [{system,
    rows: [row indexes]}]. Systems in the order they first come up (rows are nearest first when there's a location, so
    yours leads); each keeps its rows' order. A row with no system goes under "Elsewhere". Indexes, not copies: the
    answer stays the same size."""
    groups: dict[str, list[int]] = {}
    for i, r in enumerate(rows):
        groups.setdefault(r.get("system") or ELSEWHERE, []).append(i)
    return [{"system": k, "rows": v} for k, v in groups.items()]


def where(answer: dict, anchor: dict | None, gm: dict | None = None) -> dict:
    """{name, unit, rows (nearest first), systems (by_system), closest, best}. gm: {terminal id (str): gigameters}."""
    rows = rows_of(answer, anchor)
    name, unit = answer.get("name") or "", answer.get("unit") or "each"
    if not rows:
        return {"name": name, "unit": unit, "rows": [], "systems": [], "closest": None, "best": None}
    for r in rows:
        r["gm"] = (gm or {}).get(str(r["_t"]))
    best = min(rows, key=lambda r: (r["price"], r["tier"]))
    near = min(r["tier"] for r in rows)
    group = [r for r in rows if r["tier"] == near]
    closest = min(group, key=lambda r: (r["gm"] is None, r["gm"] or 0, r["price"])) if anchor else None
    rows.sort(key=lambda r: (r["tier"], r["gm"] is None, r["gm"] or 0, r["price"]))
    for r in rows:
        r["where"] = N.TIERS[r["tier"]] if anchor else ""
        r.pop("_t", None)
    return {"name": name, "unit": unit, "rows": rows, "systems": by_system(rows), "closest": closest, "best": best}

commsarray_wheretobuy/nearness.py

"""How near a seller is to the player: the nearest group first. The ids come from UEX data (its places and offers)."""
from __future__ import annotations

TIERS = ("Here", "On this moon", "Around this planet", "In this system", "Another system")


def tier(anchor: dict | None, offer: dict) -> int:
    """0 here, 1 same moon, 2 same planet (its moons and stations too), 3 same system, 4 elsewhere (or unknown)."""
    if not anchor:
        return 4
    if anchor.get("place") and offer.get("place_id") == anchor["place"]:
        return 0
    if anchor.get("moon") and offer.get("moon_id") == anchor["moon"]:
        return 1
    if anchor.get("planet") and offer.get("planet_id") == anchor["planet"]:
        return 2
    if anchor.get("system") and offer.get("system_id") == anchor["system"]:
        return 3
    return 4

commsarray_wheretobuy/pad_wheretobuy.js

// Where to buy (a Comms Array add-on): search what you want, see the closest place that sells it and the best price.
// Runs in its own sandboxed frame on the pad (window.CA). The frame has no network: it asks the add-on on the PC
// (CA.call), which has the UEX data. Where you are: the game's location when it gives one, else the place you pick
// (the pick list hides while the game says where you are).
(() => {
  const { esc } = CA;
  const call = (body) => CA.call(body);
  const money = (n) => Math.round(n).toLocaleString("en-US");
  const ago = (s) => (s == null ? "" : s < 3600 ? `${Math.max(1, Math.round(s / 60))} min ago` : s < 172800 ? `${Math.round(s / 3600)} h ago`
    : `${Math.round(s / 86400)} days ago`);
  const kindName = { item: "item", commodity: "commodity", ship: "ship" };

  // the whole search, drawn into `root` (the panel, or a big tile)
  function ui(root, inTile = false) {
    let status = null, q = "", results = [], picked = null, timer = 0, lastLoc = "", searches = 0;
    // Colours come from whatever this sits on: the pad's text colour, or the button pack's (its --text / --dim on
    // its own plate). Fields, buttons and cards are that text colour, faintly tinted, never a fixed dark box
    // (operator, 30 Nov 2026: dark boxes and unreadable placeholders on a light pack).
    root.innerHTML = `<style>
      .wtb { color: var(--text, #d6e2ee); display: flex; flex-direction: column; gap: 8px; min-width: 0; box-sizing: border-box; }
      .wtb.tile { position: absolute; inset: 0; padding: 12px 14px; }
      /* a big tile: the search pinned to the tile, its results scroll inside it (operator: "I can't get to the lower
         variations") */
      .wtb .wtb-out { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain;
        -webkit-overflow-scrolling: touch; touch-action: pan-y; padding-right: 2px; }
      .wtb .dim { color: var(--dim, #7d8fa3); }
      .wtb input, .wtb button, .wtb .card { font: inherit; color: inherit; border-radius: 8px;
        border: 1px solid color-mix(in srgb, currentColor 40%, transparent); background: color-mix(in srgb, currentColor 8%, transparent); }
      .wtb input { width: 100%; padding: 9px 10px; }
      .wtb input::placeholder { color: inherit; opacity: .65; }
      .wtb button { text-align: left; padding: 8px 10px; white-space: normal; cursor: pointer; }
      .wtb button.link { align-self: flex-start; padding: 4px 10px; }
      .wtb .card { padding: 8px 10px; }
      .wtb .row { border-top: 1px solid color-mix(in srgb, currentColor 25%, transparent); }
      .wtb .warn { color: var(--warn, #ffb547); }
    </style><div class="wtb${inTile ? " tile" : ""}">
      <div class="wtb-loc"></div>
      <input type="search" class="wtb-q" placeholder="What do you want to buy?" autocomplete="off">
      <div class="wtb-out" style="display:flex;flex-direction:column;gap:6px"></div>
      <div class="wtb-foot dim" style="font-size:11px"></div></div>`;
    const $ = (s) => root.querySelector(s);

    // where you are: the game's place, else the one you picked, else type it (any device: a tablet has no dropdown search)
    let changing = false;
    const words = (s) => String(s || "").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
    const drawLoc = () => {
      const box = $(".wtb-loc"), l = status?.location || {};
      if (l.source === "game") {
        box.innerHTML = `<div style="font-size:13px">You're at <b>${esc(l.name || "")}</b> <span class="dim">(from the game)</span></div>`;
        return;
      }
      const cur = (status?.places || []).find((p) => p.id === l.place);
      if (cur && !changing) {
        box.innerHTML = `<div style="display:flex;gap:8px;align-items:center;font-size:13px;flex-wrap:wrap">You're at
          <b>${esc(cur.name)}</b> <span class="dim">${esc([cur.near, cur.system].filter(Boolean).join(", "))}</span>
          <button class="link wtb-change">Change</button></div>`;
        $(".wtb-change").onclick = () => { changing = true; drawLoc(); $(".wtb-where")?.focus(); };
        return;
      }
      box.innerHTML = `<input type="search" class="wtb-where" placeholder="Where are you? Type a station, city or outpost" autocomplete="off">
        <div class="wtb-places" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px"></div>`;
      const input = $(".wtb-where"), list = $(".wtb-places");
      const match = () => {
        const want = words(input.value);
        const hits = !want.length ? [] : (status?.places || []).filter((p) => {
          const have = words(`${p.name} ${p.near} ${p.system}`);
          return want.every((w) => have.some((h) => h.startsWith(w)));
        }).slice(0, 8);
        list.innerHTML = hits.map((p) => `<button data-p="${esc(p.id)}"><b>${esc(p.name)}</b> <span class="dim" style="font-size:12px">${esc([p.near, p.system].filter(Boolean).join(", "))}</span></button>`).join("")
          || (want.length ? `<span class="dim" style="font-size:12px">No place by that name.</span>` : "");
        list.querySelectorAll("[data-p]").forEach((b) => b.onclick = async () => {
          changing = false;
          await call({ op: "pick", place: b.dataset.p }); await refresh(); if (picked) show(picked);
        });
      };
      input.addEventListener("input", match);
    };
    const drawFoot = () => {
      // the data, its age and the key are the UEX data add-on's (its own tile): this only says how things stand
      $(".wtb-foot").textContent = status?.error && !status?.ready ? `UEX data: ${status.error}`
        : status?.loading ? "UEX data is getting prices from UEX…" : `Prices: UEX, through UEX data${status?.age_s != null ? ", updated " + ago(status.age_s) : ""}`
          + (status?.error && status?.ready ? ` (couldn't refresh: ${status.error})` : "")
          + (/limit/i.test(status?.error || "") ? ". Add your UEX key in UEX data's tile." : "");
    };
    const refresh = async () => {
      const s = await call({ op: "status" });
      if (s.status === "offline") { $(".wtb-foot").textContent = s.message || "Comms Array isn't answering"; return; }
      status = s; lastLoc = JSON.stringify(s.location || {}); drawLoc(); drawFoot();
      // not ready yet (still loading, or UEX failed and the PC retries): look again (this asks the PC, not UEX)
      if (!s.ready) setTimeout(refresh, s.loading ? 3000 : 30000);
    };
    const drawResults = () => {
      $(".wtb-out").innerHTML = results.length ? results.map((r, i) => `<button data-i="${i}">
          <b>${esc(r.name)}</b><br><span class="dim" style="font-size:12px">${esc(kindName[r.kind] || r.kind)} · ${r.places} place${r.places === 1 ? "" : "s"} · from ${money(r.from)} aUEC ${esc(r.unit === "each" ? "" : r.unit)}</span></button>`).join("")
        : q ? `<div class="dim" style="font-size:13px">Nothing by that name sells anywhere UEX knows.</div>` : "";
      root.querySelectorAll(".wtb-out [data-i]").forEach((b) => b.onclick = () => show(results[Number(b.dataset.i)]));
    };
    const card = (title, r, unit, note) => !r ? "" : `<div class="card">
      <div class="dim" style="font-size:11px;letter-spacing:.1em;text-transform:uppercase">${title}</div>
      <b>${esc(r.place)}</b>${r.shop && r.shop !== r.place ? ` <span style="font-size:12px">· ${esc(r.shop)}</span>` : ""}
      <div class="dim" style="font-size:12px">${esc([r.near, r.system].filter(Boolean).join(", "))}${note ? " · " + esc(note) : ""}</div>
      <div style="font-size:16px;font-weight:700">${money(r.price)} aUEC <span style="font-size:12px;font-weight:400">${esc(unit === "each" ? "" : unit)}</span></div></div>`;
    const where = (r) => [r.where, r.gm != null ? `${r.gm.toFixed(1)} Gm` : ""].filter(Boolean).join(", ");
    // the full list under a header per system (Stanton, Pyro, Nyx...): the PC groups them (finder.by_system), this draws
    const bySystem = (w) => (w.systems || []).map((g) => [g.system, g.rows.map((i) => w.rows[i]).filter(Boolean)]);
    const placeRow = (x) => `<div class="row" style="display:flex;justify-content:space-between;gap:8px;font-size:12px;padding:4px 0">
            <span style="min-width:0">${esc(x.place)}<br><span class="dim">${esc([x.near, where(x)].filter(Boolean).join(" · "))}</span></span>
            <b style="white-space:nowrap">${money(x.price)}</b></div>`;
    let lookup = 0;                            // only the latest lookup draws (Codex, keys PR 26)
    async function show(r) {
      picked = r; const mine = ++lookup;
      $(".wtb-out").innerHTML = `<div class="dim" style="font-size:13px">Finding ${esc(r.name)}…</div>`;
      const w = await call({ op: "where", key: r.key });
      if (picked !== r || mine !== lookup) return;
      if (!w.rows) { $(".wtb-out").textContent = w.message || "Couldn't look that up."; return; }
      if (!w.rows.length) {                    // nowhere open sells it right now (Codex, keys PR 26)
        $(".wtb-out").innerHTML = `<button class="link wtb-back">‹ Results</button><div class="dim" style="font-size:13px">No open shop sells ${esc(w.name)} right now.</div>`;
        $(".wtb-back").onclick = () => { picked = null; drawResults(); };
        return;
      }
      const noLoc = !status?.location?.source;
      $(".wtb-out").innerHTML = `<button class="link wtb-back">‹ Results</button>
        <div><b style="font-size:15px">${esc(w.name)}</b></div>
        ${noLoc ? `<div class="warn" style="font-size:12px">Type where you are to see the closest.</div>` : card("Closest", w.closest, w.unit, w.closest && where(w.closest))}
        ${card("Best price", w.best, w.unit, where(w.best))}
        <details><summary style="cursor:pointer;font-size:13px">All ${w.rows.length} place${w.rows.length === 1 ? "" : "s"}</summary>
          ${bySystem(w).map(([sys, xs]) => `<div class="wtb-sys" style="font-size:11px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;margin-top:10px;padding-bottom:3px;border-bottom:1px solid var(--line, rgba(127,127,127,.35))">${esc(sys)} <span class="dim" style="font-weight:400">· ${xs.length}</span></div>`
            + xs.map(placeRow).join("")).join("")}</details>`;
      $(".wtb-back").onclick = () => { picked = null; drawResults(); };
    }
    $(".wtb-q").addEventListener("input", (e) => {
      clearTimeout(timer);
      timer = setTimeout(async () => {
        q = e.target.value.trim(); picked = null;
        const mine = ++searches;               // only the latest search draws (Codex, keys PR 26)
        const got = q.length < 2 ? [] : (await call({ op: "search", q })).results || [];
        if (mine !== searches) return;
        results = got;
        drawResults();
      }, 200);
    });
    // the game's location changed (or appeared): ask again, so the pick list hides or shows
    CA.onState(() => {
      const v = CA.value("location");
      const now = v && v.v != null ? String(v.t) : "";
      if (now !== root.dataset.gameLoc) {
        // compare against the location before this refresh (refresh() moves lastLoc on): Codex, keys PR 26
        root.dataset.gameLoc = now; const before = lastLoc;
        refresh().then(() => { if (picked && lastLoc !== before) show(picked); });
      }
    });
    refresh();
  }

  CA.widget("where_to_buy", {
    add: { label: "Where to buy", desc: "Search anything to buy: the closest place that sells it and the best price (prices from UEX)",
           size: [4, 2], props: () => ({ label: "Where to buy" }) },
    settings: [
      { type: "panel", panel: "search", label: "Open the search…",
        help: "A small tile opens the search; a big one (8 wide, 6 tall or more) shows it right on the page." },
      { key: "label", type: "text", label: "Label", max: 40 },
    ],
    tile(root, w, { editing }) {
      if (w.w >= 8 && w.h >= 6 && !editing) { ui(root, true); return; }
      root.innerHTML = `<div class="w b c-blue"><span>${esc(w.label || "Where to buy")}</span></div>`;
      if (!editing) root.firstChild.addEventListener("click", () => CA.openPanel("search"));
    },
    panels: { search: () => CA.sheet(`<h3><span>Where to buy</span></h3><div class="wtb-root"></div>`, (r) => ui(r.querySelector(".wtb-root"))) },
  });
})();
From the Comms Array source, commsarray-agent d615c4d.