0
# Configuration and Theming
1
2
Web3ConfigProvider for application-wide configuration and Ant Design theme integration with Web3-specific extensions.
3
4
## Capabilities
5
6
### Web3ConfigProvider
7
8
Enhanced Web3 configuration provider with Ant Design theme integration, providing Web3 state management and configuration to all child components.
9
10
```typescript { .api }
11
/**
12
* Enhanced Web3 config provider with Ant Design theme integration
13
* @param theme - Extended theme configuration with web3Components
14
* @param children - Child components that will receive Web3 context
15
* @param account - Current connected account information
16
* @param chain - Current blockchain network
17
* @param balance - Account balance information
18
* @param availableWallets - List of available wallets for connection
19
* @param availableChains - List of supported blockchain networks
20
* @param extendsContextFromParent - Whether to extend context from parent provider
21
* @param addressPrefix - Address prefix for display (e.g., '0x')
22
* @param connect - Function to connect to a wallet
23
* @param disconnect - Function to disconnect from wallet
24
* @param switchChain - Function to switch blockchain networks
25
* @param getNFTMetadata - Function to fetch NFT metadata
26
* @param sign - Signing configuration for wallet authentication
27
* @param locale - Localization overrides for components
28
*/
29
const Web3ConfigProvider: React.FC<{ theme?: Web3ThemeConfig } & Web3ConfigProviderProps>;
30
31
interface Web3ConfigProviderProps extends UniversalWeb3ProviderInterface {
32
children?: React.ReactNode;
33
locale?: Locale;
34
}
35
36
interface Web3ThemeConfig extends ThemeConfig {
37
web3Components?: {
38
ConnectModal?: Partial<ConnectModalComponentToken>;
39
};
40
}
41
42
interface UniversalWeb3ProviderInterface {
43
account?: Account;
44
chain?: Chain;
45
balance?: Balance;
46
availableWallets?: Wallet[];
47
availableChains?: Chain[];
48
extendsContextFromParent?: boolean;
49
addressPrefix?: string | false;
50
connect?: (wallet?: Wallet, options?: ConnectOptions) => Promise<void | Account>;
51
disconnect?: () => Promise<void>;
52
switchChain?: (chain: Chain) => Promise<void>;
53
getNFTMetadata?: (params: { address: string; tokenId?: bigint }) => Promise<NFTMetadata>;
54
sign?: SignConfig;
55
}
56
```
57
58
**Usage Examples:**
59
60
```typescript
61
import { Web3ConfigProvider } from "@ant-design/web3";
62
63
// Basic configuration
64
function App() {
65
return (
66
<Web3ConfigProvider>
67
<MyDApp />
68
</Web3ConfigProvider>
69
);
70
}
71
72
// With wallet and chain configuration
73
function AppWithWallets() {
74
const availableWallets = [
75
{
76
name: "MetaMask",
77
remark: "Connect using MetaMask wallet",
78
icon: <MetaMaskIcon />,
79
extensions: [{
80
key: 'Chrome',
81
browserIcon: 'chrome',
82
browserName: 'Chrome',
83
link: 'https://metamask.io',
84
description: 'MetaMask browser extension'
85
}]
86
},
87
{
88
name: "WalletConnect",
89
remark: "Scan QR code with your mobile wallet",
90
icon: <WalletConnectIcon />,
91
universalProtocol: { link: "wc:" }
92
}
93
];
94
95
const availableChains = [
96
{
97
id: 1,
98
name: "Ethereum",
99
type: ChainType.EVM,
100
icon: <EthereumIcon />,
101
nativeCurrency: {
102
name: "Ether",
103
symbol: "ETH",
104
decimal: 18
105
}
106
},
107
{
108
id: 137,
109
name: "Polygon",
110
type: ChainType.EVM,
111
icon: <PolygonIcon />,
112
nativeCurrency: {
113
name: "MATIC",
114
symbol: "MATIC",
115
decimal: 18
116
}
117
}
118
];
119
120
return (
121
<Web3ConfigProvider
122
availableWallets={availableWallets}
123
availableChains={availableChains}
124
addressPrefix="0x"
125
>
126
<MyDApp />
127
</Web3ConfigProvider>
128
);
129
}
130
131
// With custom theme
132
function ThemedApp() {
133
const web3Theme = {
134
token: {
135
colorPrimary: '#1890ff',
136
},
137
web3Components: {
138
ConnectModal: {
139
borderRadius: 12,
140
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
141
padding: 24
142
}
143
}
144
};
145
146
return (
147
<Web3ConfigProvider theme={web3Theme}>
148
<MyDApp />
149
</Web3ConfigProvider>
150
);
151
}
152
153
// With connection handlers
154
function AppWithHandlers() {
155
const handleConnect = async (wallet, options) => {
156
console.log('Connecting to:', wallet?.name);
157
// Custom connection logic
158
try {
159
const account = await connectWallet(wallet, options);
160
return account;
161
} catch (error) {
162
console.error('Connection failed:', error);
163
throw error;
164
}
165
};
166
167
const handleDisconnect = async () => {
168
console.log('Disconnecting wallet');
169
// Custom disconnection logic
170
await disconnectWallet();
171
};
172
173
const handleChainSwitch = async (chain) => {
174
console.log('Switching to chain:', chain.name);
175
// Custom chain switching logic
176
await switchToChain(chain.id);
177
};
178
179
return (
180
<Web3ConfigProvider
181
connect={handleConnect}
182
disconnect={handleDisconnect}
183
switchChain={handleChainSwitch}
184
>
185
<MyDApp />
186
</Web3ConfigProvider>
187
);
188
}
189
190
// With NFT metadata fetching
191
function AppWithNFTs() {
192
const fetchNFTMetadata = async ({ address, tokenId }) => {
193
const response = await fetch(`/api/nft/${address}/${tokenId}`);
194
if (!response.ok) throw new Error('Failed to fetch NFT metadata');
195
return response.json();
196
};
197
198
return (
199
<Web3ConfigProvider getNFTMetadata={fetchNFTMetadata}>
200
<MyDApp />
201
</Web3ConfigProvider>
202
);
203
}
204
205
// With signing configuration
206
function AppWithSigning() {
207
const signConfig = {
208
signIn: async (address) => {
209
const message = `Sign in with wallet ${address}`;
210
const signature = await signMessage(message);
211
await authenticateUser(address, signature);
212
},
213
signOut: async () => {
214
await logoutUser();
215
}
216
};
217
218
return (
219
<Web3ConfigProvider sign={signConfig}>
220
<MyDApp />
221
</Web3ConfigProvider>
222
);
223
}
224
```
225
226
### Theme Configuration
227
228
Web3-specific theme extensions for customizing component appearance and behavior.
229
230
```typescript { .api }
231
/**
232
* Extended theme configuration interface for Web3 components
233
*/
234
interface Web3ThemeConfig extends ThemeConfig {
235
web3Components?: {
236
ConnectModal?: Partial<ConnectModalComponentToken>;
237
};
238
}
239
240
interface ConnectModalComponentToken {
241
borderRadius?: number;
242
boxShadow?: string;
243
padding?: number;
244
headerHeight?: number;
245
footerHeight?: number;
246
walletItemPadding?: number;
247
walletItemBorderRadius?: number;
248
qrCodeSize?: number;
249
}
250
251
interface ThemeConfig {
252
token?: {
253
colorPrimary?: string;
254
colorSuccess?: string;
255
colorWarning?: string;
256
colorError?: string;
257
colorInfo?: string;
258
colorBgBase?: string;
259
colorTextBase?: string;
260
fontFamily?: string;
261
fontSize?: number;
262
borderRadius?: number;
263
};
264
components?: {
265
Button?: ComponentToken;
266
Modal?: ComponentToken;
267
Select?: ComponentToken;
268
Input?: ComponentToken;
269
};
270
}
271
```
272
273
**Usage Examples:**
274
275
```typescript
276
import { Web3ConfigProvider } from "@ant-design/web3";
277
278
// Custom Web3 theme
279
const customWeb3Theme = {
280
token: {
281
colorPrimary: '#722ed1', // Purple primary color
282
colorBgBase: '#f5f5f5',
283
borderRadius: 8,
284
},
285
web3Components: {
286
ConnectModal: {
287
borderRadius: 16,
288
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.12)',
289
padding: 32,
290
headerHeight: 64,
291
walletItemPadding: 16,
292
walletItemBorderRadius: 12,
293
qrCodeSize: 200
294
}
295
},
296
components: {
297
Button: {
298
borderRadius: 8,
299
fontSize: 16
300
},
301
Modal: {
302
borderRadius: 12
303
}
304
}
305
};
306
307
function CustomThemedApp() {
308
return (
309
<Web3ConfigProvider theme={customWeb3Theme}>
310
<ConnectButton />
311
<ConnectModal />
312
</Web3ConfigProvider>
313
);
314
}
315
316
// Dark theme configuration
317
const darkWeb3Theme = {
318
token: {
319
colorBgBase: '#141414',
320
colorTextBase: '#ffffff',
321
colorPrimary: '#1890ff',
322
},
323
web3Components: {
324
ConnectModal: {
325
borderRadius: 8,
326
boxShadow: '0 4px 16px rgba(255, 255, 255, 0.1)',
327
padding: 24
328
}
329
}
330
};
331
332
// Dynamic theme switching
333
function DynamicThemedApp() {
334
const [isDark, setIsDark] = useState(false);
335
336
const theme = isDark ? darkWeb3Theme : customWeb3Theme;
337
338
return (
339
<Web3ConfigProvider theme={theme}>
340
<button onClick={() => setIsDark(!isDark)}>
341
Switch to {isDark ? 'Light' : 'Dark'} Theme
342
</button>
343
<MyDApp />
344
</Web3ConfigProvider>
345
);
346
}
347
```
348
349
### Localization Configuration
350
351
Comprehensive localization support for all Web3 components with built-in English and Chinese locales.
352
353
```typescript { .api }
354
/**
355
* Locale configuration for Web3 components
356
*/
357
interface Locale {
358
ConnectButton?: Partial<RequiredLocale['ConnectButton']>;
359
ConnectModal?: Partial<RequiredLocale['ConnectModal']>;
360
NFTCard?: Partial<RequiredLocale['NFTCard']>;
361
Address?: Partial<RequiredLocale['Address']>;
362
TokenSelect?: Partial<RequiredLocale['TokenSelect']>;
363
CryptoInput?: Partial<RequiredLocale['CryptoInput']>;
364
PayPanel?: Partial<RequiredLocale['PayPanel']>;
365
}
366
367
interface RequiredLocale {
368
ConnectButton: {
369
connect: string;
370
disconnect: string;
371
copyAddress: string;
372
copied: string;
373
disconnected: string;
374
walletAddress: string;
375
};
376
ConnectModal: {
377
title: string;
378
walletGuideTitle: string;
379
walletGuideInfos: Array<{
380
title: string;
381
description: string;
382
}>;
383
qrCodePanelTitle: string;
384
qrCodePanelTip: string;
385
qrCodePanelConnecting: string;
386
qrCodePanelConnectingTip: string;
387
};
388
Address: {
389
copied: string;
390
copy: string;
391
};
392
NFTCard: {
393
actionText: string;
394
};
395
TokenSelect: {
396
placeholder: string;
397
};
398
CryptoInput: {
399
placeholder: string;
400
max: string;
401
};
402
PayPanel: {
403
generalTips: string;
404
};
405
}
406
```
407
408
**Usage Examples:**
409
410
```typescript
411
import { Web3ConfigProvider, en_US, zh_CN } from "@ant-design/web3";
412
413
// English locale (default)
414
<Web3ConfigProvider locale={en_US}>
415
<MyDApp />
416
</Web3ConfigProvider>
417
418
// Chinese locale
419
<Web3ConfigProvider locale={zh_CN}>
420
<MyDApp />
421
</Web3ConfigProvider>
422
423
// Custom locale overrides
424
const customLocale = {
425
ConnectButton: {
426
connect: "Connect Your Wallet",
427
disconnect: "Disconnect Wallet",
428
copied: "Address Copied!",
429
copyAddress: "Copy Wallet Address"
430
},
431
ConnectModal: {
432
title: "Choose Your Wallet",
433
qrCodePanelTitle: "Scan QR Code",
434
qrCodePanelTip: "Use your mobile wallet to scan this QR code"
435
},
436
Address: {
437
copy: "Click to copy",
438
copied: "Successfully copied!"
439
}
440
};
441
442
<Web3ConfigProvider locale={customLocale}>
443
<MyDApp />
444
</Web3ConfigProvider>
445
446
// Dynamic locale switching
447
function MultiLanguageApp() {
448
const [locale, setLocale] = useState(en_US);
449
450
return (
451
<Web3ConfigProvider locale={locale}>
452
<select
453
value={locale === en_US ? 'en' : 'zh'}
454
onChange={(e) => setLocale(e.target.value === 'en' ? en_US : zh_CN)}
455
>
456
<option value="en">English</option>
457
<option value="zh">中文</option>
458
</select>
459
<MyDApp />
460
</Web3ConfigProvider>
461
);
462
}
463
464
// Partial locale override
465
const partialLocale = {
466
ConnectButton: {
467
connect: "Link Wallet", // Custom text
468
disconnect: "Unlink Wallet" // Custom text
469
// Other values inherited from default locale
470
}
471
};
472
```
473
474
## Configuration Context
475
476
### ConfigContext
477
478
React context providing Web3 configuration to child components.
479
480
```typescript { .api }
481
/**
482
* React context for Web3 configuration
483
*/
484
const ConfigContext: React.Context<ConfigConsumerProps>;
485
486
interface ConfigConsumerProps extends UniversalWeb3ProviderInterface {
487
locale?: Locale;
488
}
489
```
490
491
**Usage Example:**
492
493
```typescript
494
import { useContext } from 'react';
495
import { ConfigContext } from "@ant-design/web3";
496
497
function MyComponent() {
498
const config = useContext(ConfigContext);
499
500
return (
501
<div>
502
<p>Current account: {config.account?.address}</p>
503
<p>Current chain: {config.chain?.name}</p>
504
<button onClick={() => config.connect?.()}>
505
{config.locale?.ConnectButton?.connect || 'Connect'}
506
</button>
507
</div>
508
);
509
}
510
```
511
512
## Advanced Configuration Patterns
513
514
### Nested Providers
515
516
```typescript
517
// Parent provider with base configuration
518
<Web3ConfigProvider
519
availableWallets={baseWallets}
520
availableChains={baseChains}
521
>
522
{/* Child provider extending parent context */}
523
<Web3ConfigProvider
524
extendsContextFromParent={true}
525
addressPrefix="custom:"
526
locale={customLocale}
527
>
528
<MySpecialComponent />
529
</Web3ConfigProvider>
530
</Web3ConfigProvider>
531
```
532
533
### Environment-Based Configuration
534
535
```typescript
536
const getWeb3Config = () => {
537
if (process.env.NODE_ENV === 'development') {
538
return {
539
availableChains: [...mainnetChains, ...testnetChains],
540
addressPrefix: 'dev:',
541
theme: developmentTheme
542
};
543
}
544
545
return {
546
availableChains: mainnetChains,
547
addressPrefix: '0x',
548
theme: productionTheme
549
};
550
};
551
552
<Web3ConfigProvider {...getWeb3Config()}>
553
<MyDApp />
554
</Web3ConfigProvider>
555
```
556
557
### Testing Configuration
558
559
```typescript
560
// Test configuration with mock providers
561
const testConfig = {
562
account: {
563
address: "0x1234567890abcdef1234567890abcdef12345678",
564
status: "connected"
565
},
566
chain: { id: 1337, name: "Test Network" },
567
connect: jest.fn().mockResolvedValue(mockAccount),
568
disconnect: jest.fn().mockResolvedValue(undefined),
569
switchChain: jest.fn().mockResolvedValue(undefined)
570
};
571
572
<Web3ConfigProvider {...testConfig}>
573
<ComponentUnderTest />
574
</Web3ConfigProvider>
575
```