0

I want to see Event logs in UI. And for this, I use following code in JavaScript :

var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'});
               EnergyEvent.watch(function(err, result) {
  if (err) {
    console.log(err)
    return;
  }

})

What is missed in my JavaScript code ?

You can see full code of my contract and JavaScript code in bellow:

solidity code :

    pragma solidity ^0.4.15;

import './SafeMath.sol';
import './Ownable.sol';

contract Weechain is Ownable{

  using SafeMath for uint256;

  uint256 public energyTotalSupply;
  uint256 public powerTotalSupply;

  struct Device {
    uint256 energyValue;
    uint256 powerValue;
  }
  mapping(address => Device) amount;

  event setEnergyEvent(address indexed device, uint256 energy); 
  event setPowerEvent(address indexed device, uint256 power);
  event setPayloadEvent(uint256 indexed SQN, string payload);

  // Constructor
  function Weechain() {

    energyTotalSupply = 0;
    powerTotalSupply = 0;

    amount[owner].energyValue = energyTotalSupply;
    amount[owner].powerValue = powerTotalSupply;
  }

  function amountOfenergy(address dev) constant returns (uint256 energy) {
    return amount[dev].energyValue;
  }
  function amountOfpower(address dev) constant returns (uint256 power) {
    return amount[dev].powerValue;
  }

  function setPayload(uint256 SQN, string payload) public returns (bool) {

    emit setPayloadEvent(SQN, payload);

    return true;
  }

  function setEnergy(address dev, uint256 energy) public returns(bool) {
    require(dev != address(0));

    amount[dev].energyValue = amount[dev].energyValue.add(energy);
    energyTotalSupply = energyTotalSupply.add(energy);

    emit setEnergyEvent(dev, energy);

    return true;
}

    function setPower(address dev, uint256 power) public returns (bool) {
    require(dev != address(0));

    amount[dev].powerValue = amount[dev].powerValue.add(power);
    powerTotalSupply = powerTotalSupply.add(power);

    emit setPowerEvent(dev, power);

    return true;
  }

}

Javascript and HTML code :

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Weechain Smart Contract</title>



    <script src="./node_modules/web3/dist/web3.min.js"></script>

    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
html, body, h1, h2, h3, h4, h5, h6 {
  font-family: "Courier New", Courier, monospace
}
</style>

<style>
.input {
    background-color: #373E43;
    color: black;
}
</style>

<style>
.header {
    text-align: center;
    background-color: #373E43;
    color: white;
}
/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}
/* Create three equal columns that floats next to each other */
.column {
    float: left;
    width: 33.33%;
    padding: 15px;
}
</style>

<style>
table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    text-align: left;
    padding: 8px;
}
tr:nth-child(odd){background-color: #373E43; color: white;}
tr:nth-child(even){background-color: #373E43; color: white;}
</style>

<style>
.output {
background-color: #373E43; 
color: white;
text-align: center;
}
</style>

</head>
<body>
    <div class="w3-container">

    <div class="header">
  <h1>Weechain</h1>
</div>

        <!-- <p>Output: <span id="owner"></span> 
        </p> -->
        <div class="output">
        <p id="Output" >  </p>
        </div>

<div class="row">
<div class="input">
  <div class="column">

        <label for="name" class="col-lg-2 control-label">Device Address</label>
        <input id="Address" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <label for="name" class="col-lg-2 control-label">Energy</label>
        <input id="Energy" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <button id="buttonSet" class="w3-button w3-black w3-round-large">Set Energy Value</button>

        <button id="buttonGet" class="w3-button w3-black w3-round-large">Get Energy Balance</button>

   </div>
   <div class="column">

        <label for="name" class="col-lg-2 control-label">Device Address</label>
        <input id="AddressPower" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <label for="name" class="col-lg-2 control-label">Power</label>
        <input id="Power" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <button id="buttonSetPower" class="w3-button w3-black w3-round-large">Set Power Value</button>

        <button id="buttonGetPower" class="w3-button w3-black w3-round-large">Get Power Balance</button>

   </div>
   <div class="column">

        <label for="name" class="col-lg-2 control-label">Sequence Number</label>
        <input id="SQN" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <label for="name" class="col-lg-2 control-label">Payload</label>
        <input id="Payload" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> 

        <button id="buttonSetPayload" class="w3-button w3-black w3-round-large">Set Payload Value</button>

   </div>
  </div>
</div>

    <div class="row">
        <div>
          <h2 class="sub-header">Energy Transactions</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Transaction Hash</th>
                  <th>Device Address</th>
                  <th>Energy Value</th>
                </tr>
              </thead>
              <tbody id="transactions">
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="row">
        <div>
          <h2 class="sub-header">Power Transactions</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Transaction Hash</th>
                  <th>Device Address</th>
                  <th>Power Value</th>
                </tr>
              </thead>
              <tbody id="transactionsPower">
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="row">
        <div>
          <h2 class="sub-header">Payload Transactions</h2>
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Transaction Hash</th>
                  <th>Payload</th>
                </tr>
              </thead>
              <tbody id="transactionsPayload">
              </tbody>
            </table>
          </div>
        </div>
      </div>


    </div>

    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

    <script>
       if (typeof web3 !== 'undefined') {
           web3 = new Web3(web3.currentProvider);
       } else {
           web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
       }

       //this.watchEvents = this.watchEvents.bind(this)

       web3.eth.defaultAccount = web3.eth.accounts[0];
/*
       var CoursetroContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_fName","type":"string"},{"name":"_age","type":"uint256"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructor","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]);
*/
    var CoursetroContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"energyTotalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"dev","type":"address"}],"name":"amountOfenergy","outputs":[{"name":"energy","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"powerTotalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dev","type":"address"},{"name":"energy","type":"uint256"}],"name":"setEnergy","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"SQN","type":"uint256"},{"name":"payload","type":"string"}],"name":"setPayload","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"dev","type":"address"}],"name":"amountOfpower","outputs":[{"name":"power","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"dev","type":"address"},{"name":"power","type":"uint256"}],"name":"setPower","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"device","type":"address"},{"indexed":false,"name":"energy","type":"uint256"}],"name":"setEnergyEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"device","type":"address"},{"indexed":false,"name":"power","type":"uint256"}],"name":"setPowerEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"SQN","type":"uint256"},{"indexed":false,"name":"payload","type":"string"}],"name":"setPayloadEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_by","type":"address"},{"indexed":true,"name":"_to","type":"address"}],"name":"ChangementOwnership","type":"event"}]);

       var Coursetro = CoursetroContract.at('0x8db88aaa4990408dfe41d6c77a76a09cba95d982');
/*
       var utils = require("./utils.js");
var _ = require("lodash");
var Promise = require("bluebird");

module.exports = {
    assertEvent: function(contract, filter) {
        return new Promise((resolve, reject) => {
            var event = contract[filter.event]();
            event.watch();
            event.get((error, logs) => {
                var log = _.filter(logs, filter);
                if (log) {
                    resolve(log);
                } else {
                    throw Error("Failed to find filtered event for " + filter.event);
                }
            });
            event.stopWatching();
        });
    }
}
*/



/*
var instructorEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'});
instructorEvent.watch(function(error, result){
    alert(1);
});
*/

/*
var event = testing.event_res(function(error, result) {
    if (!error)
        console.log(result.args);
    else
        console.log(error);
});
*/

 var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'});
               EnergyEvent.watch(function(err, result) {
  if (err) {
    console.log(err)
    return;
  }
  // append details of result.args to UI
})
/*
var instructorEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'});   
instructorEvent.watch(function(error, EventLogs){
if (!error) {
    alert(1);
    console.log('Event Logs:' + EventLogs);
    } else
                console.log('Event Logs error:' + error);

});
*/

       $("#buttonGet").click(function() {
       Coursetro.amountOfenergy($("#Address").val(), function(error, result) {
           if (!error) {
               $("#Output").html('Energy value of device with address ' + $("#Address").val() + ' equals '+ result.toString());//+' ('+result[1]+')');
               console.log('Energy value of device with address \"' + $("#Address").val() + '" equals "'+ result.toString() + '"');

               var receipt = web3.eth.getTransactionReceipt('0x5337d09cc54c1ec80970b7c74881f01cbf5653293873d54617b64fad21f6fb68');
               console.log(' tx hash: ' + receipt.toString());
               /*console.log("address\tfrom\t\tto\tamount\tblockHash\tblockNumber\tevent\tlogIndex\ttransactionHash\ttransactionIndex");*/
           } else
                console.log(error);
       });

       });
/*
       $("#buttonSet").click(function() {
           //Coursetro.setPayload($("#name").val(), $("#age").val());
           Coursetro.setEnergy($("#Address").val(), $("#Energy").val());
           //Coursetro.setPayload($("#name").val());
       });
*/
       $("#buttonSet").click(function() {
    var estd_gas = Coursetro.setEnergy.estimateGas($("#Address").val(), $("#Energy").val());
    console.log(estd_gas);
    var params = {
        gas: Math.round(estd_gas * 1.25),
        from: web3.eth.accounts[0]
    };

    Coursetro.setEnergy.sendTransaction($("#Address").val(), $("#Energy").val(), params, function(error, TxHash) {
           if (!error) {

               $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')');
               $('#transactions').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Address").val() + '</td><td>' + $("#Energy").val() + '</td></tr>')
               console.log(TxHash.toString());




               //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4');
               //var receipt2 = web3.toAscii(TxHash.input);
               //console.log(receipt.toString());

               //Coursetro.setEnergyEvent({},{fromBlock: 0,toBlock: 'latest'}).watch((error, event) => {})

               /*var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'});
               EnergyEvent.watch(function(err, result) {
  if (err) {
    console.log(err)
    return;
  }
  // append details of result.args to UI
})*/



               //console.log(receipt2.toString());
           } else
                console.log(error);
       });
});

////


///////////////////////



 $("#buttonSetPower").click(function() {
    var estd_gas = Coursetro.setPower.estimateGas($("#Address").val(), $("#Power").val());
    console.log(estd_gas);
    var params = {
        gas: Math.round(estd_gas * 1.25),
        from: web3.eth.accounts[0]
    };
    Coursetro.setPower.sendTransaction($("#Address").val(), $("#Power").val(), params, function(error, TxHash) {
           if (!error) {
               $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')');
               $('#transactionsPower').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Address").val() + '</td><td>' + $("#Power").val() + '</td></tr>')
               console.log(TxHash.toString());
               //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4');
               //var receipt2 = web3.toAscii(TxHash.input);
               console.log(receipt.toString());
               //console.log(receipt2.toString());
           } else
                console.log(error);
       });
});



$("#buttonGetPower").click(function() {
       Coursetro.amountOfpower($("#Address").val(), function(error, result) {
           if (!error) {
               $("#Output").html('Power value of device with address ' + $("#Address").val() + ' equals '+ result.toString());//+' ('+result[1]+')');
               console.log('Power value of device with address \"' + $("#Address").val() + '" equals "'+ result.toString() + '"');

               //var receipt = web3.eth.getTransactionReceipt('0x5337d09cc54c1ec80970b7c74881f01cbf5653293873d54617b64fad21f6fb68');
               console.log(' tx hash: ' + receipt.toString());
               /*console.log("address\tfrom\t\tto\tamount\tblockHash\tblockNumber\tevent\tlogIndex\ttransactionHash\ttransactionIndex");*/
           } else
                console.log(error);
       });

       });







