Last active
April 28, 2022 18:51
-
-
Save rpaskin/59323d3ef4fd9a9e0351db2af56fcbf0 to your computer and use it in GitHub Desktop.
Example simpleStorage web3js integration
This file contains hidden or 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
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
update de compatibilidade do metamask e web3, e nomes dos métodos para o código que vem de exemplo no Remix