Skip to content

Instantly share code, notes, and snippets.

@rpaskin
Last active April 28, 2022 18:51
Show Gist options
  • Save rpaskin/59323d3ef4fd9a9e0351db2af56fcbf0 to your computer and use it in GitHub Desktop.
Save rpaskin/59323d3ef4fd9a9e0351db2af56fcbf0 to your computer and use it in GitHub Desktop.
Example simpleStorage web3js integration
<!DOCTYPE html>
<html>
<head>
<title>Simple Storage</title>
<!-- <script src="https://cdn.jsdelivr.net/gh/ethereum/[email protected]/dist/web3.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.4.0-rc.0/web3.min.js"></script>
<button class="enableEthereumButton">Enable Ethereum</button>
<br><br>
<script type="text/javascript">
const ethereumButton = document.querySelector('.enableEthereumButton');
ethereumButton.addEventListener('click', () => {
//Will Start the metamask extension
ethereum.request({ method: 'eth_requestAccounts' });
});
const contract_address = "0x1123931C823A097D176f3c26f8fb0201b5D86611";
const contract_abi = [
{
"inputs": [
{
"internalType": "uint256",
"name": "num",
"type": "uint256"
}
],
"name": "store",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "retrieve",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
];
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
window.SimpleStorage = new window.web3.eth.Contract(contract_abi, contract_address);
saveCoinbase();
return true;
}
return false;
}
async function saveCoinbase () {
window.coinbase = await window.web3.eth.getCoinbase();
};
async function getAndShowVal () {
var val = window.SimpleStorage.methods.retrieve().call();
document.getElementById("storedData").value = await val;
};
async function setVal () {
var val = document.getElementById("storedData").value;
window.SimpleStorage.methods.store(val).send(val, {from:window.coinbase});
}
if (!ethEnabled()) {
alert("Metamask or browser with Ethereum not detected!");
}
</script>
</head>
<body>
<button id="getme" onclick="getAndShowVal()">Get</button>
StoredData: <input type="text" name="storedData" id="storedData">
<button id="setme" onclick="setVal()">Set</button>
</body>
</html>
@rpaskin
Copy link
Author

rpaskin commented Jun 30, 2021

update de compatibilidade do metamask e web3, e nomes dos métodos para o código que vem de exemplo no Remix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment