Skip to content

Instantly share code, notes, and snippets.

@sergejmueller
Created September 10, 2019 03:59
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 sergejmueller/3afb358165a0f2e9cba1884a9c353e5f to your computer and use it in GitHub Desktop.
Save sergejmueller/3afb358165a0f2e9cba1884a9c353e5f to your computer and use it in GitHub Desktop.
Simple Smart Contract App
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SimpleStorage Dapp</title>
</head>
<body>
<center>
<div id=error style="color:red"></div>
<div id=success style="color:green"></div>
<h1>Blockchain Handling</h1>
<table>
<tbody>
<tr>
<td width=150>From Blockchain:</td>
<td id="blockchainValue"></td>
<td></td>
</tr>
<tr>
<td>Set new value:</td>
<td><input id="newValue" type="number"></td>
<td><button id="button">Add</button></td>
</tr>
</tbody>
</table>
</center>
<script>
(function() {
const address = '0x34f4a0e38e60cebdb5844e9de7b4a72cdd77ee89';
const abi = [{
"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}];
const showError = error => {
document.getElementById('error').innerText = error;
};
const showSuccess = msg => {
document.getElementById('success').innerText = msg;
};
const getValue = () => {
return new Promise(async (resolve, reject) => {
const contract = web3.eth.contract(abi).at(address);
contract.get.call((error, data) => {
if (error) return reject(new Error(error));
return resolve(data);
});
});
};
const setValue = async (data) => {
return new Promise(async (resolve, reject) => {
if (!data) {
return reject(new Error('No data to submit'));
}
const contract = web3.eth.contract(abi).at(address);
contract.set.sendTransaction(data, (error, hash) => {
if (error) return reject(new Error(error));
return resolve(hash);
});
});
}
window.addEventListener('load', async () => {
try {
await ethereum.enable();
web3 = new Web3(ethereum);
web3.eth.defaultAccount = web3.eth.accounts[0];
getValue()
.then(data => document.getElementById('blockchainValue').innerText = data)
.catch(error => showError(error));
} catch (error) {
showError(error);
}
});
document.getElementById('button').addEventListener('click', () => {
setValue(document.getElementById('newValue').value)
.then(hash => showSuccess(hash))
.catch(error => showError(error));
}, false);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment