Skip to content

Cryptoreflections – Check out my decentralized Ethereum bank account

>>>>>>>>>>>>>>>>>>>>>>>>Check it out here!<<<<<<<<<<<<<<<<<<<<<<<<

It’s a crypto-mania

The crypto-mania is just an epiphenomenon of one of the greatest technological innovations of our times: the Blockchain.

The blockchain is a powerful combination of existing disciplines: peer-to-peer networking, cryptography, accounting and game theory. It allows trustless and decentralized creation and transfer of value.

If we think of the Internet as the world wide web of information, the Blockchain is the world wide web of value.

What is Ethereum?

The first blockchain was the Bitcoin one, created by the mysterious Satoshi Nakamoto, and since then many have emerged. In my opinion, the most interesting is the Ethereum blockchain created by a development team led by Vitalik Buterin.

Ethereum allows transfer of both value and logic, combining a crypto token (Ether) and a virtual machine (EVM) that processes “smart contracts” code.

Ethereum is an incredibly powerful mix of internet and the blockchain.

How can I interact with Ethereum?

The Ethereum blockchain communicates with internet via a Javascript API (Web3).

Your computer instead communicates with the Ethereum blockchain via software, transforming itself into an active or passive node of the blockchain.

Developers have created Metamask, a Google and Firefox extension, that turns your local machine into a “light” node: it is not directly connected with the blockchain (and does not need to download the full blockchain data locally, which can be very heavy and can clog your CPU/GPU) but employs the Metamask servers as a bridge in order to connect to the blockchain.

How can I build a website that interacts with the Ethereum blockchain?

You can find my example here: https://dry-forest-85635.herokuapp.com/ . It is a simple, decentralized bank account that allows you to transfer your Ether to my Ethereum account.

I used a combination of tools:

  • to program the app: Node and npm as a back-end/front-end Javascript programming architecture, Yeoman webapp-generator as a framework/boilerplate, Bower as a package manager for the Web3 API package (and Bootstrap for the UI), Gulp for automating development tasks and deployment.
  • to connect to the Ethereum blockchain: Metamask Chrome or Firefox extension
  • to host and deploy the app: Git and Heroku

Give me the code…

The most important pieces of code to develop something like the above are two Javascript files (the rest being only simple HTML code).

The first file (main.js) injects the Web3 API into the website, listens for the connection and checks that you are indeed connected to the Ethereum main blockchain (not the test ones).

Main.js

// Injects Web3 in the browser and uses Metamask if present

window.addEventListener('load', function() {

  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
  } else {
    console.log('No web3? You should consider trying MetaMask!');
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
  }

  // Now you can start your app & access web3 freely:
  startApp();

});

function startApp(){
  detectConnection();
  detectWeb3Version();
  detectNetwork();
  setTimeout(amendUI, 500);
}

// Check if Web3 is connected (to amend the UI)

function detectConnection(){
 
  if(web3.isConnected()) {
    document.getElementById('isweb3connected').innerHTML = 'Web3 Connected!';
    document.getElementById('isweb3connected').style.backgroundColor='Green';
  } else {
    document.getElementById('isweb3connected').innerHTML = 'No Connection';
    document.getElementById('isweb3connected').style.backgroundColor='Red';
  }

}

// Checks what provider you are connected with (either a full local node with Geth or a "light" node with Metamask)

function detectWeb3Version() {

    var versionJson = {};

    // Asynchronous version
    web3.version.getNode(function(error, result){
        if(error) {
          console.log(error);
        }
        else {

            if(result.toLowerCase().includes('metamask')){
                document.getElementById('nodeType').innerHTML = 'Metamask';
                document.getElementById('nodeType').style.backgroundColor='Green';
            } else if(result.toLowerCase().includes('testrpc')){
                document.getElementById('nodeType').innerHTML = 'Test RPC';
                document.getElementById('nodeType').style.backgroundColor='Red';
            } else {
                document.getElementById('nodeType').innerHTML = 'Geth';
                document.getElementById('nodeType').style.backgroundColor='Red';
            }

        }
    });
}

