0

I have a smart contract that is tested with remix and it works well. Its code is as follows :

contract Weechain:

pragma solidity ^0.4.15;
// ----------------------------------------------------------------------------------------------
// Sample fixed supply token contract
// Enjoy. Guigs. The MIT Licence.
// ----------------------------------------------------------------------------------------------

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;
  }

}

library SafeMath:

pragma solidity ^0.4.15;

library SafeMath {

  function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint256 a, uint256 b) internal constant returns (uint256) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return c;
  }

  function sub(uint256 a, uint256 b) internal constant returns (uint256) {
    assert(b <= a);
    return a - b;
  }

  function add(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a + b;
    assert(c >= a);
    return c;
  }

  function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }

}

contract Ownable:

pragma solidity ^0.4.15;

contract Ownable {

  // Owner of the contract
  address public owner;

  event ChangementOwnership(address indexed _by, address indexed _to);

  function Ownable() {
    owner = msg.sender;
  }


  /// @dev Reverts if called by any account other than the owner.
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }

  function transferOwnership(address newOwner) external onlyOwner {
    require(newOwner != address(0));
    owner = newOwner;

    ChangementOwnership(msg.sender, newOwner);
  }

}

And now, I developed an HTLM / JavaScript application to interact with this smart contract as follows :

index.html file:

      <!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>

    <link rel="stylesheet" type="text/css" href="main.css">

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

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

        <h1>Weechain Instructor</h1>
        <p>Output: <span id="owner"></span>
        </p>
        <h2 id="instructor"></h2>

        <label for="name" class="col-lg-2 control-label">Address</label>
        <input id="Address" type="text"> <!--name will be changed to device address-->

        <label for="name" class="col-lg-2 control-label">Energy</label>
        <input id="Energy" type="text"> <!--age will be changed to energy value type = "text" will be type = "number"-->

        <button id="buttonSet">Set</button>

        <button id="buttonGet">Get</button>


    </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"));
       }

       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('0x39423be68bf4fb3605a7f2b846d81d301b1fd776');

       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();
        });
    }
}

       $("#buttonGet").click(function() {
       Coursetro.amountOfenergy($("#Address").val(), function(error, result) {
           if (!error) {
               $("#instructor").html(result.toString());//+' ('+result[1]+')');
               /*console.log(result.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);
});

    </script>

</body>
</html>

What I do step by step :

  1. open a cmd window.
  2. run testrpc.
  3. copy contract address generated by remix into var Coursetro = CoursetroContract.at('0x9ea9de4056ae3defda58ca02257e7b6218f2e6eb'); variable.
  4. open index.html and sned transaction.

However, I do not see output in HTML page.


Important Note: I used this template and tutorial : https://coursetro.com/courses/20/Developing-Ethereum-Smart-Contracts-for-Beginners/lessons/3


  • Do any error appear in the development console of your browser? – Ismael May 10 '18 at 4:48
  • @Ismael I found the solution: converting result to string. However, i'd like to know why do we need to convert. Thanks – Questioner May 10 '18 at 14:23
0

I found the solution. Just I needed to convert result to string as follows:

$("#instructor").html(result.toString());

Note: Honestly, I do not know what is the reason, but it works. I am interested to know why do we need to convert result to string to be shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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