// Connect to WebSocket
const ws = new WebSocket('wss://ws.noodles.fi/ws/coin-update');
// Connection opened
ws.onopen = function() {
console.log('Connected to Noodles WebSocket');
// Send ping to keep connection alive
ws.send(JSON.stringify({
type: 'ping'
}));
// Subscribe to USDC trading data (new format - recommended)
ws.send(JSON.stringify({
type: 'subscribe',
room: 'TRADES',
data: {
coin: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
}
}));
};
// Handle incoming messages
ws.onmessage = function(event) {
const message = JSON.parse(event.data);
switch(message.type) {
case 'data':
handleDataMessage(message);
break;
case 'error':
console.error('WebSocket error:', message.error);
break;
case 'pong':
console.log('Received pong from server');
break;
}
};
function handleDataMessage(message) {
const { channel, room, data } = message;
// Check if it's a subscription confirmation
if (data && data.action && (data.action === 'subscribe' || data.action === 'unsubscribe')) {
console.log(`${data.action} confirmed for room ${data.room}:`, data.channels);
return;
}
// Handle data based on room type
if (room === 'TRADES' || channel?.startsWith('TRADES-')) {
console.log('Trading data:', data);
} else if (room === 'COIN_UPDATES' || channel?.startsWith('COIN_UPDATES-')) {
console.log('Price update:', data);
} else if (room === 'OHLC' || channel?.startsWith('OHLC.')) {
console.log('OHLC data:', data);
} else if (room === 'ALERTS' || channel?.startsWith('ALERTS.')) {
console.log('Wallet alert:', data);
}
}
// Connection error
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
// Connection closed
ws.onclose = function(event) {
console.log('WebSocket connection closed:', event.code, event.reason);
};
// Unsubscribe from a channel
function unsubscribe(room, coin, bucket) {
const message = {
type: 'unsubscribe',
room: room,
data: {}
};
if (room === 'TRADES' || room === 'OHLC') {
message.data.coin = coin;
if (room === 'OHLC' && bucket) {
message.data.bucket = bucket;
}
} else if (room === 'COIN_UPDATES') {
message.data.coins = Array.isArray(coin) ? coin : [coin];
}
ws.send(JSON.stringify(message));
}
// Example usage:
// unsubscribe('TRADES', '0x2::sui::SUI');
// unsubscribe('OHLC', '0x2::sui::SUI', 5);
// unsubscribe('COIN_UPDATES', ['0x2::sui::SUI', '0xdba...::usdc::USDC']);