refactor: expose subscribe on the base client, with optional callback and call on child clients

This commit is contained in:
Derrick Hammer 2023-07-11 02:21:30 -04:00
parent 69e29a532a
commit 208ca03e80
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
3 changed files with 20 additions and 15 deletions

View File

@ -85,6 +85,21 @@ export default abstract class BaseClient {
this.syncMutex.release(); this.syncMutex.release();
} }
protected async subscribe(callback?: (ei: ExecutionInfo) => void) {
setInterval(async () => {
try {
await this._sync();
const ei = await this.getLatestExecution();
if (ei && ei.blockHash !== this.latestBlockHash) {
this.latestBlockHash = ei.blockHash;
return await callback?.(ei);
}
} catch (e) {
console.error(e);
}
}, POLLING_DELAY);
}
public get store(): IStore { public get store(): IStore {
return this.options.store as IStore; return this.options.store as IStore;
} }

View File

@ -101,21 +101,6 @@ export default class Client extends BaseClient {
return this.getCommittee(currentPeriod, lastCommitteeHash); return this.getCommittee(currentPeriod, lastCommitteeHash);
} }
private async subscribe(callback: (ei: ExecutionInfo) => void) {
setInterval(async () => {
try {
await this._sync();
const ei = await this.getLatestExecution();
if (ei && ei.blockHash !== this.latestBlockHash) {
this.latestBlockHash = ei.blockHash;
return await callback(ei);
}
} catch (e) {
console.error(e);
}
}, POLLING_DELAY);
}
private async getCommittee( private async getCommittee(
period: number, period: number,
expectedCommitteeHash: Uint8Array | null, expectedCommitteeHash: Uint8Array | null,

View File

@ -28,6 +28,11 @@ interface Config extends BaseClientOptions {
} }
export default class Client extends BaseClient { export default class Client extends BaseClient {
async sync(): Promise<void> {
await super.sync();
this.subscribe();
}
private beaconUrl: string; private beaconUrl: string;
private blockCache = new NodeCache({ stdTTL: 60 * 60 * 12 }); private blockCache = new NodeCache({ stdTTL: 60 * 60 * 12 });
private blockHashCache = new NodeCache({ stdTTL: 60 * 60 * 12 }); private blockHashCache = new NodeCache({ stdTTL: 60 * 60 * 12 });