Ants block chain BaaS platform application development guide (V): JS SDK access

JavaScript SDK is based on access

In the previous section, we access through JavaSDK our target strand and call contract successfully. In this section, we will achieve the same call by JS SDK. JS SDK can be integrated into Web applications run in the browser; can also be integrated Node.js applications running on the server or client. In this paper, we use an example to illustrate how to access Node.js ant block chain by JS SDK.

Ready to work

Development environment configuration

  • Download and install Node.js (recommended v10.11.0 and above).
  • JS SDK installation directory to the project:
    1. Download JS SDK, and copied to the project directory:
      Ants block chain BaaS platform application development guide (V): JS SDK access
    2. Executed in the directory path
      npm i alipay-mychain-0.2.27.tgz --save

      Certificate and key

      And content required when JavaSDK similar access, we need the following documents:

  • ××× book user mechanism client.crtand the corresponding key files client.key: chain through the certificate to authenticate a user. When applying for contracts acquired certificate chain certificate file, a specific reference here or here .
  • Certified CA certificate file the contract chain ca.crt: verify the identity of users through the chain contract document. By 区块链卡片-> 右上角···> - 下载根证书get.
    Ants block chain BaaS platform application development guide (V): JS SDK access
  • Accounts private key file user.pem: Signature needs to be done by the private account when submitting the transaction to acquire when you create an account (a user.keygeneration).

The preceding two documents can be directly obtained, for the third user.pemdocument, we need to manually put the following command user.keyfiles into user.pemthe file (the code reading key file conveniently JS):

openssl ec -in user.key -passin pass:${key_password} -passout pass:${key_password} -aes256 -out user.pem

这里要注意保护密码的配置,-passout参数配置的密码需要在后续的sdk中使用到。
需要提前安装配置好openssl工具。

最终,我们项目目录下,新建一个文件夹在放所有的需要的证书文件::

~/Documents/Work/JSSDKDemos/Certs/PRD> tree
.
├── ca.crt
├── client.crt
├── client.key
├── user.key
└── user.pem

获取合约链的接入IP与端口号

与JavaSDK相同,通过区块链卡片 > 详情 > 节点处获取:
Ants block chain BaaS platform application development guide (V): JS SDK access

开始第一个JS程序

获取合约接口说明ABI

JS SDK对合约的调用依赖编译合约时生成的应用程序二进制接口说明(Application Binary Interface,ABI)。ABI文件中描述了合约暴露的方法名,输入参数类型和返回参数类型等。JS SDK会根据ABI来提供实例化的调用方法以及自动反序列号返回值。我们可以在Cloud IDE中编译合约来获取ABI:
Ants block chain BaaS platform application development guide (V): JS SDK access

也可以通过solc-js工具在本地编译合约并获取ABI文件,参见这里
例如,在蚂蚁区块链BaaS平台应用开发指南(三)中我们部署的合约,其合约内容与合约接口说明ABI如下:
合约内容:

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

ABI说明:

[
   {
      "constant":false,
      "inputs":[
         {
            "name":"x",
            "type":"uint256"
         }
      ],
      "name":"set",
      "outputs":[

      ],
      "payable":false,
      "stateMutability":"nonpayable",
      "type":"function"
   },
   {
      "constant":true,
      "inputs":[

      ],
      "name":"get",
      "outputs":[
         {
            "name":"",
            "type":"uint256"
         }
      ],
      "payable":false,
      "stateMutability":"view",
      "type":"function"
   }
]

使用JS SDK调用合约

  1. 新建一个main.js文件。
  2. 文件中填入以下内容:
const Chain = require("@alipay/mychain/index.node") // 在node环境使用 TLS 协议
const fs = require("fs")

const accountKey = fs.readFileSync("./Certs/PRD/user.pem", { encoding: "utf8" })
const accountPassword = '******'        // 需要替换为自定义的user.pem密码
const keyInfo = Chain.utils.getKeyInfo(accountKey, accountPassword)

const passphrase = '******'                 // 需要替换为自定义的client.key密码
//配置选项
let opt = {
  host: '47.101.66.49',                         // 目标区块链网络节点的 IP
  port: 18130,                                  // 端口号
  timeout: 30000,                               // 连接超时时间配置
  cert: fs.readFileSync("./Certs/PRD/client.crt", { encoding: "utf8" }),
  ca: fs.readFileSync("./Certs/PRD/ca.crt", { encoding: "utf8" }),
  key: fs.readFileSync("./Certs/PRD/client.key", { encoding: "utf8" }),
  userPublicKey: keyInfo.publicKey,
  userPrivateKey: keyInfo.privateKey,
  userRecoverPublicKey: keyInfo.publicKey, // 账户恢复公钥,本例中用不到,随便填入一个
  userRecoverPrivateKey: keyInfo.privateKey,// 恢复恢复私钥,本例中用不到,随便填入一个
  passphrase: passphrase // clinet.key的密码
}

// 初始化一个连接实例
const chain = Chain(opt)

// 提供合约abi
const abi = JSON.parse('[{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]')

// 实例化一个合约instance
let myContract = chain.ctr.contract("donglei-contract-test-002", abi); 

//调用合约的set方法,把storedData变量设为20。
myContract.set(20,
    {from:'donglei-PRD-001'},      // From参数,合约调用交易的发起者,用户id和提供的user.pem需要匹配。
    (err, output, data) => {
        console.log(data);              // 交易回执会存储在data字段中。
});

//调用合约的get方法,获取storedData的值。
myContract.get(
    {from:'donglei-PRD-001'},     // From参数,合约调用交易的发起者,用户id和提供的user.pem需要匹配。
    (err, output, data) => {
        console.log(output.toString());  // 合约方法的返回值会存储在output字段中。
});

程序运行结果如下:
Ants block chain BaaS platform application development guide (V): JS SDK access

小结

在本节中,我们通过JS SDK接入蚂蚁区块链并实现了合约的调用,与JavaSDK最大的不同在于JS SDK通过ABI说明来实例化合约的调用接口和返回值解析,不需要手动构造方法签名及反序列化返回值。可以看到,一个完整的调用流程如下:

  1. 初始化一个chain实例(配置好用户×××书、账户私钥和连接参数);
  2. 初始化一个合约实例(需要提供合约的ABI说明);
  3. 调用一个合约方法(需要提供调用者的用户id,通过data字段获取交易回执);
  4. Return value acquired contract (contract value is stored in the return in output, JS SDK will automatically return value deserialized);

Web access environmental considerations
need to be aware in the Node.js environment, interactive programs and data link using a TLS protocol. If you want to JS SDK to integrate into a Web application, the browser uses the HTTPS protocol for data exchange with the chain, the chain needs at this time administrator configure different access interfaces. Specific developers can work order system and development support team through.
In addition, the Web environment Node.js environment and SDK are different ways to introduce
Web: const Chain = require("@alipay/mychain/index.node")
Node.js:const Chain = require("@alipay/mychain")

Guess you like

Origin blog.51cto.com/14321927/2424488