-
Notifications
You must be signed in to change notification settings - Fork 513
/
README.md
1026 lines (864 loc) · 32.9 KB
/
README.md
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# @web3-onboard/core
This is the core package that contains all of the UI and logic to be able to seamlessly connect user's wallets to your app and track the state of those wallets. Onboard no longer contains any wallet specific code, so wallets need to be passed in upon initialization.
## Installation
Install the core module:
`npm i @web3-onboard/core`
If you would like to support all wallets, then you can install all of the wallet modules:
`npm i @web3-onboard/injected-wallets @web3-onboard/coinbase @web3-onboard/ledger @web3-onboard/trezor @web3-onboard/keepkey @web3-onboard/walletconnect @web3-onboard/web3auth @web3-onboard/torus @web3-onboard/portis @web3-onboard/mew @web3-onboard/gnosis @web3-onboard/magic @web3-onboard/fortmatic @web3-onboard/dcent`
Note:
- MEW wallet currently fails to install on M1 macs
- All wallet modules (except for `injected-wallets`) require extra dependencies and may require polyfilling the node built in modules for the browser. See the [Build Environments](#build-environments) section for more info
- **If using React** you may be interested in checking out the React Hooks package here - https://www.npmjs.com/package/@web3-onboard/react
- **If using Vue** you may be interested in checking out the Vue package here - https://www.npmjs.com/package/@web3-onboard/vue
## Initialization
Onboard needs to be initialized with an options object before the API can be used:
```typescript
type InitOptions {
wallets: WalletInit[]
chains: Chain[]
appMetadata?: AppMetadata
i18n?: i18nOptions
accountCenter?: AccountCenterOptions
apiKey?: string
notify?: Partial<NotifyOptions>
}
```
### Options
**`wallets`**
An array of wallet modules that you would like to be presented to the user to select from when connecting a wallet. A wallet module is an abstraction that allows for easy interaction without needing to know the specifics of how that wallet works and are separate packages that can be included. A list of wallet module packages that can be installed can be found [here](../).
**`chains`**
An array of Chains that your app supports:
```typescript
type Chain = {
id: ChainId // hex encoded string, eg '0x1' for Ethereum Mainnet
namespace?: 'evm' // string indicating chain namespace. Defaults to 'evm' but will allow other chain namespaces in the future
rpcUrl: string // used for network requests
label: string // used for display, eg Ethereum Mainnet
token: TokenSymbol // the native token symbol, eg ETH, BNB, MATIC
color?: string // the color used to represent the chain and will be used as a background for the icon
icon?: string // the icon to represent the chain
publicRpcUrl?: string // an optional public RPC used when adding a new chain config to the wallet
blockExplorerUrl?: string // also used when adding a new config to the wallet
}
```
**`appMetadata`**
An object that defines your app:
```typescript
type AppMetadata = {
// app name
name: string
// SVG icon string, with height or width (whichever is larger) set to 100% or a valid image URL
// note: if using an emoji make sure to send base64 string
icon: string
// Optional wide format logo (ie icon and text) to be displayed in the sidebar of connect modal. Defaults to icon if not provided
logo?: string
// description of app
description?: string
// url to a getting started guide for app
gettingStartedGuide?: string
// url that points to more information about app
explore?: string
// if your app only supports injected wallets and when no injected wallets detected, recommend the user to install some
recommendedInjectedWallets?: RecommendedInjectedWallets[]
}
type RecommendedInjectedWallets = {
name: string // display name
url: string // link to download wallet
}
```
**`i18n`**
An object that defines the display text for different locales. Can also be used to override the default text. To override the default text, pass in a object for the `en` locale.
```typescript
type Locale = string // eg 'en', 'es'
type i18nOptions = Record<Locale, i18n>
```
To see a list of all of the text values that can be internationalized or replaced, check out the [default en file](src/i18n/en.json).
Onboard is using the [ICU syntax](https://formatjs.io/docs/core-concepts/icu-syntax/) for formatting under the hood.
**`accountCenter`**
An object that defines whether the account center UI (default and minimal) is enabled and it's position on the screen. Currently the account center is enabled for both desktop and mobile devices.
```typescript
export type AccountCenter = {
enabled: boolean
position?: AccountCenterPosition // default: 'topRight'
expanded?: boolean // default: true
minimal?: boolean // enabled by default for mobile
}
export type AccountCenterOptions = {
desktop: Omit<AccountCenter, 'expanded'>
mobile: Omit<AccountCenter, 'expanded'>
}
type AccountCenterPosition =
| 'topRight'
| 'bottomRight'
| 'bottomLeft'
| 'topLeft'
```
**`notify`**
Notify provides by default transaction notifications for all connected wallets on the current blockchain. When switching chains the previous chain listeners remain active for 60 seconds to allow capture and report of an remaining transactions that may be in flight.
By default transaction notifications are captured if a DAppID is provided in the Onboard config along with the Account Center being enabled.
An object that defines whether transaction notifications will display (defaults to true if an API key is provided). This object contains an `enabled` flag prop and an optional `transactionHandler` which is a callback that can disable or allow customizations of notifications.
Currently notifications are positioned in the same location as the account center (either below, if the Account Center is positioned along the top, or above if positioned on the bottom of the view).
The `transactionHandler` can react off any property of the Ethereum TransactionData returned to the callback from the event (see console.log in example init). In turn, it can return a Custom `Notification` object to define the verbiage, styling, or add functionality:
- `Notification.message` - to completely customize the message shown
- `Notification.eventCode` - handle codes in your own way - see codes here under the notify prop [default en file here](src/i18n/en.json)
- `Notification.type` - icon type displayed (see `NotificationType` below for options)
- `Notification.autoDismiss` - time (in ms) after which the notification will be dismissed. If set to `0` the notification will remain on screen until the user dismisses the notification, refreshes the page or navigates away from the site with the notifications
- `Notification.link` - add link to the transaction hash. For instance, a link to the transaction on etherscan
- `Notification.onClick()` - onClick handler for when user clicks the notification element
Notify can also be styled by using the CSS variables found below. These are setup to allow maximum customization with base styling variables setting the global theme (i.e. `--onboard-grey-600`) along with more precise component level styling variables available (`--notify-onboard-grey-600`) with the latter taking precedent if defined
If notifications are enabled the notifications can be handled through onboard app state as seen below.
```javascript
const wallets = onboard.state.select('notifications')
const { unsubscribe } = wallets.subscribe(update =>
console.log('transaction notifications: ', update)
)
// unsubscribe when updates are no longer needed
unsubscribe()
```
```typescript
export type NotifyOptions = {
desktop: Notify
mobile: Notify
}
export type Notify = {
enabled: boolean // default: true
/**
* Callback that receives all transaction events
* Return a custom notification based on the event
* Or return false to disable notification for this event
* Or return undefined for a default notification
*/
transactionHandler?: (
event: EthereumTransactionData
) => TransactionHandlerReturn
position: CommonPositions
}
export type CommonPositions =
| 'topRight'
| 'bottomRight'
| 'bottomLeft'
| 'topLeft'
export type TransactionHandlerReturn = CustomNotification | boolean | void
export type CustomNotification = Partial<Omit<Notification, 'id' | 'startTime'>>
export type Notification = {
id: string
key: string
type: NotificationType
network: Network
startTime?: number
eventCode: string
message: string
autoDismiss: number
link?: string
onClick?: (event: Event) => void
}
export type NotificationType = 'pending' | 'success' | 'error' | 'hint'
export declare type Network =
| 'main'
| 'testnet'
| 'ropsten'
| 'rinkeby'
| 'goerli'
| 'kovan'
| 'xdai'
| 'bsc-main'
| 'matic-main'
| 'fantom-main'
| 'matic-mumbai'
| 'local'
export interface UpdateNotification {
(notificationObject: CustomNotification): {
dismiss: () => void
update: UpdateNotification
}
}
```
### Initialization Example
Putting it all together, here is an example initialization with the injected wallet modules:
```javascript
import Onboard from '@web3-onboard/core'
import injectedModule from '@web3-onboard/injected-wallets'
const injected = injectedModule()
const onboard = Onboard({
wallets: [injected],
chains: [
{
id: '0x1',
token: 'ETH',
label: 'Ethereum Mainnet',
rpcUrl: `https://mainnet.infura.io/v3/${INFURA_ID}`
},
{
id: '0x3',
token: 'tROP',
label: 'Ethereum Ropsten Testnet',
rpcUrl: `https://ropsten.infura.io/v3/${INFURA_ID}`
},
{
id: '0x4',
token: 'rETH',
label: 'Ethereum Rinkeby Testnet',
rpcUrl: `https://rinkeby.infura.io/v3/${INFURA_ID}`
},
{
id: '0x38',
token: 'BNB',
label: 'Binance Smart Chain',
rpcUrl: 'https://bsc-dataseed.binance.org/'
},
{
id: '0x89',
token: 'MATIC',
label: 'Matic Mainnet',
rpcUrl: 'https://matic-mainnet.chainstacklabs.com'
},
{
id: '0xfa',
token: 'FTM',
label: 'Fantom Mainnet',
rpcUrl: 'https://rpc.ftm.tools/'
}
],
appMetadata: {
name: 'Token Swap',
icon: myIcon, // svg string icon
logo: myLogo, // svg string logo
description: 'Swap tokens for other tokens',
recommendedInjectedWallets: [
{ name: 'MetaMask', url: 'https://metamask.io' },
{ name: 'Coinbase', url: 'https://wallet.coinbase.com/' }
]
},
apiKey: 'xxx387fb-bxx1-4xxc-a0x3-9d37e426xxxx'
notify: {
desktop: {
enabled: true,
transactionHandler: transaction => {
console.log({ transaction })
if (transaction.eventCode === 'txPool') {
return {
type: 'success',
message: 'Your transaction from #1 DApp is in the mempool',
}
}
},
position: 'bottomLeft'
},
mobile: {
enabled: true,
transactionHandler: transaction => {
console.log({ transaction })
if (transaction.eventCode === 'txPool') {
return {
type: 'success',
message: 'Your transaction from #1 DApp is in the mempool',
}
}
},
position: 'topRight'
}
},
accountCenter: {
desktop: {
position: 'topRight',
enabled: true,
minimal: true
},
mobile: {
position: 'topRight',
enabled: true,
minimal: true
}
},
i18n: {
en: {
connect: {
selectingWallet: {
header: 'custom text header'
}
},
notify: {
transaction: {
txStuck: 'custom text for this notification event'
},
watched: {
// Any words in brackets can be re-ordered or removed to fit your dapps desired verbiage
"txPool": "Your account is {verb} {formattedValue} {asset} {preposition} {counterpartyShortened}"
}
}
},
es: {
transaction: {
txRequest: 'Su transacción está esperando que confirme'
}
}
}
})
```
## Connecting a Wallet
To initiate a user to select and connect a wallet you can call the `connectWallet` function on an initialized Onboard instance. It will return a `Promise` that will resolve when the user either successfully connects a wallet, or when they dismiss the UI. The resolved value from the promise will be the latest state of the `wallets` array. The order of the wallets array is last to first, so the most recently selected wallet will be the first item in the array and can be thought of as the "primary wallet". If no wallet was selected, then the `wallets` array will have the same state as it had before calling `connectWallet`.
### Example
```javascript
async function connectWallet() {
const wallets = await onboard.connectWallet()
console.log(wallets)
}
connectWallet()
```
### Auto Selecting a Wallet
A common UX pattern is to remember the wallet(s) that a user has previously connected by storing them in localStorage and then automatically selecting them for the user next time they visit your app.
You could enable this in your app by first syncing the `wallets` array to localStorage:
```javascript
const walletsSub = onboard.state.select('wallets')
const { unsubscribe } = walletsSub.subscribe(wallets => {
const connectedWallets = wallets.map(({ label }) => label)
window.localStorage.setItem(
'connectedWallets',
JSON.stringify(connectedWallets)
)
})
// Don't forget to unsubscribe when your app or component un mounts to prevent memory leaks
// unsubscribe()
```
Now that you have the most recent wallets connected saved in local storage, you can auto select those wallet(s) when your app loads:
```javascript
const previouslyConnectedWallets = JSON.parse(
window.localStorage.getItem('connectedWallets')
)
if (previouslyConnectedWallets) {
// Connect the most recently connected wallet (first in the array)
await onboard.connectWallet({ autoSelect: previouslyConnectedWallets[0] })
// You can also auto connect "silently" and disable all onboard modals to avoid them flashing on page load
await onboard.connectWallet({
autoSelect: { label: previouslyConnectedWallets[0], disableModals: true }
})
// OR - loop through and initiate connection for all previously connected wallets
// note: This UX might not be great as the user may need to login to each wallet one after the other
// for (walletLabel in previouslyConnectedWallets) {
// await onboard.connectWallet({ autoSelect: walletLabel })
// }
}
```
## Disconnecting a Wallet
A wallet can be disconnected, which will cleanup any background operations the wallet may be doing and will also remove it from the Onboard `wallets` array:
```javascript
// disconnect the first wallet in the wallets array
const [primaryWallet] = onboard.state.get().wallets
await onboard.disconnectWallet({ label: primaryWallet.label })
```
The `disconnectWallet` method takes the `wallet.label` value and returns a `Promise` that resolves to the current state of the `wallets` array.
## State
Onboard currently keeps track of the following state:
- `wallets`: The wallets connected to Onboard
- `chains`: The chains that Onboard has been initialized with
- `accountCenter`: The current state of the account center UI
- `walletModules`: The wallet modules that are currently set and will be rendered in the wallet selection modal
```typescript
type AppState = {
wallets: WalletState[]
chains: Chain[]
accountCenter: AccountCenter
walletModules: WalletModule[]
locale: Locale
notify: Notify
notifications: Notification[]
}
type Chain {
namespace?: 'evm'
id: ChainId
rpcUrl: string
label: string
token: TokenSymbol
color?: string
icon?: string
}
type WalletState = {
label: string
icon: string
provider: EIP1193Provider
accounts: Account[]
chains: ConnectedChain[]
instance?: unknown
}
type Account = {
address: string
ens: {
name?: string
avatar?: string
contentHash?: string
getText?: (key: string) => Promise<string | undefined>
}
balance: Record<TokenSymbol, string>
}
type ConnectedChain = {
namespace: 'evm'
id: ChainId
}
type ChainId = string
type TokenSymbol = string
type AccountCenter = {
enabled: boolean
position: AccountCenterPosition
expanded: boolean
minimal: boolean
}
type AccountCenterPosition =
| 'topRight'
| 'bottomRight'
| 'bottomLeft'
| 'topLeft'
type WalletModule {
label: string
getIcon: () => Promise<string>
getInterface: (helpers: GetInterfaceHelpers) => Promise<WalletInterface>
}
```
### Get Current State
The current state of Onboard can be accessed at any time using the `state.get()` method:
```javascript
const currentState = onboard.state.get()
```
### Subscribe to State Updates
State can also be subscribed to using the `state.select()` method. The `select` method will return an [RXJS Observable](https://rxjs.dev/guide/observable). Understanding of RXJS observables is not necessary to subscribe to state updates, but allows for composable functionality if wanted. The key point to understand is that if you subscribe for updates, remember to unsubscribe when you are finished to prevent memory leaks.
To subscribe to all state updates, call the `select` method with no arguments:
```javascript
const state = onboard.state.select()
const { unsubscribe } = state.subscribe(update =>
console.log('state update: ', update)
)
// remember to unsubscribe when updates are no longer needed
// unsubscribe()
```
Specific top level slices of state can be subscribed to. For example you may want to just subscribe to receive updates to the `wallets` array only:
```javascript
const wallets = onboard.state.select('wallets')
const { unsubscribe } = wallets.subscribe(update =>
console.log('wallets update: ', update)
)
// unsubscribe when updates are no longer needed
unsubscribe()
```
### Actions to Modify State
A limited subset of internal actions are exposed to update the Onboard state.
**`setWalletModules`**
For updating the wallets that are displayed in the wallet selection modal. This can be used if the wallets you want to support is conditional on another user action within your app. The `setWalletModules` action is called with an updated array of wallets (the same wallets that are passed in on initialization)
```typescript
import Onboard from '@web3-onboard/core'
import injectedModule from '@web3-onboard/injected-wallets'
import ledgerModule from '@web3-onboard/ledger'
import trezorModule from '@web3-onboard/trezor'
const injected = injectedModule()
const ledger = ledgerModule()
const trezor = trezorModule({
email: '<EMAIL_CONTACT>',
appUrl: '<APP_URL>'
})
// initialize with injected and hardware wallets
const onboard = Onboard({
wallets: [injected, trezor, ledger],
chains: [
{
id: '0x1',
token: 'ETH',
label: 'Ethereum Mainnet',
rpcUrl: `https://mainnet.infura.io/v3/${INFURA_ID}`
}
]
})
// then after a user action, you may decide to only display hardware wallets on the next call to onboard.connectWallet
onboard.state.actions.setWalletModules([ledger, trezor])
```
**`updateBalances`**
You may decide to get updated balances for connected wallets after a user action by calling the `updatedBalances` function, which expects a conditional array of addresses:
```javascript
onboard.state.actions.updateBalances() // update all balances for all connected addresses
onboard.state.actions.updateBalances(['0xfdadfadsadsadsadasdsa']) // update balance for one address
onboard.state.actions.updateBalances([
'0xfdadfadsadsadsadasdsa',
'0xfdsafdsfdsfdsfds'
]) // update balance for two addresses
```
**`setLocale`**
Onboard will automatically detect the browser locale at runtime, but if you would like to update it manually you can call the `setLocale` function:
```javascript
onboard.state.actions.setLocal('fr_FR')
```
**`updateNotify`**
If you need to update your notify configuration after initialization, you can do that by calling the `updateNotify` function:
```javascript
onboard.state.actions.updateNotify({
desktop: {
enabled: true,
transactionHandler: transaction => {
console.log({ transaction })
if (transaction.eventCode === 'txPool') {
return {
type: 'success',
message: 'Your transaction from #1 DApp is in the mempool'
}
}
},
position: 'bottomLeft'
},
mobile: {
enabled: true,
transactionHandler: transaction => {
console.log({ transaction })
if (transaction.eventCode === 'txPool') {
return {
type: 'success',
message: 'Your transaction from #1 DApp is in the mempool'
}
}
},
position: 'topRight'
}
})
```
**`customNotification`**
Notify can be used to deliver custom DApp notifications by passing a `CustomNotification` object to the `customNotification` action. This will return an `UpdateNotification` type.
This `UpdateNotification` will return an `update` function that can be passed a new `CustomNotification` to update the existing notification.
The `customNotification` method also returns a `dismiss` method that is called without any parameters to dismiss the notification.
```typescript
const { update, dismiss } = onboard.state.actions.customNotification({
type: 'pending',
message: 'This is a custom DApp pending notification to use however you want',
autoDismiss: 0
})
setTimeout(
() =>
update({
eventCode: 'dbUpdateSuccess',
message: 'Updated status for custom notification',
type: 'success',
autoDismiss: 8000
}),
4000
)
```
**`updateAccountCenter`**
If you need to update your Account Center configuration after initialization, you can call the `updateAccountCenter` function with the new configuration
```typescript
onboard.state.actions.updateAccountCenter({
desktop: {
position: 'topRight',
enabled: true,
minimal: true
},
mobile: {
position: 'topRight',
enabled: true,
minimal: true
}
})
```
**`setPrimaryWallet`**
The primary wallet (first in the list of connected wallets) and primary account (first in the list of connected accounts for a wallet) can be set by using the `setPrimaryWallet` function. The wallet that is to be set needs to be passed in for the first parameter and if you would like to set the primary account, the address of that account also needs to be passed in:
```typescript
// set the second wallet in the wallets array as the primary
onboard.state.actions.setPrimaryWallet(wallets[1])
// set the second wallet in the wallets array as the primary wallet
// as well as setting the third account in that wallet as the primary account
onboard.state.actions.setPrimaryWallet(
wallets[1],
wallets[1].accounts[2].address
)
```
## Setting the User's Chain/Network
When initializing Onboard you define a list of chains/networks that your app supports. If you would like to prompt the user to switch to one of those chains, you can use the `setChain` method on an initialized instance of Onboard:
```typescript
type SetChain = (options: SetChainOptions) => Promise<boolean>
type SetChainOptions = {
chainId: string // hex encoded string
chainNamespace?: 'evm' // defaults to 'evm' (currently the only valid value, but will add more in future updates)
wallet?: string // the wallet.label of the wallet to set chain
}
const success = await onboard.setChain({ chainId: '0x89' })
```
The `setChain` methods takes an options object with a `chainId` property hex encoded string for the chain id to switch to. The chain id must be one of the chains that Onboard was initialized with. If the wallet supports programatically adding and switching the chain, then the user will be prompted to do so, if not, then a modal will be displayed indicating to the user that they need to switch chains to continue. The `setChain` method returns a promise that resolves when either the user has confirmed the chain switch, or has dismissed the modal and resolves with a boolean indicating if the switch network was successful or not. The `setChain` method will by default switch the first wallet (the most recently connected) in the `wallets` array. A specific wallet can be targeted by passing in the `wallet.label` in the options object as the `wallet` parameter.
## Custom Styling
The Onboard styles can customized via [CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties). The following properties and their default properties can be customized by adding these variables to the `:root` in your CSS file:
```css
:root {
/* CUSTOMIZE THE COLOR PALLETTE */
--onboard-white: white;
--onboard-black: black;
--onboard-primary-1: #2f80ed;
--onboard-primary-100: #eff1fc;
--onboard-primary-200: #d0d4f7;
--onboard-primary-300: #b1b8f2;
--onboard-primary-400: #929bed;
--onboard-primary-500: #6370e5;
--onboard-primary-600: #454ea0;
--onboard-primary-700: #323873;
--onboard-gray-100: #ebebed;
--onboard-gray-200: #c2c4c9;
--onboard-gray-300: #999ca5;
--onboard-gray-400: #707481;
--onboard-gray-500: #33394b;
--onboard-gray-600: #242835;
--onboard-gray-700: #1a1d26;
--onboard-success-100: #d1fae3;
--onboard-success-200: #baf7d5;
--onboard-success-300: #a4f4c6;
--onboard-success-400: #8df2b8;
--onboard-success-500: #5aec99;
--onboard-success-600: #18ce66;
--onboard-success-700: #129b4d;
--onboard-danger-100: #ffe5e6;
--onboard-danger-200: #ffcccc;
--onboard-danger-300: #ffb3b3;
--onboard-danger-400: #ff8080;
--onboard-danger-500: #ff4f4f;
--onboard-danger-600: #cc0000;
--onboard-danger-700: #660000;
--onboard-warning-100: #ffefcc;
--onboard-warning-200: #ffe7b3;
--onboard-warning-300: #ffd780;
--onboard-warning-400: #ffc74c;
--onboard-warning-500: #ffaf00;
--onboard-warning-600: #cc8c00;
--onboard-warning-700: #664600;
/* CUSTOMIZE ACCOUNT CENTER STACK POSITIONING*/
--account-center-z-index
/* CUSTOMIZE SECTIONS OF THE CONNECT MODAL */
--onboard-connect-content-width
--onboard-connect-content-height
--onboard-wallet-columns
--onboard-connect-sidebar-background
--onboard-connect-sidebar-color
--onboard-connect-sidebar-progress-background
--onboard-connect-sidebar-progress-color
--onboard-connect-header-background
--onboard-connect-header-color
--onboard-main-scroll-container-background
--onboard-link-color
--onboard-close-button-background
--onboard-close-button-color
--onboard-checkbox-background
--onboard-checkbox-color
--onboard-wallet-button-background
--onboard-wallet-button-background-hover
--onboard-wallet-button-color
--onboard-wallet-button-border-color
--onboard-wallet-button-border-radius
--onboard-wallet-button-box-shadow
--onboard-wallet-app-icon-border-color
/* CUSTOMIZE THE CONNECT MODAL */
--onboard-modal-border-radius
--onboard-modal-backdrop
--onboard-modal-box-shadow
/* CUSTOMIZE THE ACTION REQUIRED MODAL */
--onboard-action-required-modal-background
/* FONTS */
--onboard-font-family-normal: Sofia Pro;
--onboard-font-family-semibold: Sofia Pro Semibold;
--onboard-font-family-light: Sofia Pro Light;
--onboard-font-size-1: 3rem;
--onboard-font-size-2: 2.25rem;
--onboard-font-size-3: 1.5rem;
--onboard-font-size-4: 1.25rem;
--onboard-font-size-5: 1rem;
--onboard-font-size-6: 0.875rem;
--onboard-font-size-7: 0.75rem;
/* SPACING */
--onboard-spacing-1: 3rem;
--onboard-spacing-2: 2rem;
--onboard-spacing-3: 1.5rem;
--onboard-spacing-4: 1rem;
--onboard-spacing-5: 0.5rem;
/* BORDER RADIUS */
--onboard-border-radius-1: 24px;
--onboard-border-radius-2: 20px;
--onboard-border-radius-3: 16px;
/* SHADOWS */
--onboard-shadow-0: none;
--onboard-shadow-1: 0px 4px 12px rgba(0, 0, 0, 0.1);
--onboard-shadow-2: inset 0px -1px 0px rgba(0, 0, 0, 0.1);
/* MAIN MODAL POSITIONING */
--onboard-modal-z-index
--onboard-modal-top
--onboard-modal-bottom
--onboard-modal-right
--onboard-modal-left
/* HD WALLET ACCOUNT SELECT MODAL POSITIONING */
--onboard-account-select-modal-z-index
--onboard-account-select-modal-top
--onboard-account-select-modal-bottom
--onboard-account-select-modal-right
--onboard-account-select-modal-left
/* MAGIC WALLET MODAL POSITIONING */
--onboard-login-modal-z-index
--onboard-login-modal-top
--onboard-login-modal-bottom
--onboard-login-modal-right
--onboard-login-modal-left
/* HARDWARE WALLET STYLES */
/* *if not set will fallback to variables with `--onboard` prefix shown above */
/* COLORS */
--account-select-modal-white: white;
--account-select-modal-black: black;
--account-select-modal-primary-100: #eff1fc;
--account-select-modal-primary-200: #d0d4f7;
--account-select-modal-primary-300: #b1b8f2;
--account-select-modal-primary-500: #6370e5;
--account-select-modal-primary-600: #454ea0;
--account-select-modal-gray-100: #ebebed;
--account-select-modal-gray-200: #c2c4c9;
--account-select-modal-gray-300: #999ca5;
--account-select-modal-gray-500: #33394b;
--account-select-modal-gray-700: #1a1d26;
--account-select-modal-danger-500: #ff4f4f;
/* FONTS */
--account-select-modal-font-family-normal: Sofia Pro;
--account-select-modal-font-family-light: Sofia Pro Light;
--account-select-modal-font-size-5: 1rem;
--account-select-modal-font-size-7: .75rem;
--account-select-modal-font-line-height-1: 24px;
/* SPACING */
--account-select-modal-margin-4: 1rem;
--account-select-modal-margin-5: 0.5rem;
/* notify STYLES */
--notify-onboard-font-family-normal
--notify-onboard-font-size-5
--notify-onboard-gray-300
--notify-onboard-gray-600
--notify-onboard-border-radius
--notify-onboard-font-size-7
--notify-onboard-font-size-6
--notify-onboard-line-height-4
--notify-onboard-primary-100
--notify-onboard-primary-400
--notify-onboard-main-padding
}
```
## Build Environments
Many of the wallet modules require dependencies that are not normally included in browser builds (namely the node builtin modules such as `crypto`, `buffer`, `util` etc). If you are having build issues you can try the following bundler configs to resolve these dependency issues:
### Webpack 4
Everything should just work since the node built-ins are automatically bundled in v4
### Webpack 5
You'll need to add some dev dependencies with the following command:
`npm i --save-dev assert buffer crypto-browserify stream-http https-browserify os-browserify process stream-browserify util`
Then add the following to your `webpack.config.js` file:
```javascript
const webpack = require('webpack')
module.exports = {
resolve: {
alias: {
assert: 'assert',
buffer: 'buffer',
crypto: 'crypto-browserify',
http: 'stream-http',
https: 'https-browserify',
os: 'os-browserify/browser',
process: 'process/browser',
stream: 'stream-browserify',
util: 'util'
}
},
experiments: {
asyncWebAssembly: true
},
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer']
})
]
}
```
#### If using create-react-app
[CRACO](https://www.npmjs.com/package/@craco/craco) provides an easy way to override webpack config which is obfuscated in Create React App built applications.
The above webpack 5 example can be used in the `craco.config.js` file at the root level in this case.
### SvelteKit
Add the following dev dependencies:
`npm i --save-dev rollup-plugin-polyfill-node`
Then add the following to your `svelte.config.js` file:
```javascript
import adapter from '@sveltejs/adapter-auto'
import preprocess from 'svelte-preprocess'
import nodePolyfills from 'rollup-plugin-polyfill-node'
const MODE = process.env.NODE_ENV
const development = MODE === 'development'
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: preprocess(),
kit: {
adapter: adapter(),
vite: {
plugins: [
development &&
nodePolyfills({
include: [
'node_modules/**/*.js',
new RegExp('node_modules/.vite/.*js')
],
http: true,
crypto: true
})
],
resolve: {
alias: {
crypto: 'crypto-browserify',
stream: 'stream-browserify',
assert: 'assert'
}
},
build: {
rollupOptions: {
plugins: [nodePolyfills({ crypto: true, http: true })]
},
commonjsOptions: {
transformMixedEsModules: true
}
}
}
}
}
export default config
```
### Vite
Add the following dev dependencies:
`npm i --save-dev rollup-plugin-polyfill-node`
Then add the following to your `vite.config.js` file:
```javascript
import nodePolyfills from 'rollup-plugin-polyfill-node'
const MODE = process.env.NODE_ENV
const development = MODE === 'development'
export default {
// other config options
plugins: [
development &&
nodePolyfills({
include: [
'node_modules/**/*.js',
new RegExp('node_modules/.vite/.*js')
],
http: true,
crypto: true
})
],
resolve: {