Skip to content

Instantly share code, notes, and snippets.

@Jerga99
Created January 5, 2024 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jerga99/5f062a90221714da95323f5f07553d8c to your computer and use it in GitHub Desktop.
Save Jerga99/5f062a90221714da95323f5f07553d8c to your computer and use it in GitHub Desktop.
import './App.css';
import React, {useCallback, useEffect, useState} from 'react';
import Web3 from "web3";
import detectEthereumProvider from '@metamask/detect-provider';
import { loadContract } from './utils/load_contract';
function App() {
const [web3Api, setWeb3Api] = useState({
provider: null,
web3: null,
contract: null
})
const [balance, setBalance] = useState(null)
const [account, setAccount] = useState(null)
useEffect(() => {
const loadProvider = async () => {
// with metamask we have access to window.ethereum & to window.web3
// metamask injects a global API into website
// this API will allow website to request users, accounts, read data to blockchain
// can also sign messages and transactions
const provider = await detectEthereumProvider()
const contract = await loadContract('Faucet', provider)
if(provider) {
setWeb3Api({
web3: new Web3(provider),
provider,
contract
})
} else {
console.error('Please install Metamask')
}
}
loadProvider ()
}, [])
useEffect(() => {
const loadBalance = async () => {
const { contract, web3 } = web3Api
web3.eth.getBalance(contract.address, (err, balance) => {
setBalance(web3.fromWei(parseInt(balance), "ether"))
});
}
web3Api.contract && loadBalance()
}, [web3Api])
useEffect(() => {
const getAccount = async () => {
web3Api.web3.eth.getAccounts((err, accounts) => {
setAccount(accounts[0])
})
}
web3Api.web3 && getAccount()
}, [web3Api.web3])
const addFunds = useCallback(async () => {
const { contract, Web3 } = web3Api
await contract.addFunds({
from: account,
value: Web3.utils.toWei("1", "ether")
})
}, [web3Api, account])
return (
<>
<div className = 'faucet-wrapper'>
<div className = 'faucet'>
<div className = 'is-flex is-align-items-center'>
<span>
<strong className = 'mr-2'>Account: </strong>
</span>
{account ?
<div>{account}</div>:
<button
className = 'button is-small'
onClick = {() => web3Api.provider.request({method: 'eth_requestAccounts'}
)}
>
Connect Wallet
</button>
}
</div>
<div className = 'balance-view is-size-2 my-4'>
Current Balance: <strong>{balance}</strong> ETH
</div>
<button
onClick={addFunds}
className = "button is-link mr-2">
Donate 1eth
</button>
<button className = 'button is-primary is-dark'>Withdraw</button>
</div>
</div>
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment