JavaScript API 1

Pulling information from the blockchain

We are going to take a quick look at some of the bindings in the JavaScript API and how they can be used to build powerful front ends for your dapps. In this tutorial we will cover how to use the JavaScript API to pull information from both your client and the blockchain stored on your local computer.

Almost all our code is going to be executed synchronously – with the exception of web3.eth.watch, which will create a ‘watch’ object to monitor the state of the blockchain.

We are going to be using the below html / JavaScript template and we will add new JavaScript’s function while explaining what they do. We will not be using any custom libraries and our only aesthetic choice will be to use bootstrap to make things look nice.

<html>
<head>
  <title>JavaScript API</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js">
  
<script type="text/javascript">
///First web3.eth.watch code to monitor coinbase
  

///Insert your contract address var here:
 

///Second web3.eth.watch code to monitor block number
  

</script>

</head>

<body>

  <div class="header">
    <h3>JavaScript API</h3>
  </div>

  <div class="jumbotron">
    <h5>Coinbase Address: <strong id="coinbase"></strong></h5>
    <h5>Balance: <strong id="balance"></strong></h5>
    <h5>Latest Block Number: <strong id="latestBlock"></strong></h5>
    <h5>Latest Block Timestamp: <strong id="latestBlockTimestamp"></strong></h5>
    <h5>Latest Block Hash: <strong id="latestBlockHash"></strong></h5>
    <h5>Contract String: <strong id="contractString"></strong></h5>
    <h5>Favourite Python: <strong id="favouritePython"></strong></h5>
    <br>
  </div>

</body>

</html>

Take the above and paste it into your preferred text editor and save it as a html file somewhere convenient. Now open Alethzero and use the browser to navigate to it. You should see the below:

Screen Shot 2015-02-27 at 11.17.39 (2)

We have listed several pieces of information; Coinbase Address, Balance, Latest Block Number, etc.. – currently they are all blank, and we will use our JavaScript bindings to pull the information from the browser and pass them to the web page.

Switch back to the text editor everything should be pretty familiar to anyone who has created a html page before. Take a look at the lines between 7 and 17 here I have created a skeleton for you to add the JavaScript bindings that interact with the browser.

All of our bindings use the web3 object, and we will only be using the web3.eth object today. Others such as the whisper protocol web3.shh and the future swarm protocol will be covered later. A full list of available JavaScript bindings can be found on our github wiki page – https://github.com/ethereum/wiki/wiki/JavaScript-API.

The first binding you will need to use is web3.eth.watch. This object monitors the state of the blockchain and allows you to specify what triggers its function using filters. There are two main options for this ‘chain’ and ‘pending’ which look out for changes in the blockchain or the pending transactions respectively. You may also specify log items as filters but this will be covered later. This watch object is important because there is nothing static about the blockchain, it will be rare that you will not wish to have the webpage update whenever the state of the blockchain changes – i.e.: a new block is mined.

Take the below and copy it into your html – then save your file and reload the AZ web browser.

web3.eth.watch('chain').changed(function(){
  //Your Code goes here
});

This watch objects function will execute as soon as there are changes in the blockchain (ie a new block being mined). Currently it has no code to execute – lets rectify this by adding:

web3.eth.watch('chain').changed(function(){
  var coinbase = web3.eth.coinbase;
  document.getElementById('coinbase').innerText = coinbase;
});

We have added a variable ‘coinbase’ to retrieve our coinbase account (the account that we use to mine blocks and send transaction) from the client using web3.eth.coinbase. Once the blockchains state changes the function will modify our web page to display our coinbase account number. This is pretty cool, but not particularly interesting as our coinbase account doesn’t really change that much (only if we add a new account or manually set the coinbase to something else). The web3.eth.balanceAt function returns the balance in ether at a particular address when passed that address in the form of a string. We will use it to display the balance at our coinbase address.

web3.eth.watch('chain').changed(function(){
  var coinbase = web3.eth.coinbase;
  document.getElementById('coinbase').innerText = coinbase;
  var balance = web3.eth.balanceAt(coinbase);
  document.getElementById('balance').innerText = balance;
});

Take a look at the web page in the browser – if you have anything higher than a zero balance you will likely see some thing like this ‘0x678’. This is because the browser returns the account balance as a hexadecimal value – don’t worry we have a built in function web3.toDecimal() to convert it to a decimal:

var balance = web3.eth.balanceAt(coinbase);
  document.getElementById('balance').innerText = web3.toDecimal(balance);

Now your webpage should look more like this:

Screen Shot 2015-02-27 at 11.24.58 (2)

Because we have placed both our functions inside our web3.eth.watch function whenever a new block is registered, the code is executed again and our web page will be updated. Try mining some more ether and watch it update.