////////////////////   






       $("#buttonSetPayload").click(function() {
    var estd_gas = Coursetro.setPayload.estimateGas($("#SQN").val(), $("#Payload").val());
    console.log(estd_gas);
    var params = {
        gas: Math.round(estd_gas * 1.25),
        from: web3.eth.accounts[0]
    };
    Coursetro.setPayload.sendTransaction($("#SQN").val(), $("#Payload").val(), params, function(error, TxHash) {
           if (!error) {
               $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')');
               $('#transactionsPayload').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Payload").val() + '</td></tr>')
               console.log(TxHash.toString());
               //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4');
               //var receipt2 = web3.toAscii(TxHash.input);
               console.log(receipt.toString());
               //console.log(receipt2.toString());
           } else
                console.log(error);
       });
});



////////////////


    // TODO: trigger event when vote is counted, not when component renders







    </script>

</body>
</html>

Note 1 : I used this tutorial : https://media.consensys.net/technical-introduction-to-events-and-logs-in-ethereum-a074d65dd61e

Update : I changed my JavaScript code regarding to comment of User Ismael. However, I do not see still the event logs.

2
  • You are setting your watch event after the transaction is sent and you have to do it before.
    – Ismael
    May 13, 2018 at 16:49
  • @Ismael Thank you. I moved the code before click event for setEnergy transaction, however I do not still see the loge in UI. there is still some thing wrong in Javascript code ? Thanks
    – Questioner
    May 13, 2018 at 17:59

1 Answer 1

2

If you want to develop a web application that interacts with a smart contract (send transaction, pull events, etc.). I really recommend you to use Truffle (to compile/deploy/test smart contracts) and truffle-contract library (to interact from a web page).

Smart contract

Step 1: Install Truffle

$ npm install -g truffle

Step 2: Initialise the project

$ truffle init

Step 3: Add your contract and libraries (openzepellin) in the folder "contract"

$contracts$ ls -l
-rw-rw-r-- 1 gjeanmart gjeanmart  515 May 13 17:34 Migrations.sol
-rw-rw-r-- 1 gjeanmart gjeanmart 1010 Oct 26  1985 Ownable.sol
-rw-rw-r-- 1 gjeanmart gjeanmart 1134 Oct 26  1985 SafeMath.sol
-rw-rw-r-- 1 gjeanmart gjeanmart 1646 May 13 18:53 Weechain.sol

Step 4: Write a deployment script in the folder "migration"

$ vi 1_initial_migration.js
var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};


$ vi 2_deploy_contracts.js
var Weechain = artifacts.require("./Weechain.sol");

module.exports = function(deployer) {
    deployer.deploy(Weechain)
};

Step 5: Write the configuration in "truffle.js"

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 9545,
      network_id: "*" // Match any network id
    }
  }
};

Step 6: Deployment

Execute truffle develop to run a sandbox Ethereum Blockchain.

$ truffle develop
Truffle Develop started at http://127.0.0.1:9545/

Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de

Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5

Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat

⚠️  Important ⚠️  : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.

Then run migrate to deploy your smart contract on this blockchain.

truffle(develop)> migrate
Compiling ./contracts/Ownable.sol...
Compiling ./contracts/SafeMath.sol...
Compiling ./contracts/Weechain.sol...
Compiling Ownable.sol...
Compiling SafeMath.sol...

Compilation warnings encountered:

