web3.js/example/contract.html

77 lines
2.3 KiB
HTML
Raw Normal View History

2014-11-14 12:11:47 +00:00
<!doctype>
<html>
<head>
2015-04-20 11:52:40 +00:00
<script type="text/javascript" src="../dist/web3.js"></script>
2014-11-14 12:11:47 +00:00
<script type="text/javascript">
2015-04-07 02:39:47 +00:00
var web3 = require('web3');
2015-04-20 12:38:08 +00:00
web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
2014-11-14 12:11:47 +00:00
2015-05-13 10:05:38 +00:00
// solidity code code
var source = "" +
"contract test {\n" +
" function multiply(uint a) constant returns(uint d) {\n" +
" return a * 7;\n" +
" }\n" +
"}\n";
2015-05-21 10:02:15 +00:00
var compiled = web3.eth.compile.solidity(source);
var code = compiled.test.code;
// contract json abi, this is autogenerated using solc CLI
var abi = compiled.test.info.abiDefinition;
2014-11-14 12:11:47 +00:00
2015-02-24 09:36:54 +00:00
var myContract;
2014-11-14 12:11:47 +00:00
function createExampleContract() {
// hide create button
document.getElementById('create').style.visibility = 'hidden';
2015-05-13 10:05:38 +00:00
document.getElementById('code').innerText = code;
2014-11-14 12:11:47 +00:00
2015-04-20 12:38:08 +00:00
// let's assume that coinbase is our account
web3.eth.defaultAccount = web3.eth.coinbase;
2015-02-24 09:36:54 +00:00
2015-04-20 12:38:08 +00:00
// create contract
2015-07-07 09:56:50 +00:00
document.getElementById('status').innerText = "transaction sent, waiting for confirmation";
2015-07-07 09:51:13 +00:00
web3.eth.contract(abi).new({data: code}, function (err, contract) {
2015-07-20 14:44:25 +00:00
if(err) {
2015-07-07 09:58:42 +00:00
console.error(err);
2015-07-07 09:51:13 +00:00
return;
2015-07-20 14:44:25 +00:00
// callback fires twice, we only want the second call when the contract is deployed
} else if(contract.address){
myContract = contract;
console.log('address: ' + myContract.address);
document.getElementById('status').innerText = 'Mined!';
document.getElementById('call').style.visibility = 'visible';
2015-05-13 15:46:49 +00:00
}
2015-07-07 09:51:13 +00:00
});
2014-11-14 12:11:47 +00:00
}
function callExampleContract() {
// this should be generated by ethereum
2015-01-08 14:31:46 +00:00
var param = parseInt(document.getElementById('value').value);
2014-11-14 12:11:47 +00:00
// call the contract
2015-04-20 12:38:08 +00:00
var res = myContract.multiply(param);
2015-01-27 10:53:34 +00:00
document.getElementById('result').innerText = res.toString(10);
2014-11-14 12:11:47 +00:00
}
</script>
</head>
<body>
<h1>contract</h1>
2015-05-13 10:05:38 +00:00
<div id="code"></div>
2015-05-13 15:46:49 +00:00
<div id="status"></div>
2014-11-14 12:11:47 +00:00
<div id='create'>
<button type="button" onClick="createExampleContract();">create example contract</button>
</div>
<div id='call' style='visibility: hidden;'>
<input type="number" id="value" onkeyup='callExampleContract()'></input>
</div>
<div id="result"></div>
</body>
</html>