From 17d9565e7f3d1c589b1dd0f980b23b88442dc90d Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 3 Jun 2019 17:50:28 +0200 Subject: [PATCH] Allow extensions with opt. subscribe & fallback (#51) --- README.md | 8 ++++---- packages/extension-dapp/src/index.ts | 19 +++++++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0e9c446a..55c0456a 100644 --- a/README.md +++ b/README.md @@ -73,15 +73,15 @@ interface Injected { interface Account = { readonly address: string; // ss-58 encoded address - readonly name?: string; // optional name for display + readonly name?: string; // (optional) name for display }; // exposes accounts interface Accounts { // retrieves the list of accounts for right now - get (): Promise>; - // subscribe to all accounts, updating as they change - subscribe (cb: (accounts: Array) => any): () => void + get: () => Promise>; + // (optional) subscribe to all accounts, updating as they change + subscribe?: (cb: (accounts: Array) => any) => () => void } // a signer that communicates with the extension via sendMessage diff --git a/packages/extension-dapp/src/index.ts b/packages/extension-dapp/src/index.ts index bf947af9..f41bea14 100644 --- a/packages/extension-dapp/src/index.ts +++ b/packages/extension-dapp/src/index.ts @@ -53,14 +53,29 @@ export function web3Enable (originName: string): Promise - values.filter(([, ext]) => ext).map(([info, ext]) => ({ ...info, ...ext } as InjectedExtension)) + values + .filter(([, ext]) => ext) + .map(([info, ext]) => { + // if we don't have an accounts subscriber, add a single-shot version + if (ext && !ext.accounts.subscribe) { + ext.accounts.subscribe = (cb: (accounts: Array) => any): Unsubcall => { + ext.accounts.get().then(cb).catch(console.error); + + return (): void => { + // no ubsubscribe needed, this is a single-shot + }; + }; + } + + return { ...info, ...ext } as InjectedExtension; + }) ) .catch(() => [] as Array) .then((values) => { const names = values.map(({ name, version }) => `${name}/${version}`); isWeb3Injected = web3IsInjected(); - console.log(`web3Enable: Enabled ${values.length} extensions ${names.join(', ')}`); + console.log(`web3Enable: Enabled ${values.length} extension${values.length !== 1 ? 's' : ''}: ${names.join(', ')}`); return values; })