VNTChain入门指南3——DAPP开发

Go on after last blog


Introduction

Environment

  • Docker and bottle v0.6.1

  • go v1.10(maybe not required)

  • Node.js v8.11.2

  • Vnt.js && Vnt-kit.js

  • gvnt

    You can install them through 'vnt-full-install-guide.md' file.

Say before

This document mainly help developers use VNTChain to start local testnet, develop a DAPP with VNTChain (including create build deploy smart contract and interact with smart contract or VNTChain net).

Why not use official guide directly?

There is long time since it updated last time.Some steps and some way don't work.

I am GenjiLemon.GiitHub:https://github.com/GenjiLemon. Email:lemonfay{AT}qq.com.You have to keep origin URL of this blog if reprint.


Develop DAPP

We use node.js to interact with VNTChain.For node.js(vnt.js && vnt-kit.js) is the only SDK for VNTChain, here we

Write smart contract

refer to VNT区块链浏览器.We use C language to write smart contract.

  1. enter the contract folder.

    mkdir contract && cd contract

  2. download vntlib.h

    wget https://github.com/vntchain/vnt-documentation/blob/master/smart-contract/vntlib.h

  3. Create sample.c as a samle smart contract source code.

    touch sample.c && vi sample.c

    Paste the following

#include "vntlib.h"

KEY string NAME = "GenjiLemon";

constructor Sample(){

}

MUTABLE
void setName(string newName){

NAME = newName;

}

UNMUTABLE
string getName(){

return NAME;

}

Now we define one permanent variable NAME ,and its getter and setter.

TIPS:

  1. If you want to edit the permanent variable in a function, you have to set it MUTABLE

  2. We use KEY to define a permanent variable.

  3. You can define more types of variable folloing the official documentation

Compile smart contract

Now you are in smart contract

  1. Run command

Use docker command to complie the sample.c

docker run --rm -v <your contract directory>:/tmp vntchain/bottle:0.6.0 compile -code /tmp/<your contract file name> 

My command is:

docker run --rm -v /home/lemon/project/vntchain/testnet/demo/contract:/tmp vntchain/bottle:0.6.1 compile -code /tmp/sample.c     

You will get the output:

Compile contract: Sample
=========================
Input file
===========
   > Contract path:           /tmp/sample.c
Output file
============
   > Abi path:                /tmp/output/Sample.abi
   > Precompile code path:    /tmp/output/Sample_precompile.c
   > Wasm path:               /tmp/output/Sample.wasm
   > Compress data path:      /tmp/output/Sample.compress
   > Compress hex Data path:  /tmp/output/Sample.hex
   > Deploy js path:          /tmp/output/Sample.js
   > Contract json path:      /tmp/output/Sample.json
   > Please use Sample.compress when you want to create a contract
Compile finished. 312.139951ms
  1. Assign permission

    sudo chmod 755 output

  2. Check file

    tree .
    .
    ├── output
    │   ├── Sample.abi
    │   ├── Sample.compress
    │   ├── Sample.hex
    │   ├── Sample.js
    │   ├── Sample.json
    │   ├── Sample_precompile.c
    │   └── Sample.wasm
    ├── sample.c
    └── vntlib.h
    
    1 directory, 9 files

Among them, Sample.compress is for deployment and Sample.abi is for call.

Deploy smart contract

We use vnt.js to deploy smart contract.It may be the one way.

First ,you have to boot the testnet

1. Prepare for environment

You have to create a node.js project first.

npm init

Enter some info about project.Then install basic packages.

npm install --save https://github.com/vntchain/vnt.js.git
npm install --save https://github.com/vntchain/vnt-kit.js.git

npm install --save ethereumjs-tx@1.3.7
npm install --save ethereumjs-account

If you fail, please follow [vnt-full-install-guide.md]

2. Deploy

You can press node to enter node environment or just run node xxx.js.But the latter is recommended, and I will show this.

  1. Create file and edit

touch deploy_script.js && vi deploy_script.js

You can edit the flollowing code sample.js

var fs = require('fs');
var Vnt = require("vnt")
var vntkit = require("vnt-kit")
var Tx = require("ethereumjs-tx")
// 设置连接的节点
var vnt = new Vnt();
vnt.setProvider(new vnt.providers.HttpProvider("http://127.0.0.1:8545"));
// 解锁用户
var account_address = '0xfbb316db66f6945addf00bc059a3f3dc5c4d8731';
var account_password = 'password0';
vnt.personal.unlockAccount(account_address,account_password);

// 准备代码和abi
var baseDir = "/home/lemon/project/vntchain/testnet/demo/contract/output/"
var codeFile = baseDir+"Sample.compress"
var abiFile = baseDir+"Sample.abi"
var wasmabi = fs.readFileSync(abiFile)
//将abi数据解析成json结构
var abi = JSON.parse(wasmabi.toString("utf-8"))

