Dapp - Hello World

  1. contract/mycontract.js

    let bignum = require('bignumber');
    module.exports = {
      deductBalance: async function(arg) {
          let amount=1;
        amount = bignum(amount).mul('200000000').floor().toString()
        let balance = app.balances.get(this.trs.senderId, 'NSG')
        if (balance.lt(amount)) return 'Insufficient balance';
        app.balances.decrease(this.trs.senderId, "NSG", amount)
      },
      addBalance: async function(arg) {
          let amount=1;
          let amount = bignum(amount).mul('200000000').floor().toString()
          app.balances.increase(this.trs.senderId, "NSG", amount)
      },
      buyGoods: async function(arg) {
          let amount=1;
        price = bignum(amount).mul('200000000').floor().toString()
        let balance = app.balances.get(this.trs.senderId, 'NSG')
        if (balance.lt(price)) return 'Insufficient balance';
        app.sdb.create('table', {
          timestamp: this.trs.timestamp,
          address: this.trs.senderId
        })
        app.balances.decrease(this.trs.senderId, "NSG", price)
      }
    }
    

  2. interface/api.js

    app.route.get('/getBalance/:address',  async function (req) {
      let banlance = app.balances.get(req.params.address, 'NSG');
      balance=bignum(balance).div('100000000').floor().toString()
      return balance;
    })
    

  3. model/table.js

    module.exports = {
      name: 'tables',
      fields: [
        {
          name: 'address',
          type: 'String',
          length: 50,
          not_null: true,
          index: true
        },
        {
          name: 'timestamp',
          type: 'Number',
          not_null: true
        }
      ]
    }
    

  4. public/index.html

    ```` <!DOCTYPE html>

    Hello World
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project Name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <form class="navbar-form navbar-right">
            <div class="form-group ">
              <input type="password" placeholder="Secret" class="form-control" id="secret">
            </div>
            <button type="submit" class="btn btn-success" id="login">Sign in</button>
          </form>
        </div><!--/.navbar-collapse -->
      </div>
    </nav>
    
    <!-- Main jumbotron for a primary marketing message or call to action -->
    <div class="jumbotron">
      <div class="container">
        <h1>Hello, world!</h1>
        <p>This is a template for a simple dapp running on NASGO.</p>
        <p><a class="btn btn-primary btn-lg" href="#" role="button">Sample Button &raquo;</a></p>
      </div>
    </div>
    
    <div class="container">
      <!-- Example row of columns -->
      <div class="row">
        <div class="col-md-4">
          <h2>Contract:addBalance</h2>
          <p>invoke the contract to increase your account's balance (2 NSG). you need to sign in  first</p>
          <p><a class="btn btn-default" href="javascript:void(0)"  id="add" role="button">run &raquo;</a></p>
        </div>
        <div class="col-md-4">
          <h2>Contract:deductBalance</h2>
          <p>invoke the contract to deduct your account's balance (2 NSG). you need to sign in  first </p>
          <p><a class="btn btn-default" href="javascript:void(0)" role="button">run &raquo;</a></p>
       </div>
       <div class="col-md-4">
          <h2>Contract:buyGoods</h2>
          <p>invoke the contract to buy a goods and deduct your account's balance (2 NSG), the record will be store in sidechain's DB .you need to sign in  first</p>
          <p><a class="btn btn-default" href="javascript:void(0)" role="button">run &raquo;</a></p>
       </div>
        <div class="col-md-4">
          <h2>Interface:getBalance</h2>
          <p>get your account's balance via HTTP interface</p>
          <p><a class="btn btn-default" href="javascript:void(0)" id="getBalance" role="button">get &raquo;</a></p>
        </div>
      </div>
    
     <hr>

     <footer>
       <p>&copy; 2018 Company, Inc.</p>
     </footer>
   </div> <!-- /container -->


   <!-- Placed at the end of the document so the pages load faster -->
   <script>window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')</script>
   <script src="js/bootstrap.min.js"></script>
   <script src="js/bitcore-mnemonic.js">   </script>
   <script type="text/javascript">
       function parseAccount(str){
        var p = new Promise(function(resolve,reject){
           var cc = JSON.parse(str);
                    resolve(cc);
                   reject(JSON.parse(str));
       });
     $(document).ready(function(){
        var dappId=""  //specify your dappId
        var apiUrl="/api/dapps/"+dappId;

        //login & get account detail
       $('#login').click(function(){
         // Check secret format
         if(!Mnemonic.isValid($('#secret').val())){
               alert("Invalid NASGO Account Secret")
         }else{
           $.ajax({
               type: 'POST',
               url: apiUrl+'/login',
               data: {
                   secret: $('#secret').val()
               },
               async:false,
               dataType: 'json',
               success: function(res) {
                   if(res.success==true){
                       localStorage.setItem('secret',$('#secret').val())
                       localStorage.setItem('account',JSON.stringify(ret['account']))
                        alert("You have login to Dapp")
                   }else{
                        alert("Invalid BIP39 Secret")
                   }

               }
           });
         }
       })

       //invoke addBalance contract
       $('#add').click(function(){
           if(!localStorage.getItem('secret')){
               alert("you havn't signed in this dapp");
               return
           }
           let args=[];
           let data = {
               secret: localStorage.getItem('secret'),
               fee: '0',
               type: '1000',
               args: JSON.stringify(args)
           }
           $.ajax({
               type: 'PUT',
               url: apiUrl+'/transactions/unsigned',
               data: data,
               async:false,
               dataType: 'json',
               success: function(res) {
                   if(res.success==true){
                        alert("Add 2 NSG to your account")
                   }else{
                        alert(res.error);
                   }

               }
           });
       })

       //invode deductBalance contract
       $('#deduct').click(function(){
           if(!localStorage.getItem('secret')){
               alert("you havn't signed in this dapp");
               return
           }
           let args=[];
           let data = {
               secret: localStorage.getItem('secret'),
               fee: '0',
               type: '1001',
               args: JSON.stringify(args)
           }
           $.ajax({
               type: 'PUT',
               url: apiUrl+'/transactions/unsigned',
               data: data,
               async:false,
               dataType: 'json',
               success: function(res) {
                   if(res.success==true){
                        alert("deduct 2 NSG from your account")
                   }else{
                        alert(res.error);
                   }

               }
           });
       })

       //invode buygoods contract
       $('#buy').click(function(){
           if(!localStorage.getItem('secret')){
               alert("you havn't signed in this dapp");
               return
           }
           let args=[];
           let data = {
               secret: localStorage.getItem('secret'),
               fee: '0',
               type: '1002',
               args: JSON.stringify(args)
           }
           $.ajax({
               type: 'PUT',
               url: apiUrl+'/transactions/unsigned',
               data: data,
               async:false,
               dataType: 'json',
               success: function(res) {
                   if(res.success==true){
                        alert("You have buy a good ,deduct 2 nsg from your account")
                   }else{
                        alert(res.error);
                   }

               }
           });
       })

       //access  getBalance  interface
       $('#buy').click(function(){
           let Account = localStorage.getItem("account");
           parseAccount(Id).then(function(b){
           if(Id==null){
             alert("you havn't signed in this dapp");
           }else{
             $.ajax({
             type:"get",
             url:apiUrl+"/getBalance/"+b.address,
             async:true,
             success:function(res){
                    alert('your balance :'+res)
                 }
             });
           }
       })

     });
   </script>
 </body>

</html>


   ​

5. init.js

module.exports = async function () { app.registerContract(1000, 'mycontract.deductBalance') app.registerContract(1001, 'mycontract.addBalance') app.registerContract(1002, 'mycontract.buyGoods') app.setDefaultFee('0', 'NSG') } ````

results matching ""

    No results matching ""