Hello below is my code, when I try to connect to the websocket, I get the authentication error, please what am I doing wrong?
class CoinbaseWebSocket {
constructor() {
this.API_KEY = '';
this.SIGNING_KEY = '';
this.algorithm = 'ES256';
this.CHANNEL_NAMES = {
level2: 'level2',
user: 'user',
tickers: 'ticker',
ticker_batch: 'ticker_batch',
status: 'status',
market_trades: 'market_trades',
candles: 'candles',
};
this.WS_API_URL = 'wss://advanced-trade-ws.coinbase.com';
this.connections = [];
this.sentUnsub = false;
}
timestampAndSign(message, channel, products = []) {
console.log('Zombies');
console.log(this.API_KEY);
const timestamp = Math.floor(Date.now() / 1000).toString();
const jwt = sign(
{
aud: ['public_websocket_api'],
iss: 'coinbase-cloud',
nbf: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 120,
sub: this.API_KEY,
},
this.SIGNING_KEY,
{
algorithm: this.algorithm,
header: {
kid: this.API_KEY,
nonce: crypto.randomBytes(16).toString('hex'),
},
}
);
console.log('main');
console.log({ jwt: jwt, timestamp: timestamp });
return { ...message, jwt: jwt, timestamp: timestamp };
}
async subscribeToProducts(products, channelName, ws) {
console.log(`------ Trying to subscribe -------`);
console.log(channelName);
console.log(products);
return new Promise((resolve, reject) => {
const message = {
type: 'subscribe',
channel: channelName,
product_ids: products,
};
const subscribeMsg = this.timestampAndSign(message, channelName, products);
ws.send(JSON.stringify(subscribeMsg), (error) => {
if (error) reject(error);
else resolve();
});
});
}
async unsubscribeToProducts(products, channelName, ws) {
return new Promise((resolve, reject) => {
const message = {
type: 'unsubscribe',
channel: channelName,
product_ids: products,
};
const subscribeMsg = this.timestampAndSign(message, channelName, products);
ws.send(JSON.stringify(subscribeMsg), (error) => {
if (error) reject(error);
else resolve();
});
});
}
onMessage(data) {
const parsedData = JSON.parse(data);
fs.appendFile('Output1.txt', data, (err) => {
if (err) throw err;
});
}
async setupConnection() {
const ws = new WebSocket(this.WS_API_URL);
ws.on('message', async (data) => {
const date2 = new Date(new Date().toUTCString());
const diffTime = Math.abs(date2 - this.date1);
if (diffTime > 5000 && !this.sentUnsub) {
await this.unsubscribeToProducts(['BTC-USD'], this.CHANNEL_NAMES.level2, ws);
this.sentUnsub = true;
}
const parsedData = JSON.parse(data);
console.log({parsedData});
fs.appendFile('Output1.txt', data, (err) => {
if (err) throw err;
});
});
ws.on('open', async () => {
const products = ['BTC-USD'];
await this.subscribeToProducts(products, this.CHANNEL_NAMES.level2, ws);
});
this.connections.push(ws);
}
startConnections() {
this.date1 = new Date(new Date().toUTCString());
for (let i = 0; i < 1; i++) {
this.setupConnection();
}
}
}
module.exports = CoinbaseWebSocket