UNPKG

@drift-labs/sdk-browser

Version:
95 lines (94 loc) 3.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PollingUserStatsAccountSubscriber = void 0; const types_1 = require("./types"); const events_1 = require("events"); class PollingUserStatsAccountSubscriber { constructor(program, userStatsAccountPublicKey, accountLoader) { this.isSubscribed = false; this.program = program; this.accountLoader = accountLoader; this.eventEmitter = new events_1.EventEmitter(); this.userStatsAccountPublicKey = userStatsAccountPublicKey; } async subscribe(userStatsAccount) { if (this.isSubscribed) { return true; } if (userStatsAccount) { this.userStats = { data: userStatsAccount, slot: undefined }; } await this.addToAccountLoader(); await this.fetchIfUnloaded(); if (this.doesAccountExist()) { this.eventEmitter.emit('update'); } this.isSubscribed = true; return true; } async addToAccountLoader() { if (this.callbackId !== undefined) { return; } this.callbackId = await this.accountLoader.addAccount(this.userStatsAccountPublicKey, (buffer, slot) => { if (!buffer) { return; } if (this.userStats && this.userStats.slot > slot) { return; } const account = this.program.account.userStats.coder.accounts.decodeUnchecked('UserStats', buffer); this.userStats = { data: account, slot }; this.eventEmitter.emit('userStatsAccountUpdate', account); this.eventEmitter.emit('update'); }); this.errorCallbackId = this.accountLoader.addErrorCallbacks((error) => { this.eventEmitter.emit('error', error); }); } async fetchIfUnloaded() { if (this.userStats === undefined) { await this.fetch(); } } async fetch() { var _a, _b; try { const dataAndContext = await this.program.account.userStats.fetchAndContext(this.userStatsAccountPublicKey, this.accountLoader.commitment); if (dataAndContext.context.slot > ((_b = (_a = this.userStats) === null || _a === void 0 ? void 0 : _a.slot) !== null && _b !== void 0 ? _b : 0)) { this.userStats = { data: dataAndContext.data, slot: dataAndContext.context.slot, }; } } catch (e) { console.log(`PollingUserStatsAccountSubscriber.fetch() UserStatsAccount does not exist: ${e.message}`); } } doesAccountExist() { return this.userStats !== undefined; } async unsubscribe() { if (!this.isSubscribed) { return; } this.accountLoader.removeAccount(this.userStatsAccountPublicKey, this.callbackId); this.callbackId = undefined; this.accountLoader.removeErrorCallbacks(this.errorCallbackId); this.errorCallbackId = undefined; this.isSubscribed = false; } assertIsSubscribed() { if (!this.isSubscribed) { throw new types_1.NotSubscribedError('You must call `subscribe` before using this function'); } } getUserStatsAccountAndSlot() { if (!this.doesAccountExist()) { throw new types_1.NotSubscribedError('You must call `subscribe` or `fetch` before using this function'); } return this.userStats; } } exports.PollingUserStatsAccountSubscriber = PollingUserStatsAccountSubscriber;