Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
// getABI loads the ABI of the contract
// This is an async function so we can wait for it to finish executing
async function getABI(){
// DevToken.json should be placed inside the public folder so we can reach it
let ABI = "";
await fetch('./DevToken.json', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// getContractAddress returns the address of the contract
// hardcoded :)
function getContractAddress() {
return "0xaD183414719d49Fc3F8Fb0490662C4d484972d86";
}
function App() {
// Adding our Devtoken state and a set function to assign it
const [devToken, setDevToken] = useState(0);
async function connectToSelectedNetwork() {
// This will connect to the selected network inside MetaMask
const web3 = new Web3(Web3.givenProvider);
// Set the ABI of the Built contract so we can interact with it
const abi = await getABI();
const address = getContractAddress();
// Make a new instance of the contract by giving the address and abi
const devtoken = new web3.Contract(abi, address);
// Set the state of the app by passing the contract so we can reach it from other places
// this will trigger whenever the App function is called, which index.js runs at startup
useEffect(() => {
// Here we check if there is web3 support
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(window.web3.currentProvider)
// Check if its MetaMask that is installed
if (window.web3.currentProvider.isMetaMask === true) {
connectMetaMask();
connectToSelectedNetwork();
} else {
// accounts is the metamask accounts and setAccounts is used to assign them
const [accounts, setAccounts] = useState(0);
// connectMetaMask is used to connect to MetaMask and ask permission to grab account information
function connectMetaMask() {
// We need to make the connection to MetaMask work.
// Send Request for accounts and to connect to metamask.
window.web3.requestAccounts()
.then((result) => {
// Whenever the user accepts this will trigger
setAccounts(result);
})
.catch((error) => {
// getUserProfile will fetch account information from the block chain network
async function getUserProfile() {
// Let's grab the tokens total supply, the method is named the same as in the Solidity code, and add call() to execute it.
// We will add the keyword await to let the code know that it should block until the reponse arrives.
const devTokenSupply = await devToken.methods.totalSupply().call();
console.log(devTokenSupply);
}
const [loaded, setLoaded] = useState(false);
useEffect(() => {
// Only get profile if we are completly loaded
if (loaded && (accounts !== 0)) {
// get user info
console.log(accounts);
getUserProfile()
} else {
// dirty trick to trigger reload if something went wrong
setTimeout(setLoaded(true), 500);
}