@rango-dev/wallets-react 0.26.0 → 0.26.1-next.0

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/hub/autoConnect.d.ts +9 -0
  3. package/dist/hub/autoConnect.d.ts.map +1 -0
  4. package/dist/hub/constants.d.ts +3 -0
  5. package/dist/hub/constants.d.ts.map +1 -0
  6. package/dist/hub/helpers.d.ts +19 -0
  7. package/dist/hub/helpers.d.ts.map +1 -0
  8. package/dist/hub/lastConnectedWallets.d.ts +16 -0
  9. package/dist/hub/lastConnectedWallets.d.ts.map +1 -0
  10. package/dist/hub/mod.d.ts +3 -0
  11. package/dist/hub/mod.d.ts.map +1 -0
  12. package/dist/hub/types.d.ts +4 -0
  13. package/dist/hub/types.d.ts.map +1 -0
  14. package/dist/hub/useHubAdapter.d.ts +10 -0
  15. package/dist/hub/useHubAdapter.d.ts.map +1 -0
  16. package/dist/hub/useHubRefs.d.ts +7 -0
  17. package/dist/hub/useHubRefs.d.ts.map +1 -0
  18. package/dist/hub/utils.d.ts +38 -0
  19. package/dist/hub/utils.d.ts.map +1 -0
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +4 -4
  22. package/dist/legacy/autoConnect.d.ts +8 -0
  23. package/dist/legacy/autoConnect.d.ts.map +1 -0
  24. package/dist/legacy/helpers.d.ts +2 -6
  25. package/dist/legacy/helpers.d.ts.map +1 -1
  26. package/dist/legacy/mod.d.ts +5 -0
  27. package/dist/legacy/mod.d.ts.map +1 -0
  28. package/dist/legacy/types.d.ts +12 -4
  29. package/dist/legacy/types.d.ts.map +1 -1
  30. package/dist/legacy/useAutoConnect.d.ts +5 -4
  31. package/dist/legacy/useAutoConnect.d.ts.map +1 -1
  32. package/dist/legacy/useLegacyProviders.d.ts +5 -1
  33. package/dist/legacy/useLegacyProviders.d.ts.map +1 -1
  34. package/dist/legacy/utils.d.ts +3 -0
  35. package/dist/legacy/utils.d.ts.map +1 -0
  36. package/dist/useProviders.d.ts +4 -0
  37. package/dist/useProviders.d.ts.map +1 -0
  38. package/dist/wallets-react.build.json +1 -1
  39. package/package.json +3 -3
  40. package/src/hub/autoConnect.ts +186 -0
  41. package/src/hub/constants.ts +2 -0
  42. package/src/hub/helpers.ts +67 -0
  43. package/src/hub/lastConnectedWallets.ts +117 -0
  44. package/src/hub/mod.ts +2 -0
  45. package/src/hub/types.ts +12 -0
  46. package/src/hub/useHubAdapter.ts +339 -0
  47. package/src/hub/useHubRefs.ts +41 -0
  48. package/src/hub/utils.ts +388 -0
  49. package/src/legacy/autoConnect.ts +78 -0
  50. package/src/legacy/helpers.ts +17 -92
  51. package/src/legacy/mod.ts +13 -0
  52. package/src/legacy/types.ts +14 -6
  53. package/src/legacy/useAutoConnect.ts +8 -16
  54. package/src/legacy/useLegacyProviders.ts +45 -7
  55. package/src/legacy/utils.ts +7 -0
  56. package/src/provider.tsx +3 -3
  57. package/src/useProviders.ts +120 -0
  58. package/dist/legacy/constants.d.ts +0 -2
  59. package/dist/legacy/constants.d.ts.map +0 -1
  60. package/src/legacy/constants.ts +0 -1
