From df9166ed9cf9a92aed466ac680a1c98efe9461dd Mon Sep 17 00:00:00 2001 From: dapplion Date: Wed, 4 Nov 2020 13:45:02 +0000 Subject: [PATCH] Cache a promise for Bls instead of Bls --- src/context.ts | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/context.ts b/src/context.ts index daac1c5..bda3551 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,22 +1,34 @@ /* eslint-disable require-atomic-updates */ -import blsWasmWrapper from "@chainsafe/eth2-bls-wasm"; +import bls from "@chainsafe/eth2-bls-wasm"; -let blsWrapper: typeof blsWasmWrapper | null = null; +type Bls = typeof bls; +let blsGlobal: Bls | null = null; +let blsGlobalPromise: Promise | null = null; -export async function init(): Promise { - if(blsWrapper) return blsWrapper; - await blsWasmWrapper.init(); - blsWrapper = blsWasmWrapper; - return blsWrapper; +export async function setupBls(): Promise { + if (!blsGlobal) { + await bls.init(); + blsGlobal = bls; + } + return blsGlobal; +} + +// Cache a promise for Bls instead of Bls to make sure it is initialized only once +export async function init(): Promise { + if (!blsGlobalPromise) { + blsGlobalPromise = setupBls(); + } + return blsGlobalPromise; } export function destroy(): void { - blsWrapper = null; + blsGlobal = null; + blsGlobalPromise = null; } -export function getContext(): typeof blsWasmWrapper{ - if(blsWrapper) { - return blsWrapper; +export function getContext(): Bls { + if (!blsGlobal) { + throw new Error("BLS not initialized"); } - throw new Error("BLS not initialized"); + return blsGlobal; } \ No newline at end of file