// Checks to which Ethereum blockchain you are connected: either the Mainnet (network ID = 1) or the testnets (network ID != 1)

function detectNetwork(){
 
    web3.version.getNetwork(function(error, netId){
      if(error){
        console.log(error);
      }else{
        switch (netId) {
          case '1':
            document.getElementById('netId').innerHTML = 'This is MainNet';
            document.getElementById('netId').style.backgroundColor='Green';
            break;
          case '2':
            document.getElementById('netId').innerHTML = 'This is Morden (deprecated)';
            document.getElementById('netId').style.backgroundColor='Red';
            break;
          case '3':
            document.getElementById('netId').innerHTML = 'This is Ropsten';
            document.getElementById('netId').style.backgroundColor='Red';
            break;
          case '4':
            document.getElementById('netId').innerHTML = 'This is Rinkeby';
            document.getElementById('netId').style.backgroundColor='Red';
            break;
          case '42':
            document.getElementById('netId').innerHTML = 'This is Kovan';
            document.getElementById('netId').style.backgroundColor='Red';
            break;          
          default:
            document.getElementById('netId').innerHTML = 'This is an unknown network.';
            document.getElementById('netId').style.backgroundColor='Red';
        }        
      }

  });

}

// This is for changing the UI in line with the results of the code above

function amendUI(){

  document.getElementById('transferButton').disabled = true;
  document.getElementById('etherAmount').disabled = true;
  document.getElementById('fromAccount').disabled = true;
  document.getElementById('toAccount').disabled = true;
  document.getElementById('dataToSend').disabled = true;

  var isweb3connected = document.getElementById('isweb3connected').innerHTML;
  var nodeType = document.getElementById('nodeType').innerHTML;
  var networkID = document.getElementById('netId').innerHTML;

  if((isweb3connected == 'Web3 Connected!') && (nodeType == 'Metamask') && (networkID == 'This is MainNet') ){
    document.getElementById('transferButton').disabled = false;
    document.getElementById('etherAmount').disabled = false;
    document.getElementById('fromAccount').disabled = false;
    document.getElementById('dataToSend').disabled = false;

  }

}

The second file (I called it Accountaction.js) is the one that allows the transaction to happen.

It reads the values entered in the form and runs the Web3 “sendTransaction( )” function to execute the transfer.

The return value is the “transaction hash” that can be used to audit the transaction by connecting to a blockchain explorer (such as etherscan).

Accountaction.js

// Sets to Address in the form
var massiAccountAddress = '0xf17f52151ebef6c7334fad080c5704d77216b732';
document.getElementById('toAccount').value = massiAccountAddress;

// Sets from Address in the form
var fromAccountAddress = web3.eth.defaultAccount;
document.getElementById('fromAccount').value = fromAccountAddress;

function doSendTransaction(){

    // Creates the Transaction object
    var transactionObject = {};

    var valueInEther = document.getElementById('etherAmount').value;
    var valueInWei = web3.toWei(valueInEther,'ether');

    var datainascii = document.getElementById('dataToSend').value;

    // Sets the four parameters of the transaction object drawing from the form
    transactionObject.from = document.getElementById('fromAccount').value;
    transactionObject.to = document.getElementById('toAccount').value;
    transactionObject.value = valueInWei;
    transactionObject.data = web3.toHex(datainascii);

    web3.eth.sendTransaction(transactionObject, function(err, transactionHash) {
      if (err){
        document.getElementById('transactionHashLink').innerHTML = 'The transaction was unsuccessful';
        document.getElementById('transactionHashPanel').style.display = 'block';
        console.log(err);
      } else{
        document.getElementById('transactionHashLink').href = 'https://etherscan.io/tx/' + transactionHash;
        document.getElementById('transactionHashLink').innerHTML = 'Check on Etherscan!';
        document.getElementById('transactionHashPanel').style.display = 'block';
        console.log(transactionHash); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385"
      }
    });
}

Hope you enjoyed the article. Do not forget to send some Ether if you did.

Published inFinanceProgrammingTechnology