Created
October 29, 2022 19:26
-
-
Save natyrix/c999cd811bf7b3422091b7ec18c1e0ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer, useCallback, useEffect } from "react"; | |
import Web3 from "web3"; | |
import EthContext from "./EthContext"; | |
import { reducer, actions, initialState } from "./state"; | |
function EthProvider({ children }) { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const init = useCallback( | |
async artifact => { | |
if (artifact) { | |
const web3 = new Web3(Web3.givenProvider || "ws://localhost:7545"); | |
const accounts = await web3.eth.requestAccounts(); | |
const networkID = await web3.eth.net.getId(); | |
const { abi } = artifact; | |
let address, contract; | |
try { | |
console.log("JSNJC") | |
console.log(networkID) | |
address = artifact.networks[networkID].address; | |
contract = new web3.eth.Contract(abi, address); | |
} catch (err) { | |
console.error(err); | |
} | |
dispatch({ | |
type: actions.init, | |
data: { artifact, web3, accounts, networkID, contract } | |
}); | |
} | |
}, []); | |
useEffect(() => { | |
const tryInit = async () => { | |
try { | |
const artifact = require("../../contracts/Refund.json"); | |
init(artifact); | |
} catch (err) { | |
console.error(err); | |
} | |
}; | |
tryInit(); | |
}, [init]); | |
useEffect(() => { | |
const events = ["chainChanged", "accountsChanged"]; | |
const handleChange = () => { | |
init(state.artifact); | |
}; | |
events.forEach(e => window.ethereum.on(e, handleChange)); | |
return () => { | |
events.forEach(e => window.ethereum.removeListener(e, handleChange)); | |
}; | |
}, [init, state.artifact]); | |
return ( | |
<EthContext.Provider value={{ | |
state, | |
dispatch | |
}}> | |
{children} | |
</EthContext.Provider> | |
); | |
} | |
export default EthProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment