@reown/appkit-wagmi-react-native 0.0.0-develop-20250728153935 → 0.0.0-develop-20251008155354

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 (51) hide show
  1. package/lib/commonjs/adapter.js +183 -0
  2. package/lib/commonjs/adapter.js.map +1 -0
  3. package/lib/commonjs/connectors/UniversalConnector.js +230 -0
  4. package/lib/commonjs/connectors/UniversalConnector.js.map +1 -0
  5. package/lib/commonjs/index.js +8 -121
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/package.json +1 -0
  8. package/lib/commonjs/utils/helpers.js +16 -45
  9. package/lib/commonjs/utils/helpers.js.map +1 -1
  10. package/lib/module/adapter.js +178 -0
  11. package/lib/module/adapter.js.map +1 -0
  12. package/lib/module/connectors/UniversalConnector.js +226 -0
  13. package/lib/module/connectors/UniversalConnector.js.map +1 -0
  14. package/lib/module/index.js +4 -91
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/utils/helpers.js +16 -41
  17. package/lib/module/utils/helpers.js.map +1 -1
  18. package/lib/typescript/adapter.d.ts +27 -0
  19. package/lib/typescript/adapter.d.ts.map +1 -0
  20. package/lib/typescript/connectors/UniversalConnector.d.ts +9 -0
  21. package/lib/typescript/connectors/UniversalConnector.d.ts.map +1 -0
  22. package/lib/typescript/index.d.ts +3 -24
  23. package/lib/typescript/index.d.ts.map +1 -1
  24. package/lib/typescript/utils/helpers.d.ts +3 -13
  25. package/lib/typescript/utils/helpers.d.ts.map +1 -1
  26. package/package.json +12 -28
  27. package/src/adapter.ts +227 -0
  28. package/src/connectors/UniversalConnector.ts +265 -0
  29. package/src/index.tsx +3 -121
  30. package/src/utils/helpers.ts +17 -57
  31. package/lib/commonjs/client.js +0 -516
  32. package/lib/commonjs/client.js.map +0 -1
  33. package/lib/commonjs/connectors/WalletConnectConnector.js +0 -355
  34. package/lib/commonjs/connectors/WalletConnectConnector.js.map +0 -1
  35. package/lib/commonjs/utils/defaultWagmiConfig.js +0 -46
  36. package/lib/commonjs/utils/defaultWagmiConfig.js.map +0 -1
  37. package/lib/module/client.js +0 -510
  38. package/lib/module/client.js.map +0 -1
  39. package/lib/module/connectors/WalletConnectConnector.js +0 -350
  40. package/lib/module/connectors/WalletConnectConnector.js.map +0 -1
  41. package/lib/module/utils/defaultWagmiConfig.js +0 -40
  42. package/lib/module/utils/defaultWagmiConfig.js.map +0 -1
  43. package/lib/typescript/client.d.ts +0 -40
  44. package/lib/typescript/client.d.ts.map +0 -1
  45. package/lib/typescript/connectors/WalletConnectConnector.d.ts +0 -74
  46. package/lib/typescript/connectors/WalletConnectConnector.d.ts.map +0 -1
  47. package/lib/typescript/utils/defaultWagmiConfig.d.ts +0 -11
  48. package/lib/typescript/utils/defaultWagmiConfig.d.ts.map +0 -1
  49. package/src/client.ts +0 -644
  50. package/src/connectors/WalletConnectConnector.ts +0 -472
  51. package/src/utils/defaultWagmiConfig.ts +0 -53
@@ -0,0 +1,265 @@
1
+ import type { Provider, WalletConnector } from '@reown/appkit-common-react-native';
2
+
3
+ import {
4
+ getAddress,
5
+ numberToHex,
6
+ RpcError,
7
+ SwitchChainError,
8
+ UserRejectedRequestError,
9
+ type Hex
10
+ } from 'viem';
11
+ import {
12
+ ChainNotConfiguredError,
13
+ createConnector,
14
+ ProviderNotFoundError,
15
+ type Connector
16
+ } from 'wagmi';
17
+
18
+ type UniversalConnector = Connector & {
19
+ onSessionDelete(data: { topic: string }): void;
20
+ };
21
+
22
+ type Properties = {
23
+ onSessionDelete(data: { topic: string }): void;
24
+ };
25
+
26
+ export function UniversalConnector(appKitProvidedConnector: WalletConnector) {
27
+ let provider: Provider | undefined;
28
+
29
+ let accountsChanged: UniversalConnector['onAccountsChanged'] | undefined;
30
+ let chainChanged: UniversalConnector['onChainChanged'] | undefined;
31
+ let sessionDelete: UniversalConnector['onSessionDelete'] | undefined;
32
+ let disconnect: UniversalConnector['onDisconnect'] | undefined;
33
+
34
+ function cleanupEventListeners(_provider?: Provider | null) {
35
+ if (accountsChanged) {
36
+ _provider?.off('accountsChanged', accountsChanged);
37
+ accountsChanged = undefined;
38
+ }
39
+ if (chainChanged) {
40
+ _provider?.off('chainChanged', chainChanged);
41
+ chainChanged = undefined;
42
+ }
43
+ if (disconnect) {
44
+ _provider?.off('disconnect', disconnect);
45
+ disconnect = undefined;
46
+ }
47
+ if (sessionDelete) {
48
+ _provider?.off('session_delete', sessionDelete);
49
+ sessionDelete = undefined;
50
+ }
51
+ }
52
+
53
+ return createConnector<Provider, Properties>(config => ({
54
+ id: 'walletconnect',
55
+ name: 'WalletConnect',
56
+ type: 'walletconnect' as const,
57
+ ready: !!appKitProvidedConnector.getProvider('eip155'),
58
+
59
+ async setup() {
60
+ const _provider = await this.getProvider().catch(() => null);
61
+ if (!_provider) {
62
+ return;
63
+ }
64
+ if (!sessionDelete) {
65
+ sessionDelete = this.onSessionDelete.bind(this);
66
+ _provider.on('session_delete', sessionDelete);
67
+ }
68
+ },
69
+
70
+ async connect({ chainId } = {}) {
71
+ try {
72
+ const _provider = appKitProvidedConnector.getProvider('eip155');
73
+ if (!_provider) throw new ProviderNotFoundError();
74
+
75
+ // AppKit connector is already connected or handles its own connection.
76
+ // We just need to sync its state with Wagmi.
77
+ const accountAddresses = await this.getAccounts();
78
+ if (!accountAddresses || accountAddresses.length === 0) {
79
+ throw new UserRejectedRequestError(
80
+ new Error('No accounts found or user rejected connection via AppKit.')
81
+ );
82
+ }
83
+
84
+ let currentChainId = await this.getChainId();
85
+
86
+ // Handle chain switching if requested and different
87
+ if (chainId && currentChainId !== chainId) {
88
+ await this.switchChain?.({ chainId });
89
+ currentChainId = chainId;
90
+ }
91
+ if (!accountsChanged) {
92
+ accountsChanged = this.onAccountsChanged.bind(this);
93
+ _provider.on('accountsChanged', accountsChanged);
94
+ }
95
+ if (!chainChanged) {
96
+ chainChanged = this.onChainChanged.bind(this);
97
+ _provider.on('chainChanged', chainChanged);
98
+ }
99
+ if (!disconnect) {
100
+ disconnect = this.onDisconnect.bind(this);
101
+ _provider.on('disconnect', disconnect);
102
+ }
103
+ if (!sessionDelete) {
104
+ sessionDelete = this.onSessionDelete.bind(this);
105
+ _provider.on('session_delete', sessionDelete);
106
+ }
107
+
108
+ return { accounts: accountAddresses, chainId: currentChainId };
109
+ } catch (error) {
110
+ if (error instanceof UserRejectedRequestError) throw error;
111
+ throw new UserRejectedRequestError(error as Error); // Generalize other errors as user rejection for simplicity
112
+ }
113
+ },
114
+
115
+ async disconnect() {
116
+ const _provider = await this.getProvider().catch(() => null);
117
+ try {
118
+ await appKitProvidedConnector.disconnect();
119
+ config.emitter.emit('message', { type: 'externalDisconnect' });
120
+ } catch (error) {
121
+ if (!/No matching key/i.test((error as Error).message)) {
122
+ throw error;
123
+ }
124
+ } finally {
125
+ cleanupEventListeners(_provider);
126
+ }
127
+ },
128
+
129
+ async getAccounts() {
130
+ const namespaces = appKitProvidedConnector.getNamespaces();
131
+ const eip155Accounts = namespaces?.['eip155']?.accounts as string[] | undefined;
132
+ if (!eip155Accounts) return [] as readonly Hex[];
133
+
134
+ return eip155Accounts
135
+ .map((caipAddr: string) => {
136
+ const parts = caipAddr.split(':');
137
+
138
+ return parts.length === 3 ? parts[2] : null;
139
+ })
140
+ .filter((addrPart): addrPart is string => !!addrPart)
141
+ .map((addrPart: string) => getAddress(addrPart)) as readonly Hex[];
142
+ },
143
+
144
+ async getChainId() {
145
+ const chainId = appKitProvidedConnector.getChainId('eip155')?.split(':')[1];
146
+
147
+ if (chainId) return parseInt(chainId, 10);
148
+
149
+ // Fallback: Try to get from CAIP accounts if available
150
+ const namespaces = appKitProvidedConnector.getNamespaces();
151
+ const eip155Accounts = namespaces?.['eip155']?.accounts as string[] | undefined;
152
+ if (eip155Accounts && eip155Accounts.length > 0) {
153
+ const parts = eip155Accounts[0]?.split(':');
154
+ if (parts && parts.length > 1 && typeof parts[1] === 'string') {
155
+ const chainIdNum = parseInt(parts[1], 10);
156
+ if (!isNaN(chainIdNum)) {
157
+ return chainIdNum;
158
+ }
159
+ }
160
+ }
161
+ if (config.chains && config.chains.length > 0) return config.chains[0].id;
162
+ throw new Error('Unable to determine chainId.');
163
+ },
164
+
165
+ async getProvider() {
166
+ if (!provider) {
167
+ provider = appKitProvidedConnector.getProvider('eip155');
168
+ }
169
+
170
+ return provider;
171
+ },
172
+
173
+ async isAuthorized() {
174
+ try {
175
+ const accounts = await this.getAccounts();
176
+
177
+ return !!(accounts && accounts.length > 0);
178
+ } catch {
179
+ return false;
180
+ }
181
+ },
182
+
183
+ async switchChain({ chainId }) {
184
+ const _provider = appKitProvidedConnector.getProvider('eip155');
185
+ if (!_provider) throw new Error('Provider not available for switching chain.');
186
+ const newChain = config.chains.find(c => c.id === chainId);
187
+
188
+ if (!newChain) throw new SwitchChainError(new ChainNotConfiguredError());
189
+
190
+ try {
191
+ await _provider.request({
192
+ method: 'wallet_switchEthereumChain',
193
+ params: [{ chainId: numberToHex(chainId) }]
194
+ });
195
+
196
+ return newChain;
197
+ } catch (err) {
198
+ const error = err as RpcError;
199
+
200
+ if (/(user rejected)/i.test(error.message)) throw new UserRejectedRequestError(error);
201
+
202
+ if ((error as any)?.code === 4902 || (error as any)?.data?.originalError?.code === 4902) {
203
+ // Indicates chain is not added to provider
204
+ try {
205
+ const addEthereumChainParams = {
206
+ chainId: numberToHex(chainId),
207
+ chainName: newChain.name,
208
+ nativeCurrency: newChain.nativeCurrency,
209
+ rpcUrls: [newChain.rpcUrls.default?.http[0] ?? ''],
210
+ blockExplorerUrls: [newChain.blockExplorers?.default?.url]
211
+ };
212
+
213
+ await _provider.request({
214
+ method: 'wallet_addEthereumChain',
215
+ params: [addEthereumChainParams]
216
+ });
217
+
218
+ return newChain;
219
+ } catch (addError) {
220
+ throw new UserRejectedRequestError(addError as Error);
221
+ }
222
+ }
223
+ throw new SwitchChainError(error as Error);
224
+ }
225
+ },
226
+
227
+ onAccountsChanged(accounts: string[]) {
228
+ //Only emit if the account is an evm account
229
+ const shouldEmit = accounts.some(account => account.startsWith('0x'));
230
+
231
+ if (accounts.length === 0) {
232
+ this.onDisconnect();
233
+ } else if (shouldEmit) {
234
+ config.emitter.emit('change', { accounts: accounts.map(x => getAddress(x)) });
235
+ }
236
+ },
237
+
238
+ onChainChanged(chain: string) {
239
+ const chainId = Number(chain);
240
+
241
+ //Only emit if the chain is in the config (evm)
242
+ const shouldEmit = config.chains.some(c => c.id === chainId);
243
+ if (shouldEmit) {
244
+ config.emitter.emit('change', { chainId });
245
+ }
246
+ },
247
+
248
+ async onDisconnect() {
249
+ config.emitter.emit('disconnect');
250
+
251
+ try {
252
+ const _provider = await this.getProvider();
253
+ cleanupEventListeners(_provider);
254
+ } catch (error) {
255
+ // If provider is not available, still clean up local references
256
+ // to prevent memory leaks
257
+ cleanupEventListeners(null);
258
+ }
259
+ },
260
+
261
+ onSessionDelete() {
262
+ this.onDisconnect();
263
+ }
264
+ }));
265
+ }
package/src/index.tsx CHANGED
@@ -1,122 +1,4 @@
1
- import '@walletconnect/react-native-compat';
2
- import { useEffect, useState, useSyncExternalStore } from 'react';
3
- export {
4
- AccountButton,
5
- AppKitButton,
6
- ConnectButton,
7
- NetworkButton,
8
- AppKit
9
- } from '@reown/appkit-scaffold-react-native';
10
- import type { EventName, EventsControllerState } from '@reown/appkit-scaffold-react-native';
11
- import { ConstantsUtil } from '@reown/appkit-common-react-native';
1
+ import { WagmiAdapter } from './adapter';
12
2
 
13
- export { defaultWagmiConfig } from './utils/defaultWagmiConfig';
14
- import { AppKit, type AppKitOptions } from './client';
15
-
16
- // -- Types -------------------------------------------------------------------
17
- export type { AppKitOptions } from './client';
18
-
19
- type OpenOptions = Parameters<AppKit['open']>[0];
20
-
21
- // -- Setup -------------------------------------------------------------------
22
- let modal: AppKit | undefined;
23
-
24
- export function createAppKit(options: AppKitOptions) {
25
- if (!modal) {
26
- modal = new AppKit({
27
- ...options,
28
- _sdkVersion: `react-native-wagmi-${ConstantsUtil.VERSION}`
29
- });
30
- }
31
-
32
- return modal;
33
- }
34
-
35
- // -- Hooks -------------------------------------------------------------------
36
- export function useAppKit() {
37
- if (!modal) {
38
- throw new Error('Please call "createAppKit" before using "useAppKit" hook');
39
- }
40
-
41
- async function open(options?: OpenOptions) {
42
- await modal?.open(options);
43
- }
44
-
45
- async function close() {
46
- await modal?.close();
47
- }
48
-
49
- return { open, close };
50
- }
51
-
52
- export function useAppKitState() {
53
- if (!modal) {
54
- throw new Error('Please call "createAppKit" before using "useAppKitState" hook');
55
- }
56
-
57
- const [state, setState] = useState(modal.getState());
58
-
59
- useEffect(() => {
60
- const unsubscribe = modal?.subscribeState(newState => {
61
- if (newState) setState({ ...newState });
62
- });
63
-
64
- return () => {
65
- unsubscribe?.();
66
- };
67
- }, []);
68
-
69
- return state;
70
- }
71
-
72
- export function useWalletInfo() {
73
- if (!modal) {
74
- throw new Error('Please call "createAppKit" before using "useWalletInfo" hook');
75
- }
76
-
77
- const walletInfo = useSyncExternalStore(
78
- modal.subscribeWalletInfo,
79
- modal.getWalletInfo,
80
- modal.getWalletInfo
81
- );
82
-
83
- return { walletInfo };
84
- }
85
-
86
- export function useAppKitEvents(callback?: (newEvent: EventsControllerState) => void) {
87
- if (!modal) {
88
- throw new Error('Please call "createAppKit" before using "useAppKitEvents" hook');
89
- }
90
-
91
- const [event, setEvents] = useState(modal.getEvent());
92
-
93
- useEffect(() => {
94
- const unsubscribe = modal?.subscribeEvents(newEvent => {
95
- setEvents({ ...newEvent });
96
- callback?.(newEvent);
97
- });
98
-
99
- return () => {
100
- unsubscribe?.();
101
- };
102
- }, [callback]);
103
-
104
- return event;
105
- }
106
-
107
- export function useAppKitEventSubscription(
108
- event: EventName,
109
- callback: (newEvent: EventsControllerState) => void
110
- ) {
111
- if (!modal) {
112
- throw new Error('Please call "createAppKit" before using "useAppKitEventSubscription" hook');
113
- }
114
-
115
- useEffect(() => {
116
- const unsubscribe = modal?.subscribeEvent(event, callback);
117
-
118
- return () => {
119
- unsubscribe?.();
120
- };
121
- }, [callback, event]);
122
- }
3
+ export { WagmiAdapter };
4
+ export { formatNetworks, formatNetwork } from './utils/helpers';
@@ -1,54 +1,13 @@
1
+ import { http } from 'viem';
1
2
  import {
2
- CoreHelperUtil,
3
- type CaipNetwork,
4
- type CaipNetworkId
5
- } from '@reown/appkit-scaffold-react-native';
6
- import { PresetsUtil, ConstantsUtil } from '@reown/appkit-common-react-native';
7
- import type { Connector } from '@wagmi/core';
8
- import { EthereumProvider } from '@walletconnect/ethereum-provider';
9
- import type { AppKitClientOptions } from '../client';
10
- import { http, type Hex } from 'viem';
11
-
12
- export function getCaipDefaultChain(chain?: AppKitClientOptions['defaultChain']) {
13
- if (!chain) {
14
- return undefined;
15
- }
16
-
17
- return {
18
- id: `${ConstantsUtil.EIP155}:${chain.id}`,
19
- name: chain.name,
20
- imageId: PresetsUtil.EIP155NetworkImageIds[chain.id]
21
- } as CaipNetwork;
22
- }
23
-
24
- export async function getWalletConnectCaipNetworks(connector?: Connector) {
25
- if (!connector) {
26
- throw new Error('networkControllerClient:getApprovedCaipNetworks - connector is undefined');
27
- }
28
- const provider = (await connector?.getProvider()) as Awaited<
29
- ReturnType<(typeof EthereumProvider)['init']>
30
- >;
31
- const ns = provider?.signer?.session?.namespaces;
32
- const nsMethods = ns?.[ConstantsUtil.EIP155]?.methods;
33
- const nsChains = ns?.[ConstantsUtil.EIP155]?.chains as CaipNetworkId[];
34
-
35
- return {
36
- supportsAllNetworks: Boolean(nsMethods?.includes(ConstantsUtil.ADD_CHAIN_METHOD)),
37
- approvedCaipNetworkIds: nsChains
38
- };
39
- }
40
-
41
- export function getAuthCaipNetworks() {
42
- return {
43
- supportsAllNetworks: false,
44
- approvedCaipNetworkIds: PresetsUtil.RpcChainIds.map(
45
- id => `${ConstantsUtil.EIP155}:${id}`
46
- ) as CaipNetworkId[]
47
- };
48
- }
3
+ PresetsUtil,
4
+ ConstantsUtil,
5
+ type AppKitNetwork,
6
+ type Network
7
+ } from '@reown/appkit-common-react-native';
49
8
 
50
9
  export function getTransport({ chainId, projectId }: { chainId: number; projectId: string }) {
51
- const RPC_URL = CoreHelperUtil.getBlockchainApiUrl();
10
+ const RPC_URL = ConstantsUtil.BLOCKCHAIN_API_RPC_URL;
52
11
 
53
12
  if (!PresetsUtil.RpcChainIds.includes(chainId)) {
54
13
  return http();
@@ -57,14 +16,15 @@ export function getTransport({ chainId, projectId }: { chainId: number; projectI
57
16
  return http(`${RPC_URL}/v1/?chainId=${ConstantsUtil.EIP155}:${chainId}&projectId=${projectId}`);
58
17
  }
59
18
 
60
- export function requireCaipAddress(caipAddress: string) {
61
- if (!caipAddress) {
62
- throw new Error('No CAIP address provided');
63
- }
64
- const account = caipAddress.split(':')[2] as Hex;
65
- if (!account) {
66
- throw new Error('Invalid CAIP address');
67
- }
19
+ export function formatNetwork(network: Network): AppKitNetwork {
20
+ return {
21
+ ...network,
22
+ rpcUrls: { ...network.rpcUrls },
23
+ chainNamespace: 'eip155',
24
+ caipNetworkId: `eip155:${network.id}`
25
+ };
26
+ }
68
27
 
69
- return account;
28
+ export function formatNetworks(networks: Network[]): AppKitNetwork[] {
29
+ return networks.map(formatNetwork);
70
30
  }