|
| 1 | +import React, { |
| 2 | + createContext, |
| 3 | + useState, |
| 4 | + useContext, |
| 5 | + useMemo, |
| 6 | + useEffect, |
| 7 | + useCallback, |
| 8 | +} from 'react' |
| 9 | + |
| 10 | +import { useWallet } from 'use-wallet' |
| 11 | +import { web3, registerProvider } from '../utils/ethers' |
| 12 | + |
| 13 | +import useLocalStorage from '../hooks/useLocalStorage' |
| 14 | +const atob = (a) => Buffer.from(a, 'base64').toString('binary') |
| 15 | + |
| 16 | +// Create Context |
| 17 | +export const UseWeb3Context = createContext() |
| 18 | + |
| 19 | +export const Web3Provider = (props) => { |
| 20 | + const { account, connect, status, ethereum, reset } = useWallet() |
| 21 | + |
| 22 | + // Remember provider preference |
| 23 | + const [provider, setProvider] = useLocalStorage('provider', false) |
| 24 | + |
| 25 | + // Connect/Disconnect Wallet |
| 26 | + const connectWallet = async (key) => { |
| 27 | + await connect(key) |
| 28 | + setProvider(key) |
| 29 | + registerProvider(ethereum) |
| 30 | + } |
| 31 | + const disconnectWallet = () => { |
| 32 | + reset() |
| 33 | + setProvider(false) |
| 34 | + } |
| 35 | + |
| 36 | + // Check to see if we've set a provider in local Storage and connect |
| 37 | + const initProvider = () => { |
| 38 | + if (provider) { |
| 39 | + console.log('Provider Found:', provider) |
| 40 | + connect(provider) |
| 41 | + registerProvider(ethereum) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // Once we've connected a wallet, switch to wallet provider |
| 46 | + useEffect(() => { |
| 47 | + if (status === 'connected') { |
| 48 | + console.log('Connected!') |
| 49 | + registerProvider(ethereum) |
| 50 | + } |
| 51 | + }, [status]) |
| 52 | + |
| 53 | + // Once loaded, initalise the provider |
| 54 | + useEffect(() => { |
| 55 | + initProvider() |
| 56 | + }, [provider]) |
| 57 | + |
| 58 | + const tools = useMemo( |
| 59 | + () => ({ |
| 60 | + provider, |
| 61 | + setProvider, |
| 62 | + connectWallet, |
| 63 | + disconnectWallet, |
| 64 | + account, |
| 65 | + status, |
| 66 | + }), |
| 67 | + [provider, account, status] |
| 68 | + ) |
| 69 | + |
| 70 | + // pass the value in provider and return |
| 71 | + return ( |
| 72 | + <UseWeb3Context.Provider |
| 73 | + value={{ |
| 74 | + tools, |
| 75 | + }} |
| 76 | + > |
| 77 | + {props.children} |
| 78 | + </UseWeb3Context.Provider> |
| 79 | + ) |
| 80 | +} |
| 81 | + |
| 82 | +export function useWeb3() { |
| 83 | + const web3Context = useContext(UseWeb3Context) |
| 84 | + if (web3Context === null) { |
| 85 | + throw new Error( |
| 86 | + 'useWeb3() can only be used inside of <UseToolsProvider />, ' + |
| 87 | + 'please declare it at a higher level.' |
| 88 | + ) |
| 89 | + } |
| 90 | + const { tools } = web3Context |
| 91 | + |
| 92 | + return useMemo(() => ({ web3, ...tools }), [tools]) |
| 93 | +} |
| 94 | + |
| 95 | +export default useWeb3 |
0 commit comments