Skip to content

Instantly share code, notes, and snippets.

@rbrick
Last active July 12, 2021 05:32
Show Gist options
  • Save rbrick/08d3aa3ce40bf431c7d415ff112c1c03 to your computer and use it in GitHub Desktop.
Save rbrick/08d3aa3ce40bf431c7d415ff112c1c03 to your computer and use it in GitHub Desktop.
Messing around with Metamask and Ethereum
<!DOCTYPE html>
<html>
<head>
<script src="/assets/js/web3.min.js"></script>
</head>
<body>
<h1 id="status">Not connected.</h1>
<h2 id="account">no account</h2>
<h3 id="walletBalance"></h3>
<button id="signIn">Sign in with Metamask</button>
<script>
'use strict';
let web3 = new Web3(Web3.givenProvider);
// metamask provides an ethereum object that we can
let e = window.ethereum;
if (e != null) {
document.getElementById("signIn").addEventListener('click', (ev) => {
e.request({ method: "eth_requestAccounts" });
});
e.on('accountsChanged', function (accounts) {
// Time to reload your interface with accounts[0]!
if (accounts.length == 0) {
document.getElementById("status").textContent = "Disconnected";
document.getElementById("account").textContent = "no account";
document.getElementById("signIn").hidden = false;
window.localStorage.removeItem("account");
} else {
// add something to the dom saying we're connected
document.getElementById("status").textContent = "Connected";
document.getElementById("account").textContent = accounts[0];
document.getElementById("signIn").hidden = true;
window.localStorage.setItem("account", accounts[0]);
e.request({ method: 'eth_getBalance', params: [e.selectedAddress] }).then((res) => {
document.getElementById('walletBalance').textContent = "Balance: " + web3.utils.fromWei(res);
});
}
});
if (window.localStorage.getItem("account")) {
document.getElementById("status").textContent = "Connected";
document.getElementById("account").textContent = window.localStorage.getItem("account");
}
} else {
alert("No Metamask Found");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment