Created
November 21, 2018 19:38
-
-
Save sajclarke/0d10c55bc81eb95770604932e4aa056f to your computer and use it in GitHub Desktop.
Refactor the getWeb3, getAccount and getBalance functions
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
getWeb3 = () => new Promise((resolve, reject) => { | |
try{ | |
if(typeof window.web3 !== undefined){ | |
resolve(new Web3(Web3.givenProvider)) | |
}else{ | |
this.setState({errorMsg:'web3 not found'}) | |
} | |
}catch(error){ | |
this.setState({errorMsg:'An error occurred trying to connect to web3'}) | |
} | |
}) | |
getAccount = async (web3) => { | |
//Get logged in MetaMask ETH address | |
const accounts = await web3.eth.getAccounts() | |
if(accounts.length < 1){ | |
this.setState({loading: false,errorMsg:'Could not connect to Metamask. Please unlock your metamask'}) | |
}else{ | |
this.setState({loading: false, account:accounts[0], errorMsg:''}) | |
await this.getBalance(web3, accounts) | |
} | |
} | |
getBalance = async (web3, accounts) => { | |
//Instantiate the polyToken smart contract | |
const polyFaucet = new web3.eth.Contract(PolyTokenFaucet.abi, '0xB06d72a24df50D4E2cAC133B320c5E7DE3ef94cB') | |
//Get account's POLY balance | |
const polyBalance = await polyFaucet.methods.balanceOf(accounts[0]).call({ from: accounts[0] }) | |
//We use web3.utils.fromWei to display the units of the balance from wei to ether | |
this.setState({ loading: false, errorMsg:'', web3: web3, account: accounts[0], balance: web3.utils.fromWei(polyBalance, "ether"), polyFaucet: polyFaucet }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment