@polkadot/extension-dapp 0.44.9 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle.js CHANGED
@@ -1,94 +1,67 @@
1
- // Copyright 2019-2023 @polkadot/extension-dapp authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
1
  import { isPromise, objectSpread, u8aEq } from '@polkadot/util';
5
2
  import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
6
- import { documentReadyPromise } from "./util.js";
7
-
8
- // expose utility functions
9
- export { packageInfo } from "./packageInfo.js";
10
- export { unwrapBytes, wrapBytes } from "./wrapBytes.js";
11
-
12
- // just a helper (otherwise we cast all-over, so shorter and more readable)
3
+ import { documentReadyPromise } from './util.js';
4
+ export { packageInfo } from './packageInfo.js';
5
+ export { unwrapBytes, wrapBytes } from './wrapBytes.js';
13
6
  const win = window;
14
-
15
- // don't clobber the existing object, but ensure non-undefined
16
7
  win.injectedWeb3 = win.injectedWeb3 || {};
17
-
18
- // have we found a properly constructed window.injectedWeb3
19
8
  let isWeb3Injected = web3IsInjected();
20
-
21
- // we keep the last promise created around (for queries)
22
9
  let web3EnablePromise = null;
23
10
  export { isWeb3Injected, web3EnablePromise };
24
-
25
11
  /** @internal true when anything has been injected and is available */
26
12
  function web3IsInjected() {
27
- return Object.values(win.injectedWeb3).filter(({
28
- connect,
29
- enable
30
- }) => !!(connect || enable)).length !== 0;
13
+ return Object
14
+ .values(win.injectedWeb3)
15
+ .filter(({ connect, enable }) => !!(connect || enable))
16
+ .length !== 0;
31
17
  }
32
-
33
18
  /** @internal throw a consistent error when not extensions have not been enabled */
34
19
  function throwError(method) {
35
- throw new Error(`${method}: web3Enable(originName) needs to be called before ${method}`);
20
+ throw new Error(`${method}: web3Enable(originName) needs to be called before ${method}`);
36
21
  }
37
-
38
22
  /** @internal map from Array<InjectedAccount> to Array<InjectedAccountWithMeta> */
39
23
  function mapAccounts(source, list, ss58Format) {
40
- return list.map(({
41
- address,
42
- genesisHash,
43
- name,
44
- type
45
- }) => ({
46
- address: address.length === 42 ? address : encodeAddress(decodeAddress(address), ss58Format),
47
- meta: {
48
- genesisHash,
49
- name,
50
- source
51
- },
52
- type
53
- }));
24
+ return list.map(({ address, genesisHash, name, type }) => ({
25
+ address: address.length === 42
26
+ ? address
27
+ : encodeAddress(decodeAddress(address), ss58Format),
28
+ meta: { genesisHash, name, source },
29
+ type
30
+ }));
54
31
  }
55
-
56
32
  /** @internal filter accounts based on genesisHash and type of account */
57
33
  function filterAccounts(list, genesisHash, type) {
58
- return list.filter(a => (!a.type || !type || type.includes(a.type)) && (!a.genesisHash || !genesisHash || a.genesisHash === genesisHash));
34
+ return list.filter((a) => (!a.type || !type || type.includes(a.type)) &&
35
+ (!a.genesisHash || !genesisHash || a.genesisHash === genesisHash));
59
36
  }
60
-
61
37
  /** @internal retrieves all the extensions available on the window */
62
38
  function getWindowExtensions(originName) {
63
- return Promise.all(Object.entries(win.injectedWeb3).map(([nameOrHash, {
64
- connect,
65
- enable,
66
- version
67
- }]) => Promise.resolve().then(() => connect
68
- // new style, returning all info
69
- ? connect(originName) : enable
70
- // previous interface, leakages on name/version
71
- ? enable(originName).then(e => objectSpread({
72
- name: nameOrHash,
73
- version: version || 'unknown'
74
- }, e)) : Promise.reject(new Error('No connect(..) or enable(...) hook found'))).catch(({
75
- message
76
- }) => {
77
- console.error(`Error initializing ${nameOrHash}: ${message}`);
78
- }))).then(exts => exts.filter(e => !!e));
39
+ return Promise
40
+ .all(Object
41
+ .entries(win.injectedWeb3)
42
+ .map(([nameOrHash, { connect, enable, version }]) => Promise
43
+ .resolve()
44
+ .then(() => connect
45
+ // new style, returning all info
46
+ ? connect(originName)
47
+ : enable
48
+ // previous interface, leakages on name/version
49
+ ? enable(originName).then((e) => objectSpread({ name: nameOrHash, version: version || 'unknown' }, e))
50
+ : Promise.reject(new Error('No connect(..) or enable(...) hook found')))
51
+ .catch(({ message }) => {
52
+ console.error(`Error initializing ${nameOrHash}: ${message}`);
53
+ })))
54
+ .then((exts) => exts.filter((e) => !!e));
79
55
  }
80
-
81
56
  /** @internal Ensure the enable promise is resolved and filter by extensions */
82
57
  async function filterEnable(caller, extensions) {
83
- if (!web3EnablePromise) {
84
- return throwError(caller);
85
- }
86
- const sources = await web3EnablePromise;
87
- return sources.filter(({
88
- name
89
- }) => !extensions || extensions.includes(name));
58
+ if (!web3EnablePromise) {
59
+ return throwError(caller);
60
+ }
61
+ const sources = await web3EnablePromise;
62
+ return sources.filter(({ name }) => !extensions ||
63
+ extensions.includes(name));
90
64
  }
91
-
92
65
  /**
93
66
  * @summary Enables all the providers found on the injected window interface
94
67
  * @description
@@ -96,33 +69,37 @@ async function filterEnable(caller, extensions) {
96
69
  * should be called before making use of any other web3* functions.
97
70
  */
98
71
  export function web3Enable(originName, compatInits = []) {
99
- if (!originName) {
100
- throw new Error('You must pass a name for your app to the web3Enable function');
101
- }
102
- const initCompat = compatInits.length ? Promise.all(compatInits.map(c => c().catch(() => false))) : Promise.resolve([true]);
103
- web3EnablePromise = documentReadyPromise(() => initCompat.then(() => getWindowExtensions(originName).then(values => values.map(e => {
104
- // if we don't have an accounts subscriber, add a single-shot version
105
- if (!e.accounts.subscribe) {
106
- e.accounts.subscribe = cb => {
107
- e.accounts.get().then(cb).catch(console.error);
108
- return () => {
109
- // no ubsubscribe needed, this is a single-shot
110
- };
111
- };
72
+ if (!originName) {
73
+ throw new Error('You must pass a name for your app to the web3Enable function');
112
74
  }
113
- return e;
114
- })).catch(() => []).then(values => {
115
- const names = values.map(({
116
- name,
117
- version
118
- }) => `${name}/${version}`);
119
- isWeb3Injected = web3IsInjected();
120
- console.info(`web3Enable: Enabled ${values.length} extension${values.length !== 1 ? 's' : ''}: ${names.join(', ')}`);
121
- return values;
122
- })));
123
- return web3EnablePromise;
75
+ const initCompat = compatInits.length
76
+ ? Promise.all(compatInits.map((c) => c().catch(() => false)))
77
+ : Promise.resolve([true]);
78
+ web3EnablePromise = documentReadyPromise(() => initCompat.then(() => getWindowExtensions(originName)
79
+ .then((values) => values.map((e) => {
80
+ // if we don't have an accounts subscriber, add a single-shot version
81
+ if (!e.accounts.subscribe) {
82
+ e.accounts.subscribe = (cb) => {
83
+ e.accounts
84
+ .get()
85
+ .then(cb)
86
+ .catch(console.error);
87
+ return () => {
88
+ // no ubsubscribe needed, this is a single-shot
89
+ };
90
+ };
91
+ }
92
+ return e;
93
+ }))
94
+ .catch(() => [])
95
+ .then((values) => {
96
+ const names = values.map(({ name, version }) => `${name}/${version}`);
97
+ isWeb3Injected = web3IsInjected();
98
+ console.info(`web3Enable: Enabled ${values.length} extension${values.length !== 1 ? 's' : ''}: ${names.join(', ')}`);
99
+ return values;
100
+ })));
101
+ return web3EnablePromise;
124
102
  }
125
-
126
103
  /**
127
104
  * @summary Retrieves all the accounts across all providers
128
105
  * @description
@@ -131,33 +108,25 @@ export function web3Enable(originName, compatInits = []) {
131
108
  * per-genesisHash basis. Optionally the accounts can be encoded with the provided
132
109
  * ss58Format
133
110
  */
134
- export async function web3Accounts({
135
- accountType,
136
- extensions,
137
- genesisHash,
138
- ss58Format
139
- } = {}) {
140
- const accounts = [];
141
- const sources = await filterEnable('web3Accounts', extensions);
142
- const retrieved = await Promise.all(sources.map(async ({
143
- accounts,
144
- name: source
145
- }) => {
146
- try {
147
- const list = await accounts.get();
148
- return mapAccounts(source, filterAccounts(list, genesisHash, accountType), ss58Format);
149
- } catch (error) {
150
- // cannot handle this one
151
- return [];
152
- }
153
- }));
154
- retrieved.forEach(result => {
155
- accounts.push(...result);
156
- });
157
- console.info(`web3Accounts: Found ${accounts.length} address${accounts.length !== 1 ? 'es' : ''}`);
158
- return accounts;
111
+ export async function web3Accounts({ accountType, extensions, genesisHash, ss58Format } = {}) {
112
+ const accounts = [];
113
+ const sources = await filterEnable('web3Accounts', extensions);
114
+ const retrieved = await Promise.all(sources.map(async ({ accounts, name: source }) => {
115
+ try {
116
+ const list = await accounts.get();
117
+ return mapAccounts(source, filterAccounts(list, genesisHash, accountType), ss58Format);
118
+ }
119
+ catch (error) {
120
+ // cannot handle this one
121
+ return [];
122
+ }
123
+ }));
124
+ retrieved.forEach((result) => {
125
+ accounts.push(...result);
126
+ });
127
+ console.info(`web3Accounts: Found ${accounts.length} address${accounts.length !== 1 ? 'es' : ''}`);
128
+ return accounts;
159
129
  }
160
-
161
130
  /**
162
131
  * @summary Subscribes to all the accounts across all providers
163
132
  * @description
@@ -165,41 +134,33 @@ export async function web3Accounts({
165
134
  * updates as to when new accounts do become available. The list of filtering
166
135
  * options are the same as for the web3Accounts interface.
167
136
  */
168
- export async function web3AccountsSubscribe(cb, {
169
- accountType,
170
- extensions,
171
- genesisHash,
172
- ss58Format
173
- } = {}) {
174
- const sources = await filterEnable('web3AccountsSubscribe', extensions);
175
- const accounts = {};
176
- const triggerUpdate = () => cb(Object.entries(accounts).reduce((result, [source, list]) => {
177
- result.push(...mapAccounts(source, filterAccounts(list, genesisHash, accountType), ss58Format));
178
- return result;
179
- }, []));
180
- const unsubs = sources.map(({
181
- accounts: {
182
- subscribe
183
- },
184
- name: source
185
- }) => subscribe(result => {
186
- accounts[source] = result;
187
- try {
188
- const result = triggerUpdate();
189
- if (result && isPromise(result)) {
190
- result.catch(console.error);
191
- }
192
- } catch (error) {
193
- console.error(error);
194
- }
195
- }));
196
- return () => {
197
- unsubs.forEach(unsub => {
198
- unsub();
199
- });
200
- };
137
+ export async function web3AccountsSubscribe(cb, { accountType, extensions, genesisHash, ss58Format } = {}) {
138
+ const sources = await filterEnable('web3AccountsSubscribe', extensions);
139
+ const accounts = {};
140
+ const triggerUpdate = () => cb(Object
141
+ .entries(accounts)
142
+ .reduce((result, [source, list]) => {
143
+ result.push(...mapAccounts(source, filterAccounts(list, genesisHash, accountType), ss58Format));
144
+ return result;
145
+ }, []));
146
+ const unsubs = sources.map(({ accounts: { subscribe }, name: source }) => subscribe((result) => {
147
+ accounts[source] = result;
148
+ try {
149
+ const result = triggerUpdate();
150
+ if (result && isPromise(result)) {
151
+ result.catch(console.error);
152
+ }
153
+ }
154
+ catch (error) {
155
+ console.error(error);
156
+ }
157
+ }));
158
+ return () => {
159
+ unsubs.forEach((unsub) => {
160
+ unsub();
161
+ });
162
+ };
201
163
  }
202
-
203
164
  /**
204
165
  * @summary Finds a specific provider based on the name
205
166
  * @description
@@ -209,19 +170,16 @@ export async function web3AccountsSubscribe(cb, {
209
170
  * known extension.
210
171
  */
211
172
  export async function web3FromSource(source) {
212
- if (!web3EnablePromise) {
213
- return throwError('web3FromSource');
214
- }
215
- const sources = await web3EnablePromise;
216
- const found = source && sources.find(({
217
- name
218
- }) => name === source);
219
- if (!found) {
220
- throw new Error(`web3FromSource: Unable to find an injected ${source}`);
221
- }
222
- return found;
173
+ if (!web3EnablePromise) {
174
+ return throwError('web3FromSource');
175
+ }
176
+ const sources = await web3EnablePromise;
177
+ const found = source && sources.find(({ name }) => name === source);
178
+ if (!found) {
179
+ throw new Error(`web3FromSource: Unable to find an injected ${source}`);
180
+ }
181
+ return found;
223
182
  }
224
-
225
183
  /**
226
184
  * @summary Find a specific provider that provides a specific address
227
185
  * @description
@@ -229,21 +187,20 @@ export async function web3FromSource(source) {
229
187
  * available to the page.
230
188
  */
231
189
  export async function web3FromAddress(address) {
232
- if (!web3EnablePromise) {
233
- return throwError('web3FromAddress');
234
- }
235
- const accounts = await web3Accounts();
236
- let found;
237
- if (address) {
238
- const accountU8a = decodeAddress(address);
239
- found = accounts.find(account => u8aEq(decodeAddress(account.address), accountU8a));
240
- }
241
- if (!found) {
242
- throw new Error(`web3FromAddress: Unable to find injected ${address}`);
243
- }
244
- return web3FromSource(found.meta.source);
190
+ if (!web3EnablePromise) {
191
+ return throwError('web3FromAddress');
192
+ }
193
+ const accounts = await web3Accounts();
194
+ let found;
195
+ if (address) {
196
+ const accountU8a = decodeAddress(address);
197
+ found = accounts.find((account) => u8aEq(decodeAddress(account.address), accountU8a));
198
+ }
199
+ if (!found) {
200
+ throw new Error(`web3FromAddress: Unable to find injected ${address}`);
201
+ }
202
+ return web3FromSource(found.meta.source);
245
203
  }
246
-
247
204
  /**
248
205
  * @summary List all providers exposed by one source
249
206
  * @description
@@ -251,16 +208,13 @@ export async function web3FromAddress(address) {
251
208
  * of RPC providers that any extension may supply.
252
209
  */
253
210
  export async function web3ListRpcProviders(source) {
254
- const {
255
- provider
256
- } = await web3FromSource(source);
257
- if (!provider) {
258
- console.warn(`Extension ${source} does not expose any provider`);
259
- return null;
260
- }
261
- return provider.listProviders();
211
+ const { provider } = await web3FromSource(source);
212
+ if (!provider) {
213
+ console.warn(`Extension ${source} does not expose any provider`);
214
+ return null;
215
+ }
216
+ return provider.listProviders();
262
217
  }
263
-
264
218
  /**
265
219
  * @summary Start an RPC provider provider by a specific source
266
220
  * @description
@@ -269,15 +223,10 @@ export async function web3ListRpcProviders(source) {
269
223
  * specified extension source.
270
224
  */
271
225
  export async function web3UseRpcProvider(source, key) {
272
- const {
273
- provider
274
- } = await web3FromSource(source);
275
- if (!provider) {
276
- throw new Error(`Extension ${source} does not expose any provider`);
277
- }
278
- const meta = await provider.startProvider(key);
279
- return {
280
- meta,
281
- provider
282
- };
226
+ const { provider } = await web3FromSource(source);
227
+ if (!provider) {
228
+ throw new Error(`Extension ${source} does not expose any provider`);
229
+ }
230
+ const meta = await provider.startProvider(key);
231
+ return { meta, provider };
283
232
  }