forked from thirdweb-dev/js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet-hooks.ts
481 lines (463 loc) · 12.8 KB
/
wallet-hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { useWalletContext } from "../providers/thirdweb-wallet-provider";
import invariant from "tiny-invariant";
import type {
BloctoWallet,
Coin98Wallet,
CoinbaseWallet,
CoreWallet,
CryptoDefiWallet,
EmbeddedWallet,
FrameWallet,
ImTokenWallets
LocalWallet,
MagicEdenWallet,
MagicLink,
MetaMaskWallet,
OKXWallet,
OneKeyWallet,
PaperWallet,
PhantomWallet,
RabbyWallet,
RainbowWallet,
SafeWallet,
SmartWallet,
TokenBoundSmartWallet,
TrustWallet,
WalletConnect,
XDEFIWallet,
walletIds,
} from "@thirdweb-dev/wallets";
import { WalletInstance } from "../types/wallet";
export type WalletId = (typeof walletIds)[keyof typeof walletIds];
/**
* @wallet
*/
export type WalletIdToWalletTypeMap = {
metamask: MetaMaskWallet;
coin98: Coin98Wallet;
coinbase: CoinbaseWallet;
coreWallet: CoreWallet;
rainbowWallet: RainbowWallet;
blocto: BloctoWallet;
frame: FrameWallet;
imtoken: ImTokenWallet
localWallet: LocalWallet;
magicLink: MagicLink;
paper: PaperWallet;
smartWallet: SmartWallet;
tokenBoundSmartWallet: TokenBoundSmartWallet;
safe: SafeWallet;
trust: TrustWallet;
embeddedWallet: EmbeddedWallet;
walletConnect: WalletConnect;
phantom: PhantomWallet;
walletConnectV1: WalletConnect;
okx: OKXWallet;
oneKey: OneKeyWallet;
cryptoDefiWallet: CryptoDefiWallet;
rabby: RabbyWallet;
xdefi: XDEFIWallet;
magicEden: MagicEdenWallet
};
/**
* Hook to get the instance of the currently connected wallet.
*
* @example
* ```jsx
* import { useWallet } from "@thirdweb-dev/react";
*
* function App() {
* const walletInstance = useWallet();
* }
* ```
* @returns Currently connected `WalletInstance` , or `undefined` if no wallet is connected.
* @walletConnection
*/
export function useWallet(): WalletInstance | undefined;
/**
* Hook to get the instance of the currently connected wallet if it matches the given `walletId`.
*
* @example
* ```jsx
* import { useWallet } from "@thirdweb-dev/react";
*
* function App() {
* const metamaskWalletInstance = useWallet('metamask');
* }
* ```
*
* @returns Currently connected `WalletInstance` with given `walletId` , or `undefined` if no wallet is connected or if the connected wallet does not match the given `walletId`.
* @walletConnection
*/
export function useWallet<T extends WalletId>(
walletId: T,
): WalletIdToWalletTypeMap[T] | undefined;
export function useWallet<T extends WalletId>(walletId?: T) {
const context = useWalletContext();
invariant(
context,
"useWallet() hook must be used within a <ThirdwebProvider/>",
);
const activeWallet = context.activeWallet;
if (!activeWallet) {
return undefined;
}
// if walletId is provided, return the wallet instance only if it matches the walletId
if (walletId) {
if (activeWallet.walletId === walletId) {
return activeWallet as WalletIdToWalletTypeMap[T];
} else {
return undefined;
}
}
return activeWallet;
}
/**
*
* Hook to get the `WalletConfig` object of the currently connected wallet.
*
* This is useful to get metadata about the connected wallet, such as the wallet name, logo, etc
*
* @example
*
* ```jsx
* import { useWalletConfig } from "@thirdweb-dev/react";
*
* function App() {
* const walletConfig = useWalletConfig();
*
* const walletName = walletConfig?.meta.name;
* const walletLogo = walletConfig?.meta.iconURL;
* }
* ```
*
* @returns The current connected wallet's configuration object or `undefined` if no wallet is connected.
*
* @walletConnection
*/
export function useWalletConfig() {
const context = useWalletContext();
invariant(
context,
"useWallet() hook must be used within a <ThirdwebProvider/>",
);
return context.activeWalletConfig;
}
/**
* @internal
* Get `supportedWallets` passed in the `<ThirdwebProvider/>`
* @returns `supportedWallets` configured in the `<ThirdwebProvider/>`
*/
export function useWallets() {
const context = useWalletContext();
invariant(
context,
"useWallets() hook must be used within a <ThirdwebProvider/>",
);
return context.wallets;
}
/**
* Hook for connecting a wallet to your app.
*
* The wallet also needs to be added in `ThirdwebProvider`'s `supportedWallets` prop to enable auto-connection on page load.
*
* @example
* ```jsx
* import { useConnect, metamaskWallet } from "@thirdweb-dev/react";
*
* const metamaskConfig = metamaskWallet();
*
* function App() {
* const connect = useConnect();
*
* return (
* <button
* onClick={async () => {
* const wallet = await connect(metamaskConfig, connectOptions);
* console.log("connected to ", wallet);
* }}
* >
* Connect to MetaMask
* </button>
* );
* }
* ```
*
* @returns A function to connect a wallet
*
* ```ts
* const connect = useConnect();
*
* function handleConnect() {
* const wallet = await connect(walletConfig, connectOptions);
* }
* ```
*
* The function accepts two arguments: `walletConfig` and `connectOptions`
*
* #### walletConfig
* The wallet to connect. Must be of type `WalletConfig`.
*
* [Learn more about the available wallet options](https://portal.thirdweb.com/react/v4/connecting-wallets).
*
* #### connectOptions
* The typeof `connectOptions` object depends on the wallet you are connecting. For some wallets, it may be optional
*
* If you are using typescript, `connect` will automatically infer the type of `connectOptions` based on the `walletConfig` you pass in as the first argument and will show type errors if you pass in invalid options.
*
* @walletConnection
*/
export function useConnect() {
const context = useWalletContext();
invariant(
context,
"useConnect() hook must be used within a <ThirdwebProvider/>",
);
return context.connect;
}
/**
* Hook for disconnecting the currently connected wallet.
*
* @example
* ```jsx
* import { useDisconnect } from "@thirdweb-dev/react";
*
* function App() {
* const disconnect = useDisconnect();
*
* return <button onClick={disconnect}>Disconnect</button>;
* }
* ```
*
* @returns A function to disconnect from current connected wallet
* @walletConnection
*/
export function useDisconnect() {
const context = useWalletContext();
invariant(
context,
"useDisconnect() hook must be used within a <ThirdwebProvider/>",
);
return context.disconnect;
}
/**
* Hook for checking whether your app is connected to a wallet or not.
*
* @example
* ```jsx
* import { useConnectionStatus } from "@thirdweb-dev/react";
*
* function App() {
* const connectionStatus = useConnectionStatus();
*
* if (connectionStatus === "unknown") return <p> Loading... </p>;
* if (connectionStatus === "connecting") return <p> Connecting... </p>;
* if (connectionStatus === "connected") return <p> You are connected </p>;
* if (connectionStatus === "disconnected")
* return <p> You are not connected to a wallet </p>;
* }
* ```
*
* @returns The wallet connection status
*
* It can be one of the following:
* - `unknown`: connection status is not known yet. This is the initial state.
* - `connecting`: wallet is being connected. Either because of a user action, or when the wallet is auto-connecting on page load.
* - `connected`: the wallet is connected and ready to be used.
* - `disconnected`: the wallet is not connected.
*
* @walletConnection
*/
export function useConnectionStatus() {
const context = useWalletContext();
invariant(
context,
"useConnectionStatus() must be used within a <ThirdwebProvider/>",
);
return context.connectionStatus;
}
/**
* Hook for setting the `connectionStatus` of the wallet which is returned by the `useConnectionStatus` hook
*
* This is only useful if you are manually connecting a wallet instance as mentioned in [Build your Wallet](https://portal.thirdweb.com/wallet-sdk/v2/build)
*
* @example
*
* ```ts
* import {
* useCreateWalletInstance,
* useSetConnectionStatus,
* useSetConnectedWallet,
* metamaskWallet
* } from "@thirdweb-dev/react";
*
* const walletConfig = metamaskWallet();
*
* function Example() {
* const createWalletInstance = useCreateWalletInstance();
* const setConnectionStatus = useSetConnectionStatus();
* const setConnectedWallet = useSetConnectedWallet();
*
* // Call this function to connect your wallet
* const handleConnect = async () => {
* // 1. create instance
* const walletInstance = createWalletInstance(walletConfig);
* setConnectionStatus("connecting");
*
* try {
* // 2. Call `connect` method of your wallet
* await walletInstance.connect(
* connectOptions, // if your wallet.connect method accepts any options, specify it here
* );
*
* // 3. Set connected wallet
* setConnectedWallet(walletInstance);
* props.close();
* } catch (e) {
* setConnectionStatus("disconnected");
* console.error("failed to connect", e);
* }
* };
*
* return <div> ... </div>;
* }
* ```
*
* @returns A function that sets the `connectionStatus` of the wallet
* @walletConnection
*/
export function useSetConnectionStatus() {
const context = useWalletContext();
invariant(
context,
"useSetConnectionStatus() must be used within a <ThirdwebProvider/>",
);
return context.setConnectionStatus;
}
/**
* Hook for creating a wallet instance from given `WalletConfig` object.
*
* If you just want to connect the wallet and don't need the wallet instance before connecting the wallet, use the `useConnect` hook instead.
*
* @example
*
* ```jsx
* import { useConnect, metamaskWallet } from "@thirdweb-dev/react";
*
* const metamaskConfig = metamaskWallet();
*
* function App() {
* const createWalletInstance = useCreateWalletInstance();
*
* return (
* <button
* onClick={() => {
* const metamaskWalletInstance = createWalletInstance(metamaskConfig);
* console.log(metamaskWalletInstance);
* }}
* >
* create wallet instance
* </button>
* );
* }
* ```
*
* @returns A function that creates a wallet instance for given `WalletConfig` object.
*
* @walletConnection
*/
export function useCreateWalletInstance() {
const context = useWalletContext();
invariant(
context,
"useCreateWalletInstance() must be used within a <ThirdwebProvider/>",
);
return context.createWalletInstance;
}
/**
* Hook for switching to a different network.
*
* @example
* ```jsx
* import { useSwitchChain } from "@thirdweb-dev/react";
* import { Goerli } from "@thirdweb-dev/chains";
*
* function App() {
* const switchChain = useSwitchChain();
* return (
* <button onClick={() => switchChain(Goerli.chainId)}>
* Switch to Goerli
* </button>
* );
* }
* ```
*
* @returns A function to switch the network in the currently connected wallet to network with given `chainId`
* @networkConnection
*/
export function useSwitchChain() {
const context = useWalletContext();
invariant(
context,
"useSwitchChain() must be used within a <ThirdwebProvider/>",
);
return context.switchChain;
}
/**
* Hook for setting a wallet instance as "connected" - once done, the wallet connection hooks like `useWallet`, `useAddress`, `useSigner`, `useConnectionStatus` etc will return the data for that wallet instance
*
* This is only useful if you are manually connecting a wallet instance as mentioned in [Build your Wallet](https://portal.thirdweb.com/wallet-sdk/v2/build)
*
* @example
*
* ```ts
* import {
* useCreateWalletInstance,
* useSetConnectionStatus,
* useSetConnectedWallet,
* metamaskWallet
* } from "@thirdweb-dev/react";
*
* const walletConfig = metamaskWallet();
*
* function Example() {
* const createWalletInstance = useCreateWalletInstance();
* const setConnectionStatus = useSetConnectionStatus();
* const setConnectedWallet = useSetConnectedWallet();
*
* // Call this function to connect your wallet
* const handleConnect = async () => {
* // 1. create instance
* const walletInstance = createWalletInstance(walletConfig);
* setConnectionStatus("connecting");
*
* try {
* // 2. Call `connect` method of your wallet
* await walletInstance.connect(
* connectOptions, // if your wallet.connect method accepts any options, specify it here
* );
*
* // 3. Set connected wallet
* setConnectedWallet(walletInstance);
* props.close();
* } catch (e) {
* setConnectionStatus("disconnected");
* console.error("failed to connect", e);
* }
* };
*
* return <div> ... </div>;
* }
* ```
*
* @returns A function to set a wallet instance as "connected".
* @walletConnection
*/
export function useSetConnectedWallet() {
const context = useWalletContext();
invariant(
context,
"useSwitchChain() must be used within a <ThirdwebProvider/>",
);
return context.setConnectedWallet;
}