UNPKG

@drift-labs/sdk

Version:
62 lines (61 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebSocketUserAccountSubscriber = void 0; const types_1 = require("./types"); const events_1 = require("events"); const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber"); class WebSocketUserAccountSubscriber { constructor(program, userAccountPublicKey, resubOpts, commitment) { this.isSubscribed = false; this.program = program; this.resubOpts = resubOpts; this.userAccountPublicKey = userAccountPublicKey; this.eventEmitter = new events_1.EventEmitter(); this.commitment = commitment; } async subscribe(userAccount) { if (this.isSubscribed) { return true; } this.userDataAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('user', this.program, this.userAccountPublicKey, undefined, this.resubOpts, this.commitment); if (userAccount) { this.userDataAccountSubscriber.setData(userAccount); } await this.userDataAccountSubscriber.subscribe((data) => { this.eventEmitter.emit('userAccountUpdate', data); this.eventEmitter.emit('update'); }); this.eventEmitter.emit('update'); this.isSubscribed = true; return true; } async fetch() { await Promise.all([this.userDataAccountSubscriber.fetch()]); } async unsubscribe() { if (!this.isSubscribed) { return; } await Promise.all([this.userDataAccountSubscriber.unsubscribe()]); this.isSubscribed = false; } assertIsSubscribed() { if (!this.isSubscribed) { throw new types_1.NotSubscribedError('You must call `subscribe` before using this function'); } } getUserAccountAndSlot() { this.assertIsSubscribed(); return this.userDataAccountSubscriber.dataAndSlot; } updateData(userAccount, slot) { var _a; const currentDataSlot = ((_a = this.userDataAccountSubscriber.dataAndSlot) === null || _a === void 0 ? void 0 : _a.slot) || 0; if (currentDataSlot <= slot) { this.userDataAccountSubscriber.setData(userAccount, slot); this.eventEmitter.emit('userAccountUpdate', userAccount); this.eventEmitter.emit('update'); } } } exports.WebSocketUserAccountSubscriber = WebSocketUserAccountSubscriber;