|
| 1 | +import { Commitment, PublicKey } from '@solana/web3.js'; |
| 2 | +import { UserStatsAccount } from '../types'; |
| 3 | +import { BasicUserStatsAccountSubscriber } from './basicUserStatsAccountSubscriber'; |
| 4 | +import { Program } from '@coral-xyz/anchor'; |
| 5 | +import { UserStatsAccountSubscriber } from './types'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Simple implementation of UserStatsAccountSubscriber. It will fetch the UserStatsAccount |
| 9 | + * data on subscribe (or call to fetch) if no account data is provided on init. |
| 10 | + * Expect to use only 1 RPC call unless you call fetch repeatedly. |
| 11 | + */ |
| 12 | +export class OneShotUserStatsAccountSubscriber |
| 13 | + extends BasicUserStatsAccountSubscriber |
| 14 | + implements UserStatsAccountSubscriber |
| 15 | +{ |
| 16 | + program: Program; |
| 17 | + commitment: Commitment; |
| 18 | + |
| 19 | + public constructor( |
| 20 | + program: Program, |
| 21 | + userStatsAccountPublicKey: PublicKey, |
| 22 | + data?: UserStatsAccount, |
| 23 | + slot?: number, |
| 24 | + commitment?: Commitment |
| 25 | + ) { |
| 26 | + super(userStatsAccountPublicKey, data, slot); |
| 27 | + this.program = program; |
| 28 | + this.commitment = commitment ?? 'confirmed'; |
| 29 | + } |
| 30 | + |
| 31 | + async subscribe(userStatsAccount?: UserStatsAccount): Promise<boolean> { |
| 32 | + if (userStatsAccount) { |
| 33 | + this.userStats = { data: userStatsAccount, slot: this.userStats.slot }; |
| 34 | + return true; |
| 35 | + } |
| 36 | + |
| 37 | + await this.fetchIfUnloaded(); |
| 38 | + if (this.doesAccountExist()) { |
| 39 | + this.eventEmitter.emit('update'); |
| 40 | + } |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + async fetchIfUnloaded(): Promise<void> { |
| 45 | + if (this.userStats.data === undefined) { |
| 46 | + await this.fetch(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + async fetch(): Promise<void> { |
| 51 | + try { |
| 52 | + const dataAndContext = |
| 53 | + await this.program.account.userStats.fetchAndContext( |
| 54 | + this.userStatsAccountPublicKey, |
| 55 | + this.commitment |
| 56 | + ); |
| 57 | + if (dataAndContext.context.slot > (this.userStats?.slot ?? 0)) { |
| 58 | + this.userStats = { |
| 59 | + data: dataAndContext.data as UserStatsAccount, |
| 60 | + slot: dataAndContext.context.slot, |
| 61 | + }; |
| 62 | + } |
| 63 | + } catch (e) { |
| 64 | + console.error( |
| 65 | + `OneShotUserStatsAccountSubscriber.fetch() UserStatsAccount does not exist: ${e.message}` |
| 66 | + ); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments