-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathConnectButton.tsx
More file actions
610 lines (585 loc) · 17.2 KB
/
Copy pathConnectButton.tsx
File metadata and controls
610 lines (585 loc) · 17.2 KB
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
"use client";
import styled from "@emotion/styled";
import { useEffect, useMemo, useState } from "react";
import { getDefaultWallets } from "../../../../wallets/defaultWallets.js";
import { AccountProvider } from "../../../core/account/provider.js";
import { iconSize } from "../../../core/design-system/index.js";
import { useSiweAuth } from "../../../core/hooks/auth/useSiweAuth.js";
import type { ConnectButtonProps } from "../../../core/hooks/connection/ConnectButtonProps.js";
import { useActiveAccount } from "../../../core/hooks/wallets/useActiveAccount.js";
import { useActiveWallet } from "../../../core/hooks/wallets/useActiveWallet.js";
import { useActiveWalletConnectionStatus } from "../../../core/hooks/wallets/useActiveWalletConnectionStatus.js";
import { useConnectionManager } from "../../../core/providers/connection-manager.js";
import { defaultTokens } from "../../../core/utils/defaultTokens.js";
import {
WalletUIStatesProvider,
useSetIsWalletModalOpen,
} from "../../providers/wallet-ui-states-provider.js";
import { canFitWideModal } from "../../utils/canFitWideModal.js";
import { usePreloadWalletProviders } from "../../utils/usePreloadWalletProviders.js";
import { AutoConnect } from "../AutoConnect/AutoConnect.js";
import { Modal } from "../components/Modal.js";
import { Spinner } from "../components/Spinner.js";
import { Container } from "../components/basic.js";
import { Button } from "../components/buttons.js";
import { fadeInAnimation } from "../design-system/animations.js";
import { ConnectedWalletDetails } from "./Details.js";
import ConnectModal from "./Modal/ConnectModal.js";
import { LockIcon } from "./icons/LockIcon.js";
import { useConnectLocale } from "./locale/getConnectLocale.js";
import type { ConnectLocale } from "./locale/types.js";
import { SignatureScreen } from "./screens/SignatureScreen.js";
import { useAdminWallet } from "src/exports/react.native.js";
const TW_CONNECT_WALLET = "tw-connect-wallet";
/**
* A fully featured wallet connection component that allows to:
*
* - Connect to 500+ external wallets
* - Connect with email, phone, passkey or socials
* - Convert any wallet to a ERC4337 smart wallet for gasless transactions
* - Sign in with ethereum (Auth)
*
* Once connected, the component allows to:
*
* - Reolve ENS names and avatars
* - Manage multipple connected wallets
* - Send and receive native tokens and ERC20 tokens
* - View ERC20 tokens and NFTs
* - Onramp, bridge and swap tokens
* - Switch chains
* - Connect to another app with WalletConnect
*
* @example
*
* ## Default setup
*
* ```tsx
* import { createThirdwebClient } from "thirdweb";
* import { ConnectButton } from "thirdweb/react";
*
* const client = createThirdwebClient({ clientId: "YOUR_CLIENT_ID" });
*
* <ConnectButton
* client={client}
* />
* ```
*
* [View all available config options](https://portal.thirdweb.com/references/typescript/v5/ConnectButtonProps)
*
* ## Customization options
*
* ### Customizing wallet options
*
* ```tsx
* <ConnectButton
* client={client}
* wallets={[
* createWallet("io.metamask"),
* createWallet("com.coinbase.wallet"),
* createWallet("me.rainbow"),
* ]}
* />
* ```
*
* [View all available wallets](https://portal.thirdweb.com/typescript/v5/supported-wallets)
*
* ### Customizing the default chain to connect to
*
* ```tsx
* import { sepolia } from "thirdweb/chains";
*
* <ConnectButton
* client={client}
* chain={sepolia}
* />
* ```
*
* ### Enabling Account Abstraction
*
* By passing the `accountAbstraction` prop, ALL connected wallets will be converted to smart accounts.
* And by setting `sponsorGas` to `true`, all transactions done with those smart accounts will be sponsored.
*
* ```tsx
* <ConnectButton
* client={client}
* accountAbstraction={{
* chain: sepolia,
* sponsorGas: true,
* }}
* />;
* ```
*
* Note that this prop doesn't affect ecosystem wallets. Ecosystem wallets will only be converted to smart accounts if the ecosystem owner has enabled account abstraction.
*
* ### Enabling sign in with ethereum (Auth)
*
* ```tsx
* <ConnectButton
* client={client}
* auth={{
* isLoggedIn: async (address) => {
* console.log("checking if logged in!", { address });
* return await isLoggedIn();
* },
* doLogin: async (params) => {
* console.log("logging in!");
* await login(params);
* },
* getLoginPayload: async ({ address }) =>
* generatePayload({ address }),
* doLogout: async () => {
* console.log("logging out!");
* await logout();
* },
* }}
* />;
* ```
*
* ### Customizing the theme
*
* ```tsx
* <ConnectButton
* client={client}
* theme="light"
* />
* ```
*
* For more granular control, you can also pass a custom theme object:
*
* ```tsx
* <ConnectButton
* client={client}
* theme={lightTheme({
* colors: {
* modalBg: "red",
* },
* })}
* />
* ```
*
* [View all available themes properties](https://portal.thirdweb.com/references/typescript/v5/Theme)
*
* ### Changing the display language
*
* ```tsx
* <ConnectEmbed
* client={client}
* locale="ja_JP"
* />
* ```
*
* [View all available locales](https://portal.thirdweb.com/references/typescript/v5/LocaleId)
*
* ### Customizing the connect button UI
*
* ```tsx
* <ConnectButton
* client={client}
* connectButton={{
* label: "Sign in to MyApp",
* }}
* />
* ```
*
* ### Customizing the modal UI
*
* ```tsx
* <ConnectButton
* client={client}
* connectModal={{
* title: "Sign in to MyApp",
* titleIcon: "https://example.com/logo.png",
* size: "compact",
* }}
* />
* ```
*
* ### Customizing details button UI (after connecting)
*
* ```tsx
* <ConnectButton
* client={client}
* detailsButton={{
* displayBalanceToken: {
* [sepolia.id]: "0x...", // token address to display balance for
* [ethereum.id]: "0x...", // token address to display balance for
* },
* }}
* />
* ```
*
* [View all available auth helper functions](https://portal.thirdweb.com/references/typescript/v5/createAuth)
*
* ### Customizing the Auth sign in button (after connecting, but before authenticating)
*
* ```tsx
* <ConnectButton
* client={client}
* auth={{ ... }}
* signInButton: {
* label: "Authenticate with MyApp",
* },
* }}
* />;
* ```
*
* ### Customizing supported Tokens and NFTs
*
* These tokens and NFTs will be shown in the modal when the user clicks "View Assets", as well as the send token screen.
*
* ```tsx
* <ConnectButton
* client={client}
* supportedTokens={{
* [ethereum.id]: [
* {
* address: "0x...",
* name: "MyToken",
* symbol: "MT",
* icon: "https://example.com/icon.png",
* },
* ],
* }}
* supportedNFTs={{
* [ethereum.id]: [
* "0x...", // nft contract address
* ],
* }}
* />
* ```
*
* ### Customizing the orders of the tabs in the [View Funds] screen
* When you click on "View Assets", by default the "Tokens" tab is shown first.
* If you want to show the "NFTs" tab first, change the order of the asset tabs to: ["nft", "token"]
* Note: If an empty array is passed, the [View Funds] button will be hidden
*
* ```tsx
* <ConnectButton
* client={client}
* detailsModal={{
* assetTabs: ["nft", "token"],
* }}
* />
* ```
*
* ### Callback for when the details modal is closed
* ```tsx
* <ConnectButton
* detailsModal={{
* onClose: (screen: string) => {
* console.log({ screen });
* }
* }}
* />
* ```
*
* @param props
* Props for the `ConnectButton` component
*
* Refer to [ConnectButtonProps](https://portal.thirdweb.com/references/typescript/v5/ConnectButtonProps) to see the available props.
*
* @returns A JSX element that renders the <ConnectButton> component.
*
* @component
* @walletConnection
*/
export function ConnectButton(props: ConnectButtonProps) {
const wallets = useMemo(
() =>
props.wallets ||
getDefaultWallets({
appMetadata: props.appMetadata,
chains: props.chains,
}),
[props.wallets, props.appMetadata, props.chains],
);
const localeQuery = useConnectLocale(props.locale || "en_US");
const connectionManager = useConnectionManager();
usePreloadWalletProviders({
wallets,
});
// Add props.chain and props.chains to defined chains store
useEffect(() => {
if (props.chain) {
connectionManager.defineChains([props.chain]);
}
}, [props.chain, connectionManager]);
useEffect(() => {
if (props.chains) {
connectionManager.defineChains(props.chains);
}
}, [props.chains, connectionManager]);
const size = useMemo(() => {
return !canFitWideModal() || wallets.length === 1
? "compact"
: props.connectModal?.size || "compact";
}, [wallets.length, props.connectModal?.size]);
const preferredChain =
props.accountAbstraction?.chain || props.chain || props.chains?.[0];
const autoConnectComp = props.autoConnect !== false && (
<AutoConnect
chain={preferredChain}
appMetadata={props.appMetadata}
client={props.client}
wallets={wallets}
timeout={
typeof props.autoConnect === "boolean"
? undefined
: props.autoConnect?.timeout
}
accountAbstraction={props.accountAbstraction}
onConnect={props.onConnect}
/>
);
if (!localeQuery.data) {
const combinedClassName = `${props.connectButton?.className || ""} ${TW_CONNECT_WALLET}`;
return (
<AnimatedButton
disabled={true}
className={combinedClassName}
variant="primary"
type="button"
style={{
minWidth: "165px",
height: "50px",
...props.connectButton?.style,
}}
>
{autoConnectComp}
<Spinner size="sm" color="primaryButtonText" />
</AnimatedButton>
);
}
return (
<WalletUIStatesProvider theme={props.theme} isOpen={false}>
<ConnectButtonInner {...props} connectLocale={localeQuery.data} />
<ConnectModal
shouldSetActive={true}
accountAbstraction={props.accountAbstraction}
auth={props.auth}
chain={preferredChain}
chains={props.chains}
client={props.client}
connectLocale={localeQuery.data}
meta={{
title: props.connectModal?.title,
titleIconUrl: props.connectModal?.titleIcon,
showThirdwebBranding: props.connectModal?.showThirdwebBranding,
termsOfServiceUrl: props.connectModal?.termsOfServiceUrl,
privacyPolicyUrl: props.connectModal?.privacyPolicyUrl,
requireApproval: props.connectModal?.requireApproval,
}}
welcomeScreen={props.connectModal?.welcomeScreen}
size={size}
localeId={props.locale || "en_US"}
onConnect={props.onConnect}
recommendedWallets={props.recommendedWallets}
showAllWallets={props.showAllWallets}
walletConnect={props.walletConnect}
wallets={wallets}
/>
{autoConnectComp}
</WalletUIStatesProvider>
);
}
function ConnectButtonInner(
props: ConnectButtonProps & {
connectLocale: ConnectLocale;
},
) {
const activeWallet = useActiveWallet();
const activeAccount = useActiveAccount();
const adminWallet = useAdminWallet();
const siweAuth = useSiweAuth(activeWallet, activeAccount, props.auth);
const [showSignatureModal, setShowSignatureModal] = useState(false);
// if wallet gets disconnected suddently, close the signature modal if it's open
useEffect(() => {
if (!activeAccount) {
setShowSignatureModal(false);
}
}, [activeAccount]);
// if an IAW wallet is connected and auth is required, trigger a login attempt automatically
useEffect(() => {
const isIAW = activeWallet?.id === "inApp" || adminWallet?.id === "inApp";
if (
activeAccount &&
siweAuth.requiresAuth &&
!siweAuth.isLoggedIn &&
!siweAuth.isLoggingIn &&
isIAW
) {
siweAuth.doLogin();
}
}, [
activeAccount,
siweAuth.requiresAuth,
siweAuth.doLogin,
siweAuth.isLoggedIn,
siweAuth.isLoggingIn,
activeWallet,
adminWallet,
]);
const theme = props.theme || "dark";
const connectionStatus = useActiveWalletConnectionStatus();
const locale = props.connectLocale;
const isLoading = connectionStatus === "connecting";
const connectButtonLabel =
props.connectButton?.label || locale.defaultButtonTitle;
const setIsWalletModalOpen = useSetIsWalletModalOpen();
const supportedTokens = useMemo(() => {
if (!props.supportedTokens) {
return undefined;
}
const tokens = { ...defaultTokens };
for (const k in props.supportedTokens) {
const key = Number(k);
const tokenList = props.supportedTokens[key];
if (tokenList) {
tokens[key] = tokenList;
}
}
return tokens;
}, [props.supportedTokens]);
if (!activeAccount) {
// Connect Wallet button
const combinedClassName = `${props.connectButton?.className || ""} ${TW_CONNECT_WALLET}`;
return (
<AnimatedButton
disabled={isLoading}
className={combinedClassName}
data-theme={theme}
data-is-loading={isLoading}
variant="primary"
type="button"
style={{
minWidth: "165px",
height: "50px",
fontSize: "16px",
...props.connectButton?.style,
}}
aria-label={
connectionStatus === "connecting"
? locale.connecting
: typeof connectButtonLabel === "string"
? connectButtonLabel
: locale.defaultButtonTitle
}
onClick={() => {
setIsWalletModalOpen(true);
}}
data-test="connect-wallet-button"
>
{isLoading ? (
<Spinner size="sm" color="primaryButtonText" />
) : (
connectButtonLabel
)}
</AnimatedButton>
);
}
if (siweAuth.requiresAuth) {
// loading state if loading
// TODO: figure out a way to consolidate the loading states with the ones from locale loading
if (siweAuth.isPending || siweAuth.isLoggingIn || siweAuth.isLoggingOut) {
const combinedClassName = `${props.connectButton?.className || ""} ${TW_CONNECT_WALLET}`;
return (
<AnimatedButton
disabled={true}
className={combinedClassName}
variant="primary"
type="button"
style={{
minWidth: "165px",
height: "50px",
...props.connectButton?.style,
}}
>
<Spinner size="sm" color="primaryButtonText" />
</AnimatedButton>
);
}
// sign in button + modal if *not* loading and *not* logged in
if (!siweAuth.isLoggedIn) {
return (
<>
<Button
variant="primary"
type="button"
onClick={() => {
setShowSignatureModal(true);
}}
className={props.signInButton?.className}
style={{
minWidth: "165px",
minHeight: "50px",
...props.signInButton?.style,
}}
>
{siweAuth.isLoggingIn ? (
<Spinner size="sm" color="primaryButtonText" />
) : (
<Container flex="row" center="y" gap="sm">
<LockIcon size={iconSize.sm} />
<span> {props.signInButton?.label || locale.signIn} </span>
</Container>
)}
</Button>
<Modal
size="compact"
open={showSignatureModal}
setOpen={setShowSignatureModal}
>
<SignatureScreen
client={props.client}
connectLocale={locale}
modalSize="compact"
termsOfServiceUrl={props.connectModal?.termsOfServiceUrl}
privacyPolicyUrl={props.connectModal?.privacyPolicyUrl}
onDone={() => setShowSignatureModal(false)}
auth={props.auth}
/>
</Modal>
</>
);
}
// otherwise, show the details button
}
return (
<AccountProvider address={activeAccount.address} client={props.client}>
<ConnectedWalletDetails
theme={theme}
detailsButton={props.detailsButton}
detailsModal={props.detailsModal}
supportedTokens={supportedTokens}
supportedNFTs={props.supportedNFTs}
onDisconnect={(info) => {
// logout on explicit disconnect!
if (siweAuth.requiresAuth) {
siweAuth.doLogout();
}
props.onDisconnect?.(info);
}}
chains={props?.chains || []}
chain={props.chain}
switchButton={props.switchButton}
client={props.client}
connectLocale={locale}
connectOptions={{
accountAbstraction: props.accountAbstraction,
appMetadata: props.appMetadata,
chain: props.chain,
chains: props.chains,
connectModal: props.connectModal,
recommendedWallets: props.recommendedWallets,
showAllWallets: props.showAllWallets,
walletConnect: props.walletConnect,
wallets: props.wallets,
hiddenWallets: props.detailsModal?.hiddenWallets,
}}
/>
</AccountProvider>
);
}
const AnimatedButton = /* @__PURE__ */ styled(Button)({
animation: `${fadeInAnimation} 300ms ease`,
});