To improve the extension and make it more efficient, we can indeed use the Skinport WebSocket API, which provides real-time updates on item listings.
Here's an updated version of the code that uses the WebSocket API with Socket.IO and msgpack-parser:
────────────────────────────────────────
Install required libraries
────────────────────────────────────────
We'll need socket.io-client and msgpack-parser. You can include them in your project using npm or yarn:
bash Copy code
npm install socket.io-client msgpack-parser
Or, if you prefer to include them directly in your HTML, you can use a CDN like unpkg:
html Copy code
<script src="https://unpkg.com/socket.io-client@4/dist/socket.io.js"></script>
<script src="https://unpkg.com/msgpack-parser@1/dist/msgpack-parser.min.js"></script>
────────────────────────────────────────
2. Update background.js to use WebSocket API
────────────────────────────────────────
javascript Copy code
// === CONSTANTS =======================================================
const BUFF_URL = 'https://prices.csgotrader.app/latest/buff163.json';
const SCAN_INTERVAL_MIN = 60; // refresh Buff cache every hour
const APP_ID = 730; // CS:GO
const SKINPORT_WS_URL = 'wss://skinport.com/socket.io/?EIO=4&transport=websocket';
//---------------------------------------------------------------------
let buffCache = {}; // will hold Buff163 prices
let userConfig = { // default user settings
minPrice: 0,
maxPrice: 500,
discount: 15, // % cheaper than Buff
currency: 'EUR',
running: false
};
let socket; // Skinport WebSocket connection
// ------- (1) LOAD SETTINGS WHEN EXTENSION INSTALLED -----------------
chrome.runtime.onInstalled.addListener(async () => {
const saved = await chrome.storage.sync.get(['config']);
if (saved.config) userConfig = saved.config;
// keep loop alive
chrome.alarms.create('buff-refresh', { periodInMinutes: SCAN_INTERVAL_MIN });
});
// ------- (2) LISTEN FOR UI MESSAGES (popup) -------------------------
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.type === 'updateConfig') {
userConfig = { ...userConfig, ...msg.payload };
chrome.storage.sync.set({ config: userConfig });
sendResponse({ ok: true });
if (userConfig.running) {
initWebSocket();
} else {
if (socket) socket.disconnect();
}
} else if (msg.type === 'toggleRunning') {
userConfig.running = msg.payload;
chrome.storage.sync.set({ config: userConfig });
sendResponse({ ok: true });
if (userConfig.running) {
initWebSocket();
} else {
if (socket) socket.disconnect();
}
}
});
// ------- (3) REFRESH BUFF CACHE PERIODICALLY ------------------------
chrome.alarms.onAlarm.addListener(alarm => {
if (alarm.name === 'buff-refresh') refreshBuffCache();
});
async function refreshBuffCache() {
try {
buffCache = await fetch(BUFF_URL).then(r => r.json());
} catch (err) {
console.error('Error refreshing Buff cache:', err);
}
}
// ------- (4) INIT WEBSOCKET CONNECTION -------------------------------
function initWebSocket() {
if (socket) socket.disconnect();
socket = io(SKINPORT_WS_URL, {
transports: ['websocket'],
parser: msgpackParser,
reconnection: true,
reconnectionAttempts: Infinity,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
});
socket.on('connect', () => {
console.log('Connected to Skinport WebSocket');
socket.emit('join', { room: `app_${APP_ID}` });
});
socket.on('itemlist', data => {
if (!data || !data.items) return;
const items = data.items.filter(item => item.currency === userConfig.currency);
const deals = findGoodDeals(items);
if (deals.length) {
deals.forEach(deal => {
const bought = tryAutoBuy(deal);
pushNotification(deal, bought);
});
}
});
socket.on('disconnect', () => {
console.log('Disconnected from Skinport WebSocket');
});
socket.on('error', err => {
console.error('WebSocket error:', err);
});
}
// ------- (5) FIND GOOD DEALS ----------------------------------------
function findGoodDeals(items) {
const res = [];
items.forEach(it => {
const buff = buffCache[it.market_hash_name];
if (!buff || !buff.sell_min_price) return;
const buffPrice = Number(buff.sell_min_price);
const diffPct = (buffPrice - it.price) / buffPrice * 100;
if (it.price >= userConfig.minPrice && it.price <= userConfig.maxPrice && diffPct >= userConfig.discount) {
res.push({ ...it, buffPrice, diffPct: diffPct.toFixed(2) });
}
});
return res;
}
// ------- (6) TRY AUTO-BUY -------------------------------------------
async function tryAutoBuy(item) {
const { apiKey, autoBuy } = await chrome.storage.local.get(['apiKey', 'autoBuy']);
if (!apiKey || !autoBuy) return false;
const url = `https://api.skinport.com/v1/items/${item.item_id}/buy`;
const body = JSON.stringify({ price: item.price });
const resp = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body
});
return resp.ok;
}
// ------- (7) PUSH NOTIFICATION ---------------------------------------
function pushNotification(item, bought) {
chrome.notifications.create('', {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: bought ? '✅ BOUGHT!' : '💰 Deal found!',
message:
`${item.market_hash_name}\n` +
`Skinport: ${item.price} ${userConfig.currency}\n` +
`Buff163: ${item.buffPrice} ${userConfig.currency}\n` +
`Discount: ${item.diffPct}%`
});
}
────────────────────────────────────────
8. msgpackParser implementation
────────────────────────────────────────
Create a new file msgpackParser.js with the following content:
javascript Copy code
import { encode, decode } from 'msgpack-parser';
const msgpackParser = {
packet: {
type: 'Buffer',
data: []
},
encodePacket: packet => {
return encode(packet);
},
decodePacket: data => {
return decode(data);
}
};
export default msgpackParser;
Then, include it in your background.js:
javascript Copy code
import msgpackParser from './msgpackParser.js';
This implementation uses the msgpack-parser library to handle msgpack encoding and decoding.
With these changes, your extension should now use the Skinport WebSocket API to receive real-time updates on item listings and compare prices with Buff163.