-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathWalletProvider.tsx
366 lines (346 loc) · 12.6 KB
/
WalletProvider.tsx
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
import { ComponentWithAs, IconProps } from '@chakra-ui/react'
import { HDWallet, Keyring } from '@shapeshiftoss/hdwallet-core'
import { MetaMaskHDWallet } from '@shapeshiftoss/hdwallet-metamask'
import { PortisHDWallet } from '@shapeshiftoss/hdwallet-portis'
import { getConfig } from 'config'
import findIndex from 'lodash/findIndex'
import React, { useCallback, useEffect, useMemo, useReducer } from 'react'
import { ActionTypes, WalletActions } from './actions'
import { SUPPORTED_WALLETS } from './config'
import { useKeepKeyEventHandler } from './KeepKey/hooks/useKeepKeyEventHandler'
import { useKeyringEventHandler } from './KeepKey/hooks/useKeyringEventHandler'
import { PinMatrixRequestType } from './KeepKey/KeepKeyTypes'
import { KeyManager } from './KeyManager'
import { clearLocalWallet, getLocalWalletDeviceId, getLocalWalletType } from './local-wallet'
import { useNativeEventHandler } from './NativeWallet/hooks/useNativeEventHandler'
import { IWalletContext, WalletContext } from './WalletContext'
import { WalletViewsRouter } from './WalletViewsRouter'
type GenericAdapter = {
initialize: (...args: any[]) => Promise<any>
pairDevice: (...args: any[]) => Promise<HDWallet>
}
export type Adapters = Map<KeyManager, GenericAdapter>
export type WalletInfo = {
name: string
icon: ComponentWithAs<'svg', IconProps>
deviceId: string
meta?: { label?: string; address?: string }
}
export interface InitialState {
keyring: Keyring
adapters: Adapters | null
wallet: HDWallet | null
type: KeyManager | null
initialRoute: string | null
walletInfo: WalletInfo | null
isConnected: boolean
modal: boolean
isLoadingLocalWallet: boolean
deviceId: string
noBackButton: boolean
keepKeyPinRequestType: PinMatrixRequestType | null
}
const initialState: InitialState = {
keyring: new Keyring(),
adapters: null,
wallet: null,
type: null,
initialRoute: null,
walletInfo: null,
isConnected: false,
modal: false,
isLoadingLocalWallet: false,
deviceId: '',
noBackButton: false,
keepKeyPinRequestType: null,
}
const reducer = (state: InitialState, action: ActionTypes) => {
switch (action.type) {
case WalletActions.SET_ADAPTERS:
return { ...state, adapters: action.payload }
case WalletActions.SET_WALLET:
const stateData = {
...state,
wallet: action.payload.wallet,
walletInfo: {
name: action?.payload?.name,
icon: action?.payload?.icon,
deviceId: action?.payload?.deviceId,
meta: {
label: action.payload.meta?.label ?? '',
address: (action.payload.wallet as MetaMaskHDWallet | PortisHDWallet).ethAddress ?? '',
},
},
}
return stateData
case WalletActions.SET_IS_CONNECTED:
return { ...state, isConnected: action.payload }
case WalletActions.SET_CONNECTOR_TYPE:
return { ...state, type: action.payload }
case WalletActions.SET_INITIAL_ROUTE:
return { ...state, initialRoute: action.payload }
case WalletActions.SET_WALLET_MODAL:
const newState = { ...state, modal: action.payload }
// If we're closing the modal, then we need to forget the route we were on
// Otherwise the connect button for last wallet we clicked on won't work
if (action.payload === false && state.modal === true) {
newState.initialRoute = '/'
newState.isLoadingLocalWallet = false
newState.noBackButton = false
newState.keepKeyPinRequestType = null
}
return newState
case WalletActions.NATIVE_PASSWORD_OPEN:
return {
...state,
modal: action.payload.modal,
type: KeyManager.Native,
noBackButton: state.isLoadingLocalWallet,
deviceId: action.payload.deviceId,
initialRoute: '/native/enter-password',
}
case WalletActions.OPEN_KEEPKEY_PIN:
return {
...state,
modal: true,
type: KeyManager.KeepKey,
noBackButton: true,
deviceId: action.payload.deviceId,
keepKeyPinRequestType: action.payload.pinRequestType ?? null,
initialRoute: '/keepkey/enter-pin',
}
case WalletActions.OPEN_KEEPKEY_PASSPHRASE:
return {
...state,
modal: true,
type: KeyManager.KeepKey,
noBackButton: true,
deviceId: action.payload.deviceId,
initialRoute: '/keepkey/passphrase',
}
case WalletActions.SET_LOCAL_WALLET_LOADING:
return { ...state, isLoadingLocalWallet: action.payload }
case WalletActions.RESET_STATE:
return {
...state,
wallet: null,
walletInfo: null,
isConnected: false,
type: null,
initialRoute: null,
isLoadingLocalWallet: false,
noBackButton: false,
keepKeyPinRequestType: null,
}
default:
return state
}
}
const getInitialState = () => {
const localWalletType = getLocalWalletType()
const localWalletDeviceId = getLocalWalletDeviceId()
if (localWalletType && localWalletDeviceId) {
/**
* set isLoadingLocalWallet->true to bypass splash screen
*/
return {
...initialState,
isLoadingLocalWallet: true,
}
}
return initialState
}
export const WalletProvider = ({ children }: { children: React.ReactNode }): JSX.Element => {
const [state, dispatch] = useReducer(reducer, getInitialState())
useKeyringEventHandler(state)
useKeepKeyEventHandler(state, dispatch)
useNativeEventHandler(state, dispatch)
useEffect(() => {
if (state.keyring) {
;(async () => {
const adapters: Adapters = new Map()
let options: undefined | { portisAppId: string }
for (const wallet of Object.values(KeyManager)) {
try {
options =
wallet === 'portis'
? { portisAppId: getConfig().REACT_APP_PORTIS_DAPP_ID }
: undefined
const adapter = SUPPORTED_WALLETS[wallet].adapter.useKeyring(state.keyring, options)
// useKeyring returns the instance of the adapter. We'll keep it for future reference.
await adapter.initialize()
adapters.set(wallet, adapter)
} catch (e) {
console.error('Error initializing HDWallet adapters', e)
}
}
dispatch({ type: WalletActions.SET_ADAPTERS, payload: adapters })
})()
}
}, [state.keyring])
const connect = useCallback(async (type: KeyManager) => {
dispatch({ type: WalletActions.SET_CONNECTOR_TYPE, payload: type })
const routeIndex = findIndex(SUPPORTED_WALLETS[type]?.routes, ({ path }) =>
String(path).endsWith('connect'),
)
if (routeIndex > -1) {
dispatch({
type: WalletActions.SET_INITIAL_ROUTE,
payload: SUPPORTED_WALLETS[type].routes[routeIndex].path as string,
})
}
}, [])
const create = useCallback(async (type: KeyManager) => {
dispatch({ type: WalletActions.SET_CONNECTOR_TYPE, payload: type })
const routeIndex = findIndex(SUPPORTED_WALLETS[type]?.routes, ({ path }) =>
String(path).endsWith('create'),
)
if (routeIndex > -1) {
dispatch({
type: WalletActions.SET_INITIAL_ROUTE,
payload: SUPPORTED_WALLETS[type].routes[routeIndex].path as string,
})
}
}, [])
const disconnect = useCallback(() => {
/**
* in case of KeepKey placeholder wallet,
* the disconnect function is undefined
*/
state.wallet?.disconnect?.()
dispatch({ type: WalletActions.RESET_STATE })
clearLocalWallet()
}, [state.wallet])
useEffect(() => {
const localWalletType = getLocalWalletType()
const localWalletDeviceId = getLocalWalletDeviceId()
if (localWalletType && localWalletDeviceId && state.adapters) {
;(async () => {
if (state.adapters?.has(localWalletType)) {
switch (localWalletType) {
case KeyManager.Native:
const localNativeWallet = await state.adapters
.get(KeyManager.Native)
?.pairDevice(localWalletDeviceId)
if (localNativeWallet) {
/**
* This will eventually fire an event, which the native wallet
* password modal will be shown
*/
await localNativeWallet.initialize()
} else {
disconnect()
}
break
case KeyManager.KeepKey:
try {
const localKeepKeyWallet = state.keyring.get(localWalletDeviceId)
/**
* if localKeepKeyWallet is not null it means
* KeepKey remained connected during the reload
*/
if (localKeepKeyWallet) {
const { name, icon } = SUPPORTED_WALLETS[KeyManager.KeepKey]
const deviceId = await localKeepKeyWallet.getDeviceID()
// This gets the firmware version needed for some KeepKey "supportsX" functions
await localKeepKeyWallet.getFeatures()
// Show the label from the wallet instead of a generic name
const label = (await localKeepKeyWallet.getLabel()) || name
await localKeepKeyWallet.initialize()
dispatch({
type: WalletActions.SET_WALLET,
payload: {
wallet: localKeepKeyWallet,
name: label,
icon,
deviceId,
meta: { label },
},
})
dispatch({ type: WalletActions.SET_IS_CONNECTED, payload: true })
} else {
/**
* The KeepKey wallet is disconnected,
* because the accounts are not persisted, the app cannot load without getting pub keys from the
* wallet.
*/
// TODO(ryankk): If persist is turned back on, we can restore the previous deleted code.
disconnect()
}
} catch (e) {
disconnect()
}
dispatch({ type: WalletActions.SET_LOCAL_WALLET_LOADING, payload: false })
break
case KeyManager.Portis:
const localPortisWallet = await state.adapters.get(KeyManager.Portis)?.pairDevice()
if (localPortisWallet) {
const { name, icon } = SUPPORTED_WALLETS[KeyManager.Portis]
try {
await localPortisWallet.initialize()
const deviceId = await localPortisWallet.getDeviceID()
dispatch({
type: WalletActions.SET_WALLET,
payload: {
wallet: localPortisWallet,
name,
icon,
deviceId,
},
})
dispatch({ type: WalletActions.SET_IS_CONNECTED, payload: true })
} catch (e) {
disconnect()
}
} else {
disconnect()
}
dispatch({ type: WalletActions.SET_LOCAL_WALLET_LOADING, payload: false })
break
case KeyManager.MetaMask:
const localMetaMaskWallet = await state.adapters
.get(KeyManager.MetaMask)
?.pairDevice()
if (localMetaMaskWallet) {
const { name, icon } = SUPPORTED_WALLETS[KeyManager.MetaMask]
try {
await localMetaMaskWallet.initialize()
const deviceId = await localMetaMaskWallet.getDeviceID()
dispatch({
type: WalletActions.SET_WALLET,
payload: {
wallet: localMetaMaskWallet,
name,
icon,
deviceId,
},
})
dispatch({ type: WalletActions.SET_IS_CONNECTED, payload: true })
} catch (e) {
disconnect()
}
} else {
disconnect()
}
dispatch({ type: WalletActions.SET_LOCAL_WALLET_LOADING, payload: false })
break
default:
disconnect()
break
}
}
})()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.adapters, state.keyring])
const value: IWalletContext = useMemo(
() => ({ state, dispatch, connect, create, disconnect }),
[state, connect, create, disconnect],
)
return (
<WalletContext.Provider value={value}>
{children}
<WalletViewsRouter />
</WalletContext.Provider>
)
}