@drift-labs/sdk-browser
Version:
SDK for Drift Protocol
55 lines (54 loc) • 1.96 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketProgramUserAccountSubscriber = void 0;
const types_1 = require("./types");
const events_1 = require("events");
class WebSocketProgramUserAccountSubscriber {
constructor(program, userAccountPublicKey, programSubscriber) {
this.isSubscribed = false;
this.program = program;
this.userAccountPublicKey = userAccountPublicKey;
this.eventEmitter = new events_1.EventEmitter();
this.programSubscriber = programSubscriber;
}
async subscribe(userAccount) {
if (this.isSubscribed) {
return true;
}
if (userAccount) {
this.updateData(userAccount, 0);
}
this.programSubscriber.onChange = (accountId, data, context) => {
if (accountId.equals(this.userAccountPublicKey)) {
this.updateData(data, context.slot);
this.eventEmitter.emit('userAccountUpdate', data);
this.eventEmitter.emit('update');
}
};
this.isSubscribed = true;
return true;
}
async fetch() {
if (!this.isSubscribed) {
throw new types_1.NotSubscribedError('Must subscribe before fetching account updates');
}
const account = await this.program.account.user.fetch(this.userAccountPublicKey);
this.updateData(account, 0);
}
updateData(userAccount, slot) {
this.userAccountAndSlot = {
data: userAccount,
slot,
};
}
async unsubscribe() {
this.isSubscribed = false;
}
getUserAccountAndSlot() {
if (!this.userAccountAndSlot) {
throw new types_1.NotSubscribedError('Must subscribe before getting user account data');
}
return this.userAccountAndSlot;
}
}
exports.WebSocketProgramUserAccountSubscriber = WebSocketProgramUserAccountSubscriber;