@drift-labs/sdk-browser
Version:
SDK for Drift Protocol
59 lines (58 loc) • 2.57 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketConstituentAccountSubscriber = void 0;
const types_1 = require("../accounts/types");
const events_1 = require("events");
const webSocketProgramAccountSubscriber_1 = require("../accounts/webSocketProgramAccountSubscriber");
const memcmp_1 = require("../memcmp");
class WebSocketConstituentAccountSubscriber {
constructor(constituentMap, program, resubTimeoutMs, commitment, additionalFilters) {
this.constituentMap = constituentMap;
this.isSubscribed = false;
this.program = program;
this.eventEmitter = new events_1.EventEmitter();
this.resubTimeoutMs = resubTimeoutMs;
this.commitment = commitment;
this.additionalFilters = additionalFilters;
}
async subscribe() {
if (this.isSubscribed) {
return true;
}
this.constituentDataAccountSubscriber =
new webSocketProgramAccountSubscriber_1.WebSocketProgramAccountSubscriber('LpPoolConstituent', 'Constituent', this.program, this.program.account.constituent.coder.accounts.decode.bind(this.program.account.constituent.coder.accounts), {
filters: [(0, memcmp_1.getConstituentFilter)(), ...(this.additionalFilters || [])],
commitment: this.commitment,
});
await this.constituentDataAccountSubscriber.subscribe((accountId, account, context) => {
this.constituentMap.updateConstituentAccount(accountId.toBase58(), account, context.slot);
this.eventEmitter.emit('onAccountUpdate', account, accountId, context.slot);
});
this.eventEmitter.emit('update');
this.isSubscribed = true;
return true;
}
async sync() {
try {
await this.constituentMap.sync();
this.eventEmitter.emit('update');
}
catch (error) {
console.log(`WebSocketConstituentAccountSubscriber.sync() error: ${error.message}`);
this.eventEmitter.emit('error', error);
}
}
async unsubscribe() {
if (!this.isSubscribed) {
return;
}
await Promise.all([this.constituentDataAccountSubscriber.unsubscribe()]);
this.isSubscribed = false;
}
assertIsSubscribed() {
if (!this.isSubscribed) {
throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
}
}
}
exports.WebSocketConstituentAccountSubscriber = WebSocketConstituentAccountSubscriber;