forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useChainContext.ts
53 lines (41 loc) · 1.25 KB
/
useChainContext.ts
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
import { createContext, useContext, useMemo } from 'react'
import {
ConfiguredChainContext,
IChainContext,
SupportedChainContext,
} from '@dao-dao/types'
export const ChainContext = createContext<IChainContext | null>(null)
export const useChainContextIfAvailable = (): IChainContext | null =>
useContext(ChainContext)
export const useChainContext = (): IChainContext => {
const context = useChainContextIfAvailable()
if (!context) {
throw new Error(
'useChainContext can only be used in a descendant of ChainContext.Provider.'
)
}
return context
}
export const useConfiguredChainContext = (): ConfiguredChainContext => {
const context = useChainContext()
// Make sure this is a configured chain.
if (!context.base) {
throw new Error('Unconfigured chain context.')
}
return useMemo(
(): ConfiguredChainContext => ({
...context,
config: context.base!,
}),
[context]
)
}
export const useSupportedChainContext = (): SupportedChainContext => {
const context = useChainContext()
// Make sure this is a supported chain.
if (!context.config) {
throw new Error('Unsupported chain context.')
}
return context as SupportedChainContext
}
export const useChain = () => useChainContext().chain