星云链智能合约开发(七):Dapp开发

安装neb.js

neb.js提供javascript开发的API接口

  1. 创建一个neb文件夹,在终端命令行中进入该文件夹,克隆neb.js
    git clone https://github.com/nebulasio/neb.js.git
  2. 会新建一个neb.js文件夹,进入该文件夹,安装所有依赖
    npm install
  3. 安装gulp
    npm install gulp
  4. 打包生成neb.js等文件
    gulp
  5. 执行成功会生成/dist文件夹,文件夹中会生成我们要使用js文件。
    • neb.js:Used in browser side. Including outside dependency.
    • neb-light.js:Used in Repl console. Not including outside dependency.
    • nebulas.js: Fully functional in the browser. Users can create an address, sign a transaction, and deploy/call a smart contract.

安装nebPay

NebPay SDK 为不同平台的交易提供了统一的支付接口,开发者在Dapp页面中使用NebPay API可以通过浏览器插件钱包、手机app钱包等实现交易支付和合约调用。

github地址:https://github.com/nebulasio/nebPay

安装方法同上。会生成nebPay.js文件

开发Dapp

要实现的功能非常简单:

  • 调用合约中的save方法发布信息
  • 调用合约中的read方法读取信息

建立项目

将前面生成的nebulas.js和nebPay.js放在libs文件夹下,我的目录结构如下:

image

index.html源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>星云链Dapp</title>
</head>
<body>
    <div>
        <h1>发布信息</h1>
        <div>标题:</div>
        <div><input type="text" id="title" style="width:370px"/></div>
        <div>内容:</div>
        <div><textarea cols="50" rows="10" id="content"></textarea></div>
        <div><input type="button" value="发布" id="publish"></div>
    </div>

    <div>
        <h1>执行结果:</h1>
        <div>
            <textarea cols="100" rows="5" id="result"></textarea>
        </div>
    </div>

    <br/>
    <hr/>

    <div>
        <h1>查询信息:</h1>
        <div>作者地址:</div>
        <div>
            <input type="text" id="author" style="width:370px"/>&nbsp;<input type="button" id="search" value="查询" />
        </div>
        <div>信息:</div>
        <div id="queryResult" style="height:100px;width:370px;border:1px solid #aaa">

        </div>
    </div>

    <div style="height:50px"></div>

    <script src="libs/jquery-3.3.1.min.js"></script>
    <script src="libs/nebulas.js"></script>
    <script src="libs/nebPay.js"></script>
    <script>
        "use strict";

        // 合约地址
        var dappAddress = "n1hmSwsxM2S1Zo1Q5kMuQaKcnS1Xu8ATBbx";

        // 直接访问星云链的api
        var nebulas = require("nebulas"),
            Account = nebulas.Account,
            neb = new nebulas.Neb();
        // 设置使用的网络
        neb.setRequest(new nebulas.HttpRequest("https://testnet.nebulas.io"));

        // NebPay SDK 为不同平台的交易提供了统一的支付接口
        // 开发者在Dapp页面中使用NebPay API可以通过浏览器插件钱包、手机app钱包等实现交易支付和合约调用。
        var NebPay = require("nebpay");
        var nebPay = new NebPay();

        // 执行合约返回的交易流水号,用于查询交易信息
        var serialNumber;

        $("#publish").click(function () {
            var title = $("#title").val().trim();
            var content = $("#content").val().trim();

            if (title === "" || content === "") {
                alert("标题或内容不能为空!");
                return;
            }

            // 执行合约中的save方法
            serialNumber = nebPay.call(dappAddress, "0", "save", "[\"" + title + "\",\"" + content + "\"]", {
                listener : function (resp) {
                    console.log(resp);
                    // 清空信息
                    $("#title").val("");
                    $("#content").val("");

                    // 延迟5秒执行
                    intervalQuery = setInterval(function () {
                        queryResultInfo();
                    }, 5000);
                }
            });
        });
        // 定时器
        var intervalQuery;
        // 根据交易流水号查询执行结果数据
        function queryResultInfo() {
            nebPay.queryPayInfo(serialNumber)
                .then(function (resp) {
                    $("#result").val(resp);
                    var respObject = JSON.parse(resp)
                    if(respObject.code === 0){
                        alert(`提交信息成功!`);
                        clearInterval(intervalQuery);
                    }
                })
                .catch(function (err) {
                   console.log(err);
                })
        }

        // 查看信息
        $("#search").click(function () {
            var author = $("#author").val().trim();
            if (author === "") {
                alert("作者地址不能为空!");
                return;
            }

            var from = Account.NewAccount().getAddressString();
            var value = "0";   // 金额
            var nonce = "0";   // 交易序号
            var gas_price = "1000000" // 手续费价格
            var gas_limit = "2000000" // 手续费限制
            var callFunction = "read";
            var callArgs = "[\"" + author + "\"]"; //in the form of ["args"]
            var contract = { // 合约
                "function": callFunction,  // 方法名
                "args": callArgs            // 参数
            }

            // 使用api.call执行合约中的方法
            neb.api.call(from, dappAddress, value, nonce, gas_price, gas_limit, contract).then(function (resp) {
                var ressultObj = JSON.parse(resp.result);
                $("#result").val(resp.result);

                var title = ressultObj.title;
                var content = ressultObj.content;
                var time = new Date(ressultObj.timestamp);

                $("#queryResult").html("标题:" + title + "<br/>" + "内容:" + content + "<br/>" + "时间:" + time);

            }).catch(function (err) {
                console.log("error:" + err.message)
            })
        });
    </script>
</body>
</html>

运行Dapp

发布信息

第一步

image

第二步

image

第三步

image

第四步

image

第五步

image

根据流水号查询的执行结果数据如下:

{
    "code": 0,
    "data": {
        "data": "eyJGdW5jdGlvbiI6InNhdmUiLCJBcmdzIjoiW1wi5rWL6K+V5Y+R5biD5L+h5oGvXCIsXCLmtYvor5XlnKjmmJ/kupHpk77kuIrlj5HluIPkv6Hmga9cIl0ifQ==",
        "contractAddress": "",
        "type": "call",
        "nonce": 1,
        "gasLimit": "200000",
        "gasUsed": "",
        "chainId": 1001,
        "from": "n1GjJ6CtCj9RLgcZfUD99A3fgA9fX2kuEJ5",
        "to": "n1hmSwsxM2S1Zo1Q5kMuQaKcnS1Xu8ATBbx",
        "value": "0",
        "hash": "69640cacc2075b2af7a83d3882a4da92ab5b820b08ea182f9709e0f339fc47c5",
        "gasPrice": "1000000",
        "status": 2,
        "timestamp": 1525943841
    },
    "msg": "success"
}

查询信息

image

至此,一个基于星云链开发的简单的Dapp就完成了。

总结

  • 智能合约就好比传统开发中的服务端,只不过是搭建在区块链的节点上;
  • Dapp就好比传统开发中的前端,通过给定的方式调用我们发布的智能合约中的方法;
  • 数据存储在区块链上,区块链存储区类似于传统的key-value存储系统(比如:redis),当然我们也可以结合其他存储方式综合使用。

猜你喜欢

转载自blog.51cto.com/634435/2114942