// 获取交易回执
function getTransactionReceipt(tx, cb) {
 var receipt = vnt.core.getTransactionReceipt(tx);
 if (!receipt) {
   setTimeout(function() {
     getTransactionReceipt(tx, cb)
   }, 1000);
 } else {
   cb(receipt)
 }
}

//这是合约创建主函数
function deployWasmContract() {
 // 通过abi与代码路径初始化合约
 var contract = vnt.core.contract(abi).codeFile(codeFile)

 var contractReturned = contract.new(100000, "bitcoin", "BTC", {
   from: account_address,  //from参数对应的账户会被用作交易签名
   data: contract.code, //将合约的代码当作data传入
   gas: 4000000
 }, function(err, myContract){
  if(!err) {
     console.log("transactionHash: ", myContract.transactionHash);
     getTransactionReceipt(myContract.transactionHash, function(receipt){
           console.log("tx status: ", receipt.status)
           console.log("contract address: ", receipt.contractAddress)
       });
  }
  else{
    console.log(err);
  }
});
}

// 调用部署函数
deployWasmContract();

At least, you have to edit account info and baseDir

  1. Run script

    node deploy_script.js

    Then you will get the transaction hash and contract address.

    OUTPUT:

    node deploy_script.js      
    
    (node:8685) Warning: N-API is an experimental feature and could change at any time.
    transactionHash:  0x20ac2d49eb00cddc6e8d27509d4d73caf7427dd23e72f3b2f2739013bbd8317a
    transactionHash:  0x20ac2d49eb00cddc6e8d27509d4d73caf7427dd23e72f3b2f2739013bbd8317a
    tx status:  0x1
    contract address:  0x5f6f7855be446253658e1e163559388d4a1482b2
    tx status:  0x1
    contract address:  0x5f6f7855be446253658e1e163559388d4a1482b2

    Please record the contract address.

Interact with smart contract

Make sure that you have done compile , deploy step and the testnet is running.Now you create a new folder for sample of interaction which is sub folder of node.js project we create before.

  1. Create folder

mkdir interact && cd interact

  1. Create sample file

    touch call_sample.js && vi call_sample.js

  2. Write code

    enter the following

    var fs = require('fs');
    var Vnt = require("vnt")
    var vntkit = require("vnt-kit")
    var TX= require("ethereumjs-tx")
    
    // 设置连接的节点
    var vnt = new Vnt();
    vnt.setProvider(new vnt.providers.HttpProvider("http://127.0.0.1:8545"))
    
    // 合约部署地址
    var contractAddress = '0x5f6f7855be446253658e1e163559388d4a1482b2'
    var chainid = 2;
    
    // 解锁用户
    var account_address = '0xfbb316db66f6945addf00bc059a3f3dc5c4d8731';
    var account_password = 'password0';
    vnt.personal.unlockAccount(account_address,account_password);
    
    // 准备代码和abi
    var baseDir = "/home/lemon/project/vntchain/testnet/demo/contract/output/"
    var abiFile = baseDir+"Sample.abi"
    var wasmabi = fs.readFileSync(abiFile)
    //将abi数据解析成json结构
    var abi = JSON.parse(wasmabi.toString("utf-8"))
    
    function call_getName(){
        var contract = vnt.core.contract(abi).at(contractAddress);
        var res = contract.getName.call({from:account_address});
        console.log('call_getName output : '+res);
        return res;
    }
    
    function call_setName(name){
       var contract = vnt.core.contract(abi).at(contractAddress);
       contract.setName.sendTransaction(name,{from:account_address},function(err, result){
           if(err){
               console.log("sendTransaction error :"+ err);
           }
           console.log("call_setName output : "+result);
       });
    }
    
    module.exports={
       getName:call_getName,
       setName:call_setName
    }

  At least, you have to change contractAddress account info baseDir.

  4. Run code in node environment.

         node

        Then you will enter interact environment with node.js

        Just Try:

> var cs = require('./call_sample.js')
> cs.getName()
call_getName output : GenjiLemon
'GenjiLemon'
> cs.setName('lll')
undefined
> call_setName output : 0x8324a6ee94bad2207bea19cf9d43aa7bd033e46f48eff648c48ba6c5f5218ae5
cs.getName()
call_getName output : lll
'lll'
  1. In the first line, we include call_sample.js file

  2. Then we call getName() ,it will return default value GenjiLemon we set in smart contract before.

  3. Then we call setName('lll'), it will change the value of NAME in smart contract.Then it will return transaction hash as result.

  4. Then we call getName() ,we get 'lll' .It is right.

More

Now sections in [Develope DAPP] are just sample of key steps in developement stage.

You have to consider:

  • Complex data stucture in smart contract to apply more scenes

  • More action in interaction with blockchain and smart contract

  • Backend technology choise (most language is node.js ,for limit of vnt sdk )

  • Use local net or VNT Hubble net(the latter doesnt show in this blog)

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注