1
+ import { createContext , Dispatch , useContext } from "react"
2
+
3
+ type StateType = {
4
+ provider ?: any
5
+ web3Provider ?: any
6
+ account ?: string
7
+ chainId ?: number
8
+ }
9
+
10
+ export const initialWeb3State : StateType = {
11
+ provider : null ,
12
+ web3Provider : null ,
13
+ account : null ,
14
+ chainId : null ,
15
+ }
16
+
17
+ type ActionType =
18
+ | {
19
+ type : 'SET_WEB3_PROVIDER'
20
+ provider ?: StateType [ 'provider' ]
21
+ web3Provider ?: StateType [ 'web3Provider' ]
22
+ account ?: StateType [ 'account' ]
23
+ chainId ?: StateType [ 'chainId' ]
24
+ }
25
+ | {
26
+ type : 'SET_ACCOUNT'
27
+ account ?: StateType [ 'account' ]
28
+ }
29
+ | {
30
+ type : 'SET_CHAIN_ID'
31
+ chainId ?: StateType [ 'chainId' ]
32
+ }
33
+ | {
34
+ type : 'RESET_WEB3_PROVIDER'
35
+ }
36
+
37
+ export function web3Reducer ( state : StateType , action : ActionType ) : StateType {
38
+ switch ( action . type ) {
39
+ case 'SET_WEB3_PROVIDER' :
40
+ return {
41
+ ...state ,
42
+ provider : action . provider ,
43
+ web3Provider : action . web3Provider ,
44
+ account : action . account ,
45
+ chainId : action . chainId ,
46
+ }
47
+ case 'SET_ACCOUNT' :
48
+ return {
49
+ ...state ,
50
+ account : action . account ,
51
+ }
52
+ case 'SET_CHAIN_ID' :
53
+ return {
54
+ ...state ,
55
+ chainId : action . chainId ,
56
+ }
57
+ case 'RESET_WEB3_PROVIDER' :
58
+ return initialWeb3State
59
+ default :
60
+ throw new Error ( )
61
+ }
62
+ }
63
+
64
+
65
+ export const Web3Context = createContext < { state : StateType , dispatch : Dispatch < ActionType > | undefined } > ( { state : initialWeb3State , dispatch : undefined } ) ;
66
+ export function useWeb3Context ( ) {
67
+ return useContext ( Web3Context ) ;
68
+ }
0 commit comments