We can use ‘watch’ to monitor the blockchain, and a variety of filters to change what triggers the execution of our code. Using the filter ‘pending’ means that the watch object will register a change both when a new block is mined AND when a new transaction enters the pending queue.

We are going to use another watch object with the ‘pending’ filter to monitor the blockchain and update our web page with information on the latest block. We first do this by calling web3.eth.number, which gives us the number of the latest block mined. we can then pass this as an argument to web3.eth.block to return a JSON object with several parameters containing all the relevant information regarding the block. We are going to take two of the most useful ‘timestamp’ and ‘hash’, which gives you the time of the latest block mined, and the hash of the block:

web3.eth.watch('pending').changed(function(){
  var blockNumber = web3.eth.number;
  document.getElementById('latestBlock').innerText = blockNumber;
  var hash = web3.eth.block(blockNumber).hash;
  document.getElementById('latestBlockHash').innerText = hash;
  var timeStamp = web3.eth.block(blockNumber).timestamp;
  document.getElementById('latestBlockTimestamp').innerText = Date(timeStamp);
});

Six lines of code are executed when the watch object registers a change the first and second takes the number of the block and inserts it into the webpage. The final four pull parameters from the JSON object ‘result’ and modify the webpage with them (we also use the Object method Date() to convert the timestamp from UTC to human readable date). Reload your webpage and mine a few more blocks – you should see the values update in real time.

Finally, we are going to use the API for a very useful purpose, to pull information from our contracts data storage. For demonstrating this we are first going to make things simple and create a contract initialised with data in its storage:

contract Me {
  string32 first;
  string32 last;
  string32 twitter;
  string32 nick;
  address myAddress;
  uint dateJoined;
  function Me(){
    first = 'Ken';
    last = 'Kappler';
    twitter = '@kapplerken';
    nick ='BlueChain';
    myAddress = msg.sender;
    dateJoined = block.timestamp;
  }   
}

Copy the above into the ‘New Transaction’ window and send it to the blockchain in a transaction – just like you did in the previous tutorials. While it is in the pending pane grab the contracts address as you will need to add it to your JavaScript like so:

var contractAddress = "0x52ae0988e11527678c3a75f89e487efffb101a6d";

We are going to use this and the function web3.eth.storageAt() to retreive our contracts data storage. Rather than create another watch object we can simply make an addition to the second ‘watch’ which is monitoring the pending queue, knowing as we do that the contracts storage cannot change without a new block being created.

web3.eth.watch('pending').changed(function(){
  var blockNumber = web3.eth.number;
  document.getElementById('latestBlock').innerText = blockNumber;
  var hash = web3.eth.block(blockNumber).hash;
  document.getElementById('latestBlockHash').innerText = hash;
  var timeStamp = web3.eth.block(blockNumber).timestamp;
  document.getElementById('latestBlockTimestamp').innerText = Date(timeStamp);
  var contractString = JSON.stringify(web3.eth.storageAt(contractAddress))
  document.getElementById('contractString').innerText = contractString;
});

You should be pretty comfortable with how this works by now, web3.eth.storageAt returns a JSON object with the entire content of the contracts storage. Previously we have dealt with functions that return either a single value, or a JSON object that has the same properties (hash, timestamp, etc…) each time. This time is a little different – here the JSON object is a list of key values that can be different for every contract – you cannot rely on knowing the parameters before writing your JavaScript. I’m not going to go into how you should use JavaScript to handle JSON objects like this, suffice to say that there is plenty of information on this available on the Internet. In this example we are simply going to take the JSON object returned by the promise and stringify it.

This should output to your front end:

Contract String: {“0x”:”0x4b656e0000000000000000000000000000000000000000000000000000000000″,”0x01″:”0x4b6170706c657200000000000000000000000000000000000000000000000000″,”0x02″:”0x406b6170706c65726b656e000000000000000000000000000000000000000000″,”0x03″:”0x426c7565436861696e0000000000000000000000000000000000000000000000″,”0x04″:”0x4ffb79a67c4292b8107381496a0462e3fd482d15″,”0x05″:”0x54d21719″}

You’ll note that the strings we sent to the contract have been returned as hex code, so lets grab a couple of those key value pairs and convert it back to ASCII using web3.toAscii:

...
  var storageObject = web3.eth.storageAt(contractAddress);
  document.getElementById('fullName').innerText = web3.toAscii(storageObject['0x']) + ' ' + web3.toAscii(storageObject['0x01']);
  ...

This completes our webpage. If you wish to play round with the other JavaScript bindings a complete list can be found here.

Above we’ve gone through how the Javascript API allows you to pull information from the blockchain, and from your client, and how the watch functions allow your Dapp front ends to react to changes on the blockchain. This is basically passive collection of information held on the blockchain – in the next tutorial on JavaScript we will cover the basics of sending information to the blockchain using transactions.

One thought on “JavaScript API 1

Leave a comment