-
Notifications
You must be signed in to change notification settings - Fork 18
/
provider.tsx
298 lines (274 loc) · 9.04 KB
/
provider.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
import { accountArraysAreEqual, accountsAreEqual, initPolkadotJs } from '@/helpers'
import { registerDeployments } from '@/registry'
import {
SubstrateChain,
SubstrateDeployment,
SubstrateWallet,
UseInkathonError,
UseInkathonErrorCode,
UseInkathonProviderContextType,
} from '@/types'
import {
allSubstrateWallets,
enableWallet,
getSubstrateWallet,
isWalletInstalled,
nightlyConnect,
} from '@/wallets'
import { ApiPromise, HttpProvider, WsProvider } from '@polkadot/api'
import { ApiOptions } from '@polkadot/api/types'
import { InjectedAccount, InjectedExtension, Unsubcall } from '@polkadot/extension-inject/types'
import { Signer } from '@polkadot/types/types'
import {
FC,
PropsWithChildren,
createContext,
useContext,
useEffect,
useRef,
useState,
} from 'react'
import { getSubstrateChain } from './chains'
import { getNightlyConnectAdapter } from './helpers/getNightlyAdapter'
const UseInkathonProviderContext = createContext<UseInkathonProviderContextType | null>(null)
/**
* Primary useInkathon hook that exposes `UseInkathonProviderContext`.
*/
export const useInkathon = () => {
const context = useContext(UseInkathonProviderContext)
if (!context) throw new Error('useInkathon must be used within a UseInkathonProvider')
return context
}
/**
* Main provider that needs to be wrapped around the app (see README)
* to use `useInkathon` and other hooks anywhere.
*/
export interface UseInkathonProviderProps extends PropsWithChildren {
appName: string
defaultChain: SubstrateChain | SubstrateChain['network']
connectOnInit?: boolean
deployments?: Promise<SubstrateDeployment[]>
apiOptions?: ApiOptions
}
export const UseInkathonProvider: FC<UseInkathonProviderProps> = ({
children,
appName,
defaultChain,
connectOnInit,
deployments: _deployments,
apiOptions,
}) => {
// Check if default chain was provided
if (
!defaultChain ||
(typeof defaultChain === 'string' && getSubstrateChain(defaultChain) === undefined)
) {
throw new Error(
'None or invalid `defaultChain` provided with `UseInkathonProvider`. Forgot to set environment variable?',
)
}
// Setup state variables
const isInitializing = useRef(false)
const isInitialized = useRef(false)
const [isConnecting, setIsConnecting] = useState(connectOnInit)
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<UseInkathonError | undefined>()
const [activeChain, setActiveChain] = useState<SubstrateChain>(
(typeof defaultChain === 'string'
? getSubstrateChain(defaultChain)
: defaultChain) as SubstrateChain,
)
const [api, setApi] = useState<ApiPromise>()
const [provider, setProvider] = useState<WsProvider | HttpProvider>()
const [accounts, setAccounts] = useState<InjectedAccount[]>([])
const [activeAccount, setActiveAccount] = useState<InjectedAccount>()
const [lastActiveAccount, setLastActiveAccount] = useState<InjectedAccount>()
const activeExtension = useRef<InjectedExtension>()
const activeSigner = useRef<Signer>()
const unsubscribeAccounts = useRef<Unsubcall>()
const [deployments, setDeployments] = useState<SubstrateDeployment[]>([])
// Register given deployments
useEffect(() => {
if (_deployments) registerDeployments(setDeployments, _deployments)
}, [])
// Initialize polkadot-js/api
const initialize = async (chain?: SubstrateChain): Promise<ApiPromise | undefined> => {
isInitializing.current = true
setIsConnected(false)
setError(undefined)
const _chain = chain || activeChain
let _api: ApiPromise | undefined
let _provider: WsProvider | HttpProvider | undefined
try {
;({ api: _api, provider: _provider } = await initPolkadotJs(_chain, {
noInitWarn: true,
throwOnConnect: true,
...apiOptions,
}))
api?.disconnect()
setApi(_api)
provider?.disconnect()
setProvider(_provider)
isInitialized.current = true
// Update active chain if switching
if (activeChain.network !== _chain.network) setActiveChain(_chain)
} catch (e) {
const message = 'Error while initializing Polkadot.js API'
console.error(message, e)
setError({ code: UseInkathonErrorCode.InitializationError, message })
setIsConnected(false)
setIsConnecting(false)
setApi(undefined)
setProvider(undefined)
isInitialized.current = false
}
isInitializing.current = false
return _api
}
// Updates account list and active account
const updateAccounts = (
injectedAccounts: InjectedAccount[],
lastActiveAccountAddress?: string,
) => {
const newAccounts = injectedAccounts || []
// Find active account in new accounts or fallback to latest account
const _lastAccount = lastActiveAccountAddress
? { address: lastActiveAccountAddress }
: lastActiveAccount
const newAccount =
newAccounts.find((a) => accountsAreEqual(a, _lastAccount)) || newAccounts?.[0]
// Update accounts and active account
if (!accountArraysAreEqual(accounts, newAccounts)) {
setAccounts(() => newAccounts)
}
if (!accountsAreEqual(activeAccount, newAccount)) {
setActiveAccount(() => newAccount)
}
setIsConnected(!!newAccount)
}
useEffect(() => {
if (activeAccount && !accountsAreEqual(activeAccount, lastActiveAccount)) {
setLastActiveAccount(() => activeAccount)
}
}, [activeAccount])
// Connect to injected wallet
const connect = async (
chain?: SubstrateChain,
wallet?: SubstrateWallet,
lastActiveAccountAddress?: string,
) => {
setError(undefined)
setIsConnecting(true)
setIsConnected(!!activeAccount)
// Make sure api is initialized & connected to provider
if (!api?.isConnected || (chain && chain.network !== activeChain.network)) {
const _api = await initialize(chain)
if (!_api?.isConnected) return
}
try {
// Determine installed wallets
const wallets = allSubstrateWallets.filter((w) => isWalletInstalled(w))
if (!wallets?.length) {
const message = 'No Substrate-compatible extension detected'
setError({
code: UseInkathonErrorCode.NoSubstrateExtensionDetected,
message,
})
throw new Error(message)
}
// Determine wallet to use
const preferredWallet = wallet && wallets.find((w) => w.id === wallet.id)
const _wallet = preferredWallet || wallets[0]
// Enable wallet
const extension = await enableWallet(_wallet, appName)
activeExtension.current = extension
activeSigner.current = extension?.signer as Signer
// Query & keep listening to injected accounts
unsubscribeAccounts.current?.()
const unsubscribe = extension?.accounts.subscribe((accounts) => {
updateAccounts(accounts, lastActiveAccountAddress)
})
unsubscribeAccounts.current = unsubscribe
} catch (e: any) {
console.error('Error while connecting wallet:', e)
activeExtension.current = undefined
activeSigner.current = undefined
setIsConnected(false)
} finally {
setIsConnecting(false)
}
}
// Keep active signer up to date
useEffect(() => {
api?.setSigner(activeSigner.current as Signer)
}, [api, activeSigner.current])
// Disconnect
const disconnect = async (disconnectApi?: boolean) => {
if (disconnectApi) {
await provider?.disconnect()
await api?.disconnect()
return
}
if (activeExtension.current?.name === nightlyConnect.id) {
const adapter = await getNightlyConnectAdapter(appName)
await adapter?.disconnect()
}
setIsConnected(false)
updateAccounts([])
unsubscribeAccounts.current?.()
unsubscribeAccounts.current = undefined
activeExtension.current = undefined
activeSigner.current = undefined
isInitialized.current = false
}
// API Disconnection listener
useEffect(() => {
if (!api) return
const handler = () => {
disconnect()
}
api?.on('disconnected', handler)
return () => {
api?.off('disconnected', handler)
}
}, [api])
// Initialze
useEffect(() => {
if (isInitialized.current || isInitializing.current) return
connectOnInit ? connect() : initialize()
return () => {
unsubscribeAccounts.current?.()
}
}, [])
// Switch active chain
const switchActiveChain = async (chain: SubstrateChain) => {
const activeWallet = activeExtension.current && getSubstrateWallet(activeExtension.current.name)
await connect(chain, activeWallet)
}
return (
<UseInkathonProviderContext.Provider
value={{
isInitializing: isInitializing.current,
isInitialized: isInitialized.current,
isConnecting,
isConnected,
error,
activeChain,
switchActiveChain,
api,
provider,
connect,
disconnect,
accounts,
activeAccount,
activeExtension: activeExtension.current,
activeSigner: activeSigner.current,
setActiveAccount,
lastActiveAccount,
deployments,
}}
>
{children}
</UseInkathonProviderContext.Provider>
)
}