-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb3Context.ts
68 lines (62 loc) · 1.46 KB
/
web3Context.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import {createContext, Dispatch, useContext} from "react"
type StateType = {
provider?: any
web3Provider?: any
account?: string
chainId?: number
}
export const initialWeb3State: StateType = {
provider: null,
web3Provider: null,
account: null,
chainId: null,
}
type ActionType =
| {
type: 'SET_WEB3_PROVIDER'
provider?: StateType['provider']
web3Provider?: StateType['web3Provider']
account?: StateType['account']
chainId?: StateType['chainId']
}
| {
type: 'SET_ACCOUNT'
account?: StateType['account']
}
| {
type: 'SET_CHAIN_ID'
chainId?: StateType['chainId']
}
| {
type: 'RESET_WEB3_PROVIDER'
}
export function web3Reducer(state: StateType, action: ActionType): StateType {
switch (action.type) {
case 'SET_WEB3_PROVIDER':
return {
...state,
provider: action.provider,
web3Provider: action.web3Provider,
account: action.account,
chainId: action.chainId,
}
case 'SET_ACCOUNT':
return {
...state,
account: action.account,
}
case 'SET_CHAIN_ID':
return {
...state,
chainId: action.chainId,
}
case 'RESET_WEB3_PROVIDER':
return initialWeb3State
default:
throw new Error()
}
}
export const Web3Context = createContext<{ state: StateType, dispatch: Dispatch<ActionType> | undefined}>({ state: initialWeb3State, dispatch: undefined});
export function useWeb3Context() {
return useContext(Web3Context);
}