/home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:24:3: Warning: No visibility specified. Defaulting to "public".
  function Weechain() {
  ^ (Relevant source part starts here and spans across multiple lines).
,/home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:33:3: Warning: No visibility specified. Defaulting to "public".
  function amountOfenergy(address dev) constant returns (uint256 energy) {
  ^ (Relevant source part starts here and spans across multiple lines).
,/home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:36:3: Warning: No visibility specified. Defaulting to "public".
  function amountOfpower(address dev) constant returns (uint256 power) {
  ^ (Relevant source part starts here and spans across multiple lines).

Writing artifacts to ./build/contracts

Using network 'develop'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xcb0ccc3f1fbe419b96b95c6ef63e54ac8557061922702e89ae44e1c288508247
  Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0
Saving successful migration to network...
  ... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying Weechain...
  ... 0x0bd3d3d1534c391abc50a1e3164499e45da9bb49b4501aa9fde3515440d50c7e
  Weechain: 0x345ca3e014aaf5dca488057592ee47305d9b3e10
Saving successful migration to network...
  ... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0
Saving artifacts...
truffle(develop)> 

Your smart contract are now deployed on a sandbox blockchain accessible with the RPC endpoint http://localhost:9545 and the following accounts are created and funded each with 100 ethers (these account can be imported in Metamask for testing)

Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de

Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5

Web Application

Now, the web application, you will see that now, it is very easy and clean to access the smart contract from your webpage.

Step 1: Use nodejs to serve your webapplication. Create a file serve.js

$ npm i -s connect serve-static truffle-contract
$ vi serve.js
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080, function(){
    console.log('Server running on 8080...');
});

Step 2: Run the webserver

$ node serve

Now your index.html http://localhost:8080 page is available as well as the Truffle Smart contract artifacts (sort of JSON file containing everything: ABI, Addresses, etc.) http://localhost:8080/build/contracts/Weechain.json

Step 3: initialise Web3 and load the contracts

  // Load Web3
  console.log("### LOAD WEB3")
  if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
  } else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }
  console.log(web3)

  // Default account
  console.log("### DEFAULT ACCOUNT")
  web3.eth.defaultAccount = web3.eth.accounts[0];
  console.log(web3.eth.defaultAccount)

  // Get Truffle Contract artefact
  console.log("### Get Truffle Contract artefact")
  var Coursetro;
  $.getJSON("http://localhost:8080/build/contracts/Weechain.json", function( data ) {
    console.log(data)

    // Load Contract
    var CoursetroContract = TruffleContract(data);
    CoursetroContract.setProvider(web3.currentProvider);

    // Get contract instance
    CoursetroContract.deployed().then(function(instance) {
      Coursetro = instance;
      console.log(Coursetro)
    });

  });

Step 4: Send transactions and get the events triggered from the receipt

  $("#buttonSet").click(function() {
      Coursetro.setEnergy($("#Address").val(), $("#Energy").val()).then(function(receipt) {
        console.log(receipt)
        console.log("Logs trigerred for this transaction:")
        console.log(receipt.logs)
      }).catch(function(error) {
        console.log(error)
      });

  });

enter image description here


This demonstrates how the Truffle framework (+Ganache) can abstract and simplify most of the complexity of Web3 development in general. The tutorial you mentioned is good but unfortunately June 2016 sounds a bit old. Blockchain technologies are moving and evolving very quickly !

Full code example

10
  • Thank you for your perfect answer. However, when I open your HTML file, I don't get transaction hash. In fact, I created a new folder entitled "Weechain_truffle_version" and copied all your files in your Github. Then, I open index.html file and send a transaction (ex: setEnergy) . However, I don't receive Tx hash in UI. Should I do some additional thing ? Thanks again.
    – Questioner
    May 15, 2018 at 11:48
  • In fact, when I run truffle init I receive this error : Error message Maybe that's the problem, isn't it ? Thank you
    – Questioner
    May 15, 2018 at 11:56
  • About truffle init, I think it's normal because the problem is already initialized if you pull my code. May 15, 2018 at 11:58
  • About the transaction issue, I had some problems like that in that past with truffle develop (new feature). So I generally manually start a sandbox blockchain ganache-cli -p 9545 (in another console) and run truffle migrate instead of truffle develop followed by > migrate May 15, 2018 at 11:58
  • Thank you again, but I confused a bit.Please consider I downloaded all your package in your Github in a folder entitled "Weechain_truffle_version" Screen in my computer. then, I open a cmd. I did npm install -g truffle. However, when I run truffle init , I receive this error : Error. Then, I open another cmd and run ganache-cli -p 9545, fortunately it works and I get this output : ganache . I am grateful to you if you could let me know which commands should I run with cmd respectively. Thx
    – Questioner
    May 15, 2018 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.