Allow extensions with opt. subscribe & fallback (#51)

This commit is contained in:
Jaco Greeff 2019-06-03 17:50:28 +02:00 committed by GitHub
parent 098debe216
commit 17d9565e7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 6 deletions

View File

@ -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<Array<Account>>;
// subscribe to all accounts, updating as they change
subscribe (cb: (accounts: Array<Account>) => any): () => void
get: () => Promise<Array<Account>>;
// (optional) subscribe to all accounts, updating as they change
subscribe?: (cb: (accounts: Array<Account>) => any) => () => void
}
// a signer that communicates with the extension via sendMessage

View File

@ -53,14 +53,29 @@ export function web3Enable (originName: string): Promise<Array<InjectedExtension
)
)
.then((values) =>
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<InjectedAccount>) => 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<InjectedExtension>)
.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;
})