@@ -0,0 +1,339 @@
1
+ import type { AllProxiedNamespaces, ExtensionLink } from './types.js';
2
+ import type { Providers } from '../index.js';
3
+ import type { Provider } from '@rango-dev/wallets-core';
4
+ import type {
5
+ LegacyNamespaceInputForConnect,
6
+ LegacyNamespace as Namespace,
7
+ } from '@rango-dev/wallets-core/legacy';
8
+ import type { VersionedProviders } from '@rango-dev/wallets-core/utils';
9
+
10
+ import { legacyIsNamespaceDiscoverMode } from '@rango-dev/wallets-core/legacy';
11
+ import { type WalletInfo } from '@rango-dev/wallets-shared';
12
+ import { useEffect, useRef, useState } from 'react';
13
+
14
+ import {
15
+ type ConnectResult,
16
+ HUB_LAST_CONNECTED_WALLETS,
17
+ type ProviderContext,
18
+ type ProviderProps,
19
+ } from '../legacy/mod.js';
20
+ import { useAutoConnect } from '../legacy/useAutoConnect.js';
21
+
22
+ import { autoConnect } from './autoConnect.js';
23
+ import { fromAccountIdToLegacyAddressFormat } from './helpers.js';
24
+ import { LastConnectedWalletsFromStorage } from './lastConnectedWallets.js';
25
+ import { useHubRefs } from './useHubRefs.js';
26
+ import {
27
+ checkHubStateAndTriggerEvents,
28
+ discoverNamespace,
29
+ getLegacyProvider,
30
+ transformHubResultToLegacyResult,
31
+ tryConvertNamespaceNetworkToChainInfo,
32
+ } from './utils.js';
33
+
34
+ export type UseAdapterParams = Omit<ProviderProps, 'providers'> & {
35
+ providers: Provider[];
36
+ /** This is only will be used to access some parts of the legacy provider that doesn't exists in Hub. */
37
+ allVersionedProviders: VersionedProviders[];
38
+ };
39
+
40
+ export function useHubAdapter(params: UseAdapterParams): ProviderContext {
41
+ const { getStore, getHub } = useHubRefs(params.providers);
42
+ const [, rerender] = useState(0);
43
+ // useEffect will run `subscribe` once, so we need a reference and mutate the value if it's changes.
44
+ const dataRef = useRef({
45
+ onUpdateState: params.onUpdateState,
46
+ allVersionedProviders: params.allVersionedProviders,
47
+ allBlockChains: params.allBlockChains,
48
+ });
49
+
50
+ useEffect(() => {
51
+ dataRef.current = {
52
+ onUpdateState: params.onUpdateState,
53
+ allVersionedProviders: params.allVersionedProviders,
54
+ allBlockChains: params.allBlockChains,
55
+ };
56
+ }, [params]);
57
+
58
+ // Initialize instances
59
+ useEffect(() => {
60
+ const runOnInit = () => {
61
+ getHub().init();
62
+
63
+ rerender((currentRender) => currentRender + 1);
64
+ };
65
+
66
+ // Then will call init whenever page is ready.
67
+ const initHubWhenPageIsReady = (event: Event) => {
68
+ // Then will call init whenever page is ready.
69
+ if (
70
+ event.target &&
71
+ (event.target as Document).readyState === 'complete'
72
+ ) {
73
+ runOnInit();
74
+ document.removeEventListener(
75
+ 'readystatechange',
76
+ initHubWhenPageIsReady
77
+ );
78
+ }
79
+ };
80
+
81
+ // Try to run, maybe it's ready.
82
+ runOnInit();
83
+
84
+ /*
85
+ * Try again when the page has been completely loaded.
86
+ * Some of wallets, take some time to be fully injected and loaded.
87
+ */
88
+ document.addEventListener('readystatechange', initHubWhenPageIsReady);
89
+
90
+ getStore().subscribe((curr, prev) => {
91
+ if (dataRef.current.onUpdateState) {
92
+ checkHubStateAndTriggerEvents(
93
+ getHub(),
94
+ curr,
95
+ prev,
96
+ dataRef.current.onUpdateState,
97
+ dataRef.current.allVersionedProviders,
98
+ dataRef.current.allBlockChains
99
+ );
100
+ }
101
+ rerender((currentRender) => currentRender + 1);
102
+ });
103
+ }, []);
104
+
105
+ useAutoConnect({
106
+ autoConnect: params.autoConnect,
107
+ allBlockChains: params.allBlockChains,
108
+ autoConnectHandler: () => {
109
+ void autoConnect({
110
+ getLegacyProvider: getLegacyProvider.bind(
111
+ null,
112
+ params.allVersionedProviders
113
+ ),
114
+ allBlockChains: params.allBlockChains,
115
+ getHub,
116
+ });
117
+ },
118
+ });
119
+
120
+ const lastConnectedWalletsFromStorage = new LastConnectedWalletsFromStorage(
121
+ HUB_LAST_CONNECTED_WALLETS
122
+ );
123
+
124
+ const api: ProviderContext = {
125
+ canSwitchNetworkTo(type, network) {
126
+ const provider = getLegacyProvider(params.allVersionedProviders, type);
127
+ const switchTo = provider.canSwitchNetworkTo;
128
+
129
+ if (!switchTo) {
130
+ return false;
131
+ }
132
+
133
+ return switchTo({
134
+ network,
135
+ meta: params.allBlockChains || [],
136
+ provider: provider.getInstance(),
137
+ });
138
+ },
139
+ async connect(type, namespaces) {
140
+ const wallet = getHub().get(type);
141
+ if (!wallet) {
142
+ throw new Error(
143
+ `You should add ${type} to provider first then call 'connect'.`
144
+ );
145
+ }
146
+
147
+ if (!namespaces) {
148
+ throw new Error(
149
+ 'Passing namespace to `connect` is required. you can pass DISCOVERY_MODE for legacy.'
150
+ );
151
+ }
152
+
153
+ // Check `namespace` and look into hub to see how it can match given namespace to hub namespace.
154
+ const targetNamespaces: [
155
+ LegacyNamespaceInputForConnect,
156
+ AllProxiedNamespaces
157
+ ][] = [];
158
+ namespaces.forEach((namespace) => {
159
+ let targetNamespace: Namespace;
160
+ if (legacyIsNamespaceDiscoverMode(namespace)) {
161
+ targetNamespace = discoverNamespace(namespace.network);
162
+ } else {
163
+ targetNamespace = namespace.namespace;
164
+ }
165
+
166
+ const result = wallet.findByNamespace(targetNamespace);
167
+
168
+ if (!result) {
169
+ throw new Error(
170
+ `We couldn't find any provider matched with your request namespace. (requested namespace: ${namespace.namespace})`
171
+ );
172
+ }
173
+
174
+ targetNamespaces.push([namespace, result]);
175
+ });
176
+
177
+ // Try to run `connect` on matched namespaces
178
+ const connectResultFromTargetNamespaces = targetNamespaces.map(
179
+ async ([namespaceInput, namespace]) => {
180
+ const network = tryConvertNamespaceNetworkToChainInfo(
181
+ namespaceInput,
182
+ params.allBlockChains || []
183
+ );
184
+
185
+ /*
186
+ * `connect` can have different interfaces (e.g. Solana -> .connect(), EVM -> .connect("0x1") ),
187
+ * our assumption here is all the `connect` hasn't chain or if they have, they will accept it in first argument.
188
+ * By this assumption, always passing a chain should be problematic since it will be ignored if the namespace's `connect` hasn't chain.
189
+ */
190
+ const result = namespace.connect(network);
191
+ return result.then<ConnectResult>(transformHubResultToLegacyResult);
192
+ }
193
+ );
194
+ const connectResultWithLegacyFormat = await Promise.all(
195
+ connectResultFromTargetNamespaces
196
+ );
197
+
198
+ // If Provider has support for auto connect, we will add the wallet to storage.
199
+ const legacyProvider = getLegacyProvider(
200
+ params.allVersionedProviders,
201
+ type
202
+ );
203
+ if (legacyProvider.canEagerConnect) {
204
+ const namespaces = targetNamespaces.map(
205
+ (targetNamespace) => targetNamespace[0].namespace
206
+ );
207
+ lastConnectedWalletsFromStorage.addWallet(type, namespaces);
208
+ }
209
+
210
+ return connectResultWithLegacyFormat;
211
+ },
212
+ async disconnect(type) {
213
+ const wallet = getHub().get(type);
214
+ if (!wallet) {
215
+ throw new Error(
216
+ `You should add ${type} to provider first then call 'connect'.`
217
+ );
218
+ }
219
+
220
+ wallet.getAll().forEach((namespace) => {
221
+ return namespace.disconnect();
222
+ });
223
+
224
+ if (params.autoConnect) {
225
+ lastConnectedWalletsFromStorage.removeWallets([type]);
226
+ }
227
+ },
228
+ disconnectAll() {
229
+ throw new Error('`disconnectAll` not implemented');
230
+ },
231
+ async getSigners(type) {
232
+ const provider = getLegacyProvider(params.allVersionedProviders, type);
233
+ return provider.getSigners(provider.getInstance());
234
+ },
235
+ getWalletInfo(type) {
236
+ const wallet = getHub().get(type);
237
+ if (!wallet) {
238
+ throw new Error(`You should add ${type} to provider first.`);
239
+ }
240
+
241
+ const info = wallet.info();
242
+ if (!info) {
243
+ throw new Error('Your provider should have required `info`.');
244
+ }
245
+
246
+ const provider = getLegacyProvider(params.allVersionedProviders, type);
247
+
248
+ const installLink: Exclude<WalletInfo['installLink'], string> = {
249
+ DEFAULT: '',
250
+ };
251
+
252
+ // `extensions` in legacy format was uppercase and also `DEFAULT` was used instead of `homepage`
253
+ Object.keys(info.extensions).forEach((k) => {
254
+ const key = k as ExtensionLink;
255
+
256
+ if (info.extensions[key] === 'homepage') {
257
+ installLink.DEFAULT = info.extensions[key] || '';
258
+ }
259
+
260
+ const allowedKeys: ExtensionLink[] = [
261
+ 'firefox',
262
+ 'chrome',
263
+ 'brave',
264
+ 'edge',
265
+ ];
266
+ if (allowedKeys.includes(key)) {
267
+ const upperCasedKey = key.toUpperCase() as keyof Exclude<
268
+ WalletInfo['installLink'],
269
+ string
270
+ >;
271
+ installLink[upperCasedKey] = info.extensions[key] || '';
272
+ }
273
+ });
274
+
275
+ return {
276
+ name: info.name,
277
+ img: info.icon,
278
+ installLink: installLink,
279
+ // We don't have this values anymore, fill them with some values that communicate this.
280
+ color: 'red',
281
+ supportedChains: provider.getWalletInfo(params.allBlockChains || [])
282
+ .supportedChains,
283
+ isContractWallet: false,
284
+ mobileWallet: false,
285
+ // if set to false here, it will not show the wallet in mobile in anyways. to be compatible with old behavior, undefined is more appropirate.
286
+ showOnMobile: undefined,
287
+
288
+ isHub: true,
289
+ properties: wallet.info()?.properties,
290
+ };
291
+ },
292
+ providers() {
293
+ const output: Providers = {};
294
+
295
+ Array.from(getHub().getAll().keys()).forEach((id) => {
296
+ try {
297
+ const provider = getLegacyProvider(params.allVersionedProviders, id);
298
+ output[id] = provider.getInstance();
299
+ } catch (e) {
300
+ console.warn(e);
301
+ }
302
+ });
303
+
304
+ return output;
305
+ },
306
+ state(type) {
307
+ const result = getHub().state();
308
+ const provider = result[type];
309
+
310
+ if (!provider) {
311
+ throw new Error(
312
+ `It seems your requested provider doesn't exist in hub. Provider Id: ${type}`
313
+ );
314
+ }
315
+
316
+ const accounts = provider.namespaces
317
+ .filter((namespace) => namespace.connected)
318
+ .flatMap((namespace) =>
319
+ namespace.accounts?.map(fromAccountIdToLegacyAddressFormat)
320
+ )
321
+ .filter((account): account is string => !!account);
322
+
323
+ const coreState = {
324
+ connected: provider.connected,
325
+ connecting: provider.connecting,
326
+ installed: provider.installed,
327
+ reachable: true,
328
+ accounts: accounts,
329
+ network: null,
330
+ };
331
+ return coreState;
332
+ },
333
+ suggestAndConnect(_type, _network): never {
334
+ throw new Error('`suggestAndConnect` is not implemented');
335
+ },
336
+ };
337
+
338
+ return api;
339
+ }
@@ -0,0 +1,41 @@
1
+ import type { Provider, Store } from '@rango-dev/wallets-core';
2
+
3
+ import { createStore, Hub } from '@rango-dev/wallets-core';
4
+ import { useRef } from 'react';
5
+
6
+ export function useHubRefs(providers: Provider[]) {
7
+ const store = useRef<Store | null>(null);
8
+
9
+ const hub = useRef<Hub | null>(null);
10
+
11
+ // https://react.dev/reference/react/useRef#avoiding-recreating-the-ref-contents
12
+ function getStore() {
13
+ if (store.current !== null) {
14
+ return store.current;
15
+ }
16
+ const createdStore = createStore();
17
+ store.current = createdStore;
18
+ return createdStore;
19
+ }
20
+
21
+ function getHub(): Hub {
22
+ if (hub.current !== null) {
23
+ return hub.current;
24
+ }
25
+ const createdHub = new Hub({
26
+ store: getStore(),
27
+ });
28
+ /*
29
+ * First add providers to hub
30
+ * This helps to `getWalletInfo` be usable, before initialize.
31
+ */
32
+ providers.forEach((provider) => {
33
+ createdHub.add(provider.id, provider);
34
+ });
35
+
36
+ hub.current = createdHub;
37
+ return createdHub;
38
+ }
39
+
40
+ return { getStore, getHub };
41
+ }