-
Notifications
You must be signed in to change notification settings - Fork 10
Anatomy of a Contract
In this case we'll look at a simple storage program.
contract SimpleStorage {
uint storedData;
function set(uint x) {
storedData = x;
}
function get() constant returns (uint retVal) {
return storedData;
}
}
[
{
"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "retVal",
"type": "uint256"
}
],
"type": "function"
}
]
Here is the Ethereum Byte code for this contract:
6060604052603b8060116000396000f300606060405260e060020a600035046360fe47b1811460245780636d4ce63c14602e575b005b6004356000556022565b6000546060908152602090f3
var abi = [
{
"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "retVal",
"type": "uint256"
}
],
"type": "function"
}
],
code = '6060604052603b8060116000396000f300606060405260e060020a600035046360fe47b1811460245780636d4ce63c14602e575b005b6004356000556022565b6000546060908152602090f3',
deployTransactionObject = {
from: web3.eth.accounts[0],
gas: 300000,
data: code,
},
setTransactionObject = {
from: web3.eth.accounts[0],
gas: 300000,
};
Setup the SimpleStorage Contract Object in JS
var SimpleStorage = web3.eth.contract(abi);
Deploy a new SimpleStorage contract to the Ethereum blockchain
SimpleStorage.new(deployTransactionObject, function(err, contract){
if(err)
console.log('There was an error deploying your SimpleStorage contract on the Blockchain: ', err);
if(!err) {
if(!contract.address) {
console.log('Your transaction was posted to the Ethereum blockchain with this hash identifier: ', contract.transactionHash);
} else {
console.log('Your contract was deployed to this address on the blockchain: ', contract.address);
}
}
});
Once you have deployed your SimpleStorage contract, use the address provided below as the .at address to set up a SimpleStorage Contract Instance
var contractInstance = SimpleStorage.at('0x7de20ad122e172d75086abe4df51841851f2019c');
Set Stored Value in your SimpleStorage contract on the Ethereum blockchain
contractInstance.set.sendTransaction(456, setTransactionObject, function(err, result){
if(err)
console.log('Error Saving Data on SimpleStorage: ', err);
if(!err)
console.log('Transaction Hash: ', result);
});
Get the stored value from your SimpleStorage contract on the Ethereum blockchain
contractInstance.get.call(function(err, result){
if(err)
console.log('Error Calling Contract', err);
if(!err)
console.log('Stored Value: ', result);
});
For more MeteorJS-based decentralized applications please check out https://github.com/SilentCicero?tab=repositories.