// ==UserScript==
// @name Torn Trade Basket
// @namespace laurence.torn
// @version 0.7.1
// @description Pick items on the Items page into a basket, sum market (TornTools) and TornExchange trader buy prices per line and in total, compare with what you receive.
// @match https://www.torn.com/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @connect tornexchange.com
// @connect www.tornexchange.com
// @connect api.torn.com
// @run-at document-idle
// @updateURL https://raw.githubusercontent.com/LaurenceBont/torn-userscripts/main/torn-trade-basket.user.js
// @downloadURL https://raw.githubusercontent.com/LaurenceBont/torn-userscripts/main/torn-trade-basket.user.js
// ==/UserScript==
(function () {
'use strict';
const VERSION = '0.7.1'; // keep in sync with @version
const RAW_URL = 'https://raw.githubusercontent.com/LaurenceBont/torn-userscripts/main/torn-trade-basket.user.js';
const LIVE_SHA = typeof TTB_LOADER_SHA !== 'undefined' ? TTB_LOADER_SHA : '';
// Storage contract: these keys and the basket entry shape stay the same across versions, so updates keep
// your basket. New fields must be optional (old entries without them still work); only Clear empties it.
const KEY = 'ttb_basket_v1';
const KEY_RECV = 'ttb_received_v1';
const KEY_OPEN = 'ttb_open_v1';
const KEY_TRADER = 'ttb_te_trader_v1';
const KEY_TE = 'ttb_te_list_v1';
const TE_STALE_MS = 30 * 60 * 1000;
// ---------- hand-over between the normal script and the live loader ----------
// Each Tampermonkey script has its own storage. The normal script leaves a copy of its data in
// torn.com localStorage; the loader version imports it once while its own storage is still empty.
const HANDOVER = 'ttb_handover_v1';
const ALL_KEYS = [KEY, KEY_RECV, KEY_OPEN, KEY_TRADER, KEY_TE, 'ttb_te_on_v1'];
const viaLoader = typeof TTB_LOADER !== 'undefined';
try {
if (viaLoader) {
const raw = localStorage.getItem(HANDOVER);
if (raw && GM_getValue(KEY, null) === null) {
const data = JSON.parse(raw);
ALL_KEYS.forEach((k) => { if (k in data && data[k] !== null) GM_setValue(k, data[k]); });
localStorage.removeItem(HANDOVER);
}
} else if (GM_getValue(KEY, null) !== null) {
const data = {};
ALL_KEYS.forEach((k) => { data[k] = GM_getValue(k, null); });
localStorage.setItem(HANDOVER, JSON.stringify(data));
}
} catch (e) { /* storage blocked, start fresh */ }
let basket = GM_getValue(KEY, {}); // id -> { id, itemId, name, price, maxQty, qty }
let received = GM_getValue(KEY_RECV, 0);
let open = GM_getValue(KEY_OPEN, true);
let trader = GM_getValue(KEY_TRADER, '04doolant');
let te = GM_getValue(KEY_TE, null); // { trader, ts, byId: {id: price}, byName: {name: price} }
let teOn = GM_getValue('ttb_te_on_v1', false); // master switch: no TornExchange requests at all while off
let apiKey = GM_getValue('ttb_api_key_v1', ''); // optional Torn API key (Public) for online status
let teStatus = '';
let bestResult = null; // last "Find best traders" run (session only)
const fmt = (n) => '$' + Math.round(n || 0).toLocaleString('en-US');
const toInt = (s) => parseInt(String(s || '').replace(/[^\d]/g, ''), 10) || 0;
const norm = (s) => String(s || '').trim().toLowerCase().replace(/\s+/g, ' ');
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const save = () => {
GM_setValue(KEY, basket);
GM_setValue(KEY_RECV, received);
GM_setValue(KEY_OPEN, open);
GM_setValue(KEY_TRADER, trader);
GM_setValue(KEY_TE, te);
GM_setValue('ttb_te_on_v1', teOn);
};
// ---------- which pages the script acts on ----------
// The install matches all of torn.com so new pages never need a reinstall; this list decides where it runs.
const PAGES = ['/item.php', '/trade.php', '/profiles.php'];
if (!PAGES.includes(location.pathname)) return;
// ---------- profile page: read username, load their TE list ----------
if (location.pathname.startsWith('/profiles.php')) {
if (teOn) profileMode(); // only look up the profile owner when the TE switch in the basket is on
return;
}
function profileName() {
const t = document.title.match(/^\s*(.+?)\s*\[\d+\]/);
if (t) return t[1];
const h = document.querySelector('#skip-to-content, .content-title h4');
const m = h && h.textContent.trim().match(/^(.+?)'s\s+Profile/i);
return m ? m[1] : null;
}
function profileMode() {
const toast = document.createElement('div');
toast.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:99999;background:#222;color:#ddd;'
+ 'border:1px solid #444;border-radius:6px;padding:8px 10px;font:12px Arial,sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.5)';
const show = (html) => { toast.innerHTML = html; if (!toast.isConnected) document.body.appendChild(toast); };
let tries = 0;
const timer = setInterval(() => {
const name = profileName();
if (!name && ++tries < 20) return;
clearInterval(timer);
if (!name) return;
show(`TE: checking ${esc(name)}…`);
loadTE(name,
(list) => {
trader = name; te = list; save();
show(`TE: ${esc(name)} loaded (${Object.keys(list.byName).length} items), now used in your basket`);
setTimeout(() => toast.remove(), 6000);
},
(msg) => {
show(`${esc(msg)}
Basket keeps using ${esc(trader)}`);
setTimeout(() => toast.remove(), 4000);
});
}, 500);
}
// ---------- reading a Torn item row ----------
function rowId(li) {
return li.dataset.armoryid || li.dataset.item || rowName(li);
}
function rowName(li) {
const el = li.querySelector('.name-wrap .name, .name');
return (el ? el.textContent : li.dataset.sort || 'Unknown').trim();
}
function rowQty(li) {
if (li.dataset.qty) return toInt(li.dataset.qty) || 1;
const wrap = li.querySelector('.name-wrap');
const m = (wrap ? wrap.textContent : '').match(/x\s*([\d,]+)/i);
return m ? toInt(m[1]) : 1;
}
function rowPrice(li) {
// TornTools injects ".tt-item-price" like "$480 | 400x = $192,000"; first $ value is the unit price
const tt = li.querySelector('.tt-item-price');
const src = tt ? tt.textContent : textWithoutOurUi(li);
const m = src.match(/\$\s*([\d,]+)/);
return m ? toInt(m[1]) : 0;
}
function textWithoutOurUi(li) {
const clone = li.cloneNode(true);
clone.querySelectorAll('.ttb-add').forEach((b) => b.remove());
return clone.textContent || '';
}
// ---------- TornExchange price list ----------
function fetchTE() {
teStatus = 'Loading ' + trader + '…';
render();
loadTE(trader,
(list) => { te = list; teStatus = ''; save(); render(); },
(msg) => { teStatus = msg; render(); });
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const itemIdFromImg = (img) => ((img && img.getAttribute('src')) || '').match(/\/items\/(\d+)\//)?.[1] || null;
function gmGet(url) {
return new Promise((resolve, reject) => GM_xmlhttpRequest({
method: 'GET', url,
onload: (res) => resolve(res),
onerror: () => reject(new Error('TE request failed')),
}));
}
// Fetch and parse one trader's list; cached in memory for TE_STALE_MS
const listCache = {};
async function loadTEp(name) {
const hit = listCache[norm(name)];
if (hit && Date.now() - hit.ts < TE_STALE_MS) return hit;
const res = await gmGet(`https://www.tornexchange.com/prices/${encodeURIComponent(name)}/`);
if (res.status === 404) throw new Error(`No TE list for ${name}`);
if (res.status !== 200) throw new Error(`TE error ${res.status}`);
const doc = new DOMParser().parseFromString(res.responseText, 'text/html');
const byId = {};
const byName = {};
doc.querySelectorAll('tr.item').forEach((tr) => {
const itemName = tr.querySelector('.item-name')?.textContent.trim();
const cells = tr.querySelectorAll('td');
const price = toInt(cells[cells.length - 1]?.textContent);
if (!itemName || !price) return;
byName[norm(itemName)] = price;
const id = itemIdFromImg(tr.querySelector('img'));
if (id) byId[id] = price;
});
if (!Object.keys(byName).length) throw new Error(`No TE list for ${name}`);
const text = doc.body ? doc.body.textContent : '';
const list = {
trader: name, ts: Date.now(), byId, byName,
rating: parseInt(doc.querySelector('#vote-score')?.textContent.trim(), 10),
xid: (doc.querySelector('a[href*="profiles.php?XID="]')?.getAttribute('href') || '').match(/XID=(\d+)/)?.[1] || null,
lastTrade: text.match(/Last trade made by this trader:\s*([^\n]+?)\s*(\n|$)/)?.[1] || null,
};
listCache[norm(name)] = list;
return list;
}
function loadTE(name, ok, fail) {
loadTEp(name).then(ok, (e) => fail(e.message));
}
function priceIn(list, b) {
if (!list) return null;
if (b.itemId && list.byId[b.itemId] != null) return list.byId[b.itemId];
const p = list.byName[norm(b.name)];
return p != null ? p : null;
}
function tePrice(b) {
return teOn ? priceIn(te, b) : null;
}
// ---------- best trader search ----------
// Top-paying traders for one item from /listings, sorted by price high to low
async function topTradersFor(b, want) {
const found = [];
for (let page = 1; page <= 2 && found.length < want; page++) {
const url = 'https://www.tornexchange.com/listings?model_name_contains='
+ encodeURIComponent(b.name).replace(/%20/g, '+') + '&order_by=-effective_price&status=&page=' + page;
const res = await gmGet(url);
if (res.status !== 200) break;
const doc = new DOMParser().parseFromString(res.responseText, 'text/html');
const cards = doc.querySelectorAll('.listing-card');
if (!cards.length) break;
cards.forEach((card) => {
if (found.length >= want) return;
const img = card.querySelector('.card-text img');
const sameItem = b.itemId ? itemIdFromImg(img) === String(b.itemId) : norm(img?.getAttribute('alt')) === norm(b.name);
if (!sameItem) return;
const m = (card.querySelector('a[href*="/prices/"]')?.getAttribute('href') || '').match(/\/prices\/([^/]+)\//);
if (!m) return;
const name = decodeURIComponent(m[1]);
if (found.some((f) => f.name === name)) return;
const dot = card.querySelector('.listing-player i.fa-circle')?.className || '';
found.push({
name,
xid: (card.querySelector('.listing-player a[href*="XID="]')?.getAttribute('href') || '').match(/XID=(\d+)/)?.[1] || null,
rating: parseInt(card.querySelector('.listing-player .text-end')?.textContent.trim(), 10) || 0,
status: /text-success/.test(dot) ? 'on' : /text-warning/.test(dot) ? 'idle' : 'off',
});
});
await sleep(400);
}
return found;
}
async function findBest() {
const items = Object.values(basket).filter((b) => b.qty > 0);
if (!items.length) return;
const market = items.reduce((s, b) => s + b.price * b.qty, 0);
// anchors: biggest lines until ~80% of market value, max 5
const sorted = [...items].sort((a, b) => b.price * b.qty - a.price * a.qty);
const anchors = [];
let cum = 0;
for (const b of sorted) {
if (anchors.length >= 5 || (market && cum >= 0.8 * market)) break;
anchors.push(b);
cum += b.price * b.qty;
}
try {
const traders = new Map(); // name -> meta
for (let i = 0; i < anchors.length; i++) {
teStatus = `Searching top traders ${i + 1}/${anchors.length}: ${anchors[i].name}…`;
render();
(await topTradersFor(anchors[i], 5)).forEach((t) => { if (!traders.has(t.name)) traders.set(t.name, t); });
}
const scored = await scoreTraders(items, market, traders);
bestResult = { ...scored, title: `Best traders for: ${anchors.map((a) => a.name).join(', ')}` };
teStatus = scored.rows.length ? '' : 'No traders found for the top items';
} catch (e) {
teStatus = e.message;
}
render();
}
// Price the whole basket against each trader's list; also best split, average and median
async function scoreTraders(items, market, traders) {
const rows = [];
const lists = [];
let n = 0;
for (const [name, meta] of traders) {
teStatus = `Loading price lists ${++n}/${traders.size}…`;
render();
try {
const list = await loadTEp(name);
lists.push(list);
let total = 0, lines = 0, covValue = 0;
items.forEach((b) => {
const p = priceIn(list, b);
if (p == null) return;
total += p * b.qty; lines++; covValue += b.price * b.qty;
});
rows.push({
...meta, total, lines,
rating: Number.isFinite(list.rating) ? list.rating : meta.rating,
xid: list.xid || meta.xid || null,
lastTrade: list.lastTrade,
covPct: market ? (covValue / market) * 100 : 0,
payPct: covValue ? (total / covValue) * 100 : 0, // what they pay vs market, on the lines they buy
});
} catch (e) { /* trader without readable list, skip */ }
await sleep(400);
}
// best split: each line to whichever trader pays most for it
let split = 0, splitLines = 0;
items.forEach((b) => {
let best = null;
lists.forEach((l) => { const p = priceIn(l, b); if (p != null && (best == null || p > best)) best = p; });
if (best != null) { split += best * b.qty; splitLines++; }
});
rows.sort((a, b) => b.total - a.total);
await addTornStatus(rows.slice(0, 8));
const totals = rows.map((r) => r.total);
const avg = totals.length ? totals.reduce((s, v) => s + v, 0) / totals.length : 0;
const mid = [...totals].sort((a, b) => a - b);
const median = mid.length ? (mid.length % 2 ? mid[(mid.length - 1) / 2] : (mid[mid.length / 2 - 1] + mid[mid.length / 2]) / 2) : 0;
return { ts: Date.now(), rows, split, splitLines, avg, median, lineCount: items.length };
}
// Online status + last action from the Torn API (only with your own key set; Public access is enough)
async function addTornStatus(rows) {
if (!apiKey) return;
for (const r of rows) {
if (!r.xid) continue;
teStatus = `Checking who is online… ${r.name}`;
render();
try {
const res = await gmGet(`https://api.torn.com/user/${r.xid}?selections=profile&key=${encodeURIComponent(apiKey)}&comment=TradeBasket`);
const j = JSON.parse(res.responseText || '{}');
if (j.error) { teStatus = `Torn API: ${j.error.error}`; break; }
const st = j.last_action?.status;
if (st) r.status = st === 'Online' ? 'on' : st === 'Idle' ? 'idle' : 'off';
r.seen = j.last_action?.relative || null;
} catch (e) { /* skip this one */ }
await sleep(150);
}
}
// "8 minutes ago" -> "8m"
function shortAgo(s) {
if (!s) return '';
if (/second|now/i.test(s)) return 'now';
const m = s.match(/(\d+)\s*(minute|hour|day|week|month|year)/i);
return m ? m[1] + { minute: 'm', hour: 'h', day: 'd', week: 'w', month: 'mo', year: 'y' }[m[2].toLowerCase()] : s;
}
function profileUrl(t) {
return t.xid ? `https://www.torn.com/profiles.php?XID=${t.xid}` : `https://www.torn.com/profiles.php?NID=${encodeURIComponent(t.name)}`;
}
// Most active TE traders, in the order the TornExchange homepage lists them
async function activeTraders(limit) {
const res = await gmGet('https://www.tornexchange.com/');
if (res.status !== 200) throw new Error(`TE homepage error ${res.status}`);
const doc = new DOMParser().parseFromString(res.responseText, 'text/html');
const names = [];
doc.querySelectorAll('a[href*="/prices/"]').forEach((a) => {
const m = (a.getAttribute('href') || '').match(/\/prices\/([^/?#]+)\/?/);
if (!m) return;
const name = decodeURIComponent(m[1]);
if (name && !names.includes(name)) names.push(name);
});
return names.slice(0, limit);
}
async function checkTop() {
const items = Object.values(basket).filter((b) => b.qty > 0);
if (!items.length) return;
const market = items.reduce((s, b) => s + b.price * b.qty, 0);
try {
teStatus = 'Loading top TE traders…';
render();
const names = await activeTraders(20);
if (!names.length) throw new Error('No traders found on TE homepage');
const traders = new Map(names.map((name) => [name, { name }]));
const scored = await scoreTraders(items, market, traders);
bestResult = { ...scored, title: `Top ${names.length} most active TE traders` };
teStatus = scored.rows.length ? '' : 'Could not load any top trader lists';
} catch (e) {
teStatus = e.message;
}
render();
}
function useTrader(name) {
const list = listCache[norm(name)];
if (!list) return;
trader = name; te = list; save(); render();
}
function teAge() {
if (!te) return 'not loaded';
const min = Math.round((Date.now() - te.ts) / 60000);
return min < 60 ? `${min}m ago` : `${Math.round(min / 60)}h ago`;
}
// ---------- basket ops ----------
function toggle(li) {
const id = rowId(li);
if (basket[id]) {
delete basket[id];
} else {
const maxQty = rowQty(li);
basket[id] = { id, itemId: li.dataset.item || null, name: rowName(li), price: rowPrice(li), maxQty, qty: maxQty };
}
save();
syncButtons();
render();
}
function refreshPrices() {
document.querySelectorAll('ul.itemsList > li').forEach((li) => {
const b = basket[rowId(li)];
if (!b) return;
const p = rowPrice(li);
if (p) b.price = p;
b.itemId = b.itemId || li.dataset.item || null;
b.maxQty = rowQty(li);
b.qty = Math.min(b.qty, b.maxQty);
});
save();
if (teOn) fetchTE(); else render();
}
// ---------- row buttons ----------
function decorate(li) {
if (!li.querySelector('.name-wrap, .name')) return;
let btn = li.querySelector('.ttb-add');
if (!btn) {
li.dataset.ttb = '1';
btn = document.createElement('button');
btn.className = 'ttb-add';
btn.type = 'button';
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
toggle(li);
});
setBtn(btn, !!basket[rowId(li)]);
}
place(li, btn);
}
// Put the button right after the TornTools price; TornTools injects it later, so re-check on every scan
function place(li, btn) {
const price = li.querySelector('.tt-item-price');
if (price) {
if (price.nextSibling !== btn) price.after(btn);
btn.classList.add('ttb-by-price');
} else if (!btn.isConnected) {
(li.querySelector('.name-wrap') || li.querySelector('.name').parentElement).prepend(btn);
}
}
function setBtn(btn, inBasket) {
btn.textContent = inBasket ? '✓' : '+';
btn.classList.toggle('ttb-in', inBasket);
btn.title = inBasket ? 'Remove from basket' : 'Add to basket';
}
function syncButtons() {
document.querySelectorAll('ul.itemsList > li[data-ttb]').forEach((li) => {
const btn = li.querySelector('.ttb-add');
if (btn) setBtn(btn, !!basket[rowId(li)]);
});
}
function scan() {
document.querySelectorAll('ul.itemsList > li').forEach(decorate);
if (onTradeAdd()) {
decorateTrade();
const n = tradeRows().length;
if (n !== lastTradeCount) { lastTradeCount = n; render(); } // refresh "x/y found" as rows load
}
}
let lastTradeCount = -1;
window.addEventListener('hashchange', () => { lastTradeCount = -1; render(); scan(); });
// ---------- trade page (trade.php#step=add): highlight basket items, fill their qty fields ----------
// Only fills the quantity inputs. It never clicks "Add to trade"; you review and confirm that yourself.
const onTradeAdd = () => location.pathname === '/trade.php' && /step=add/.test(location.hash);
const cleanName = (s) => norm(String(s || '').replace(/\s*x\s*[\d,]+\s*$/i, ''));
function tradeRows() {
const rows = [];
document.querySelectorAll('#trade-container li').forEach((li) => {
const nameEl = li.querySelector('.name');
if (!nameEl || li.querySelector('li')) return; // skip wrappers that contain other rows
const name = cleanName(nameEl.textContent);
const b = Object.values(basket).find((x) => cleanName(x.name) === name);
if (b) rows.push({ li, b, nameEl });
});
return rows;
}
function qtyInput(li) {
return li.querySelector('input[type="text"], input[type="number"], input:not([type])');
}
function setInput(input, value) {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
setter.call(input, String(value));
['input', 'keyup', 'change', 'blur'].forEach((type) => input.dispatchEvent(new Event(type, { bubbles: true })));
}
function fillRow(row, empty) {
const input = qtyInput(row.li);
if (input) { setInput(input, empty ? '' : row.b.qty); return true; }
const box = row.li.querySelector('input[type="checkbox"]'); // weapons/armor: single item checkbox
if (box && box.checked === !!empty) { box.click(); return true; }
return false;
}
function decorateTrade() {
tradeRows().forEach((row) => {
row.li.classList.add('ttb-trade-hit');
const tradable = qtyInput(row.li) || row.li.querySelector('input[type="checkbox"]');
let btn = row.li.querySelector('.ttb-fill');
if (!btn) {
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ttb-fill';
btn.addEventListener('click', (e) => {
e.preventDefault(); e.stopPropagation();
const r = tradeRows().find((x) => x.li === row.li); // re-read so the current basket qty is used
if (r) fillRow(r);
});
row.nameEl.after(btn);
}
const label = tradable ? `Fill ${row.b.qty}` : 'in basket';
if (btn.textContent !== label) btn.textContent = label;
btn.disabled = !tradable;
});
}
// ---------- panel ----------
const panel = document.createElement('div');
panel.id = 'ttb-panel';
document.body.appendChild(panel);
// Default sits above Torn's chat bar and its notification badges; drag the header to move it (position is remembered)
const KEY_POS = 'ttb_pos_v1';
function applyPos(pos) {
if (!pos) return;
const r = Math.max(0, Math.min(pos.right, window.innerWidth - 120));
const b = Math.max(0, Math.min(pos.bottom, window.innerHeight - 40));
panel.style.right = r + 'px';
panel.style.bottom = b + 'px';
panel.style.maxHeight = `calc(100vh - ${b + 20}px)`;
}
applyPos(GM_getValue(KEY_POS, null));
panel.addEventListener('mousedown', (e) => {
if (e.button !== 0 || !e.target.closest('.ttb-head') || e.target.closest('button, a, input')) return;
e.preventDefault();
const rect = panel.getBoundingClientRect();
const startX = e.clientX, startY = e.clientY;
const startR = window.innerWidth - rect.right, startB = window.innerHeight - rect.bottom;
let pos = null;
const move = (ev) => {
pos = { right: startR - (ev.clientX - startX), bottom: startB - (ev.clientY - startY) };
applyPos(pos);
};
const up = () => {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', up);
if (pos) GM_setValue(KEY_POS, pos);
};
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', up);
});
panel.addEventListener('dblclick', (e) => {
if (!e.target.closest('.ttb-head') || e.target.closest('button, a, input')) return;
GM_setValue(KEY_POS, null);
panel.style.right = panel.style.bottom = panel.style.maxHeight = ''; // back to default spot
});
function totals() {
let market = 0, teSum = 0, missing = 0;
Object.values(basket).forEach((b) => {
market += b.price * b.qty;
const p = tePrice(b);
if (p == null) missing++; else teSum += p * b.qty;
});
return { market, teSum, missing };
}
function diffHtml(a, base) {
if (!base) return '-';
const d = a - base;
return `${d >= 0 ? '+' : '-'}${fmt(Math.abs(d))} (${((a / base) * 100).toFixed(1)}%)`;
}
function bestHtml(market) {
const r = bestResult;
const pct = (v) => (market ? ((v / market) * 100).toFixed(1) + '%' : '-');
const stale = r.lineCount !== Object.keys(basket).length ? ' (basket changed, run again)' : '';
return `