当前位置:网站首页>The actual use of EOSJS in China Mobile Chain
The actual use of EOSJS in China Mobile Chain
2022-08-05 14:01:00 【InfoQ】
id:BSN_2021 公众号:BSN 研习社 作者:中移信息
中移(动)信息技术有限公司(以下统称“IT公司”)与BSN在2021年10month to cooperate,由BSN搭建BSN-DDC基础网络,IT公司区块链团队自主研发基于EOS的中移链DDC,面向存在DDC业务需求的各行业客户提供接入服务,使其可便捷管理DDC操作,从而灵活升级产品模式,助力客户业务创新.
一、中移链eosjs简述
中移链是基于EOS区块链框架改造,满足BSN开放联盟链要求,符合国内监管政策.China Mobile Chain Blockchain is a blockchain platform with industry-leading transaction speed and flexible utility,Designed for enterprise-level use cases,And built for public and private blockchain deployments.The middle shift chain is customizable,Address a wide range of business needs across industries with a role-based permission system and secure application transaction processing.The China Mobile Chain Architecture introduces a new blockchain architecture,旨在实现分布式应用的性能扩展.This is achieved by creating an OS-like architecture on which applications can be built.There are many family members of China Mobile Chain,其中eosjsOne of the most important members of his family.
eosjs是一个 Javascript 库,Its core is to provide some API,能使
中移链Nodeos RPC API
Integrate with China Mobile Chain based blockchain,这使js(包括nodejs、html中的js、in the front-end frameworkjs)Has the ability to directly operate the blockchain.
二、eosjs的使用.
(一)环境准备
确保安装了较新版本的
Node.js
.
(二)安装
通过yarn安装eosjs
yarn add eosjs
通过npm安装eosjs
npm install eosjs
(三)eosjs核心描述
eosjs核心:
eosjsPackages are mainly providedJsonRpc对象和Api对象.
JsonRpc
JsonRpc是一个无状态且轻量级的远程过程调用(RPC)传送协议.Its delivery content is as follows:1、必需参数:String form of the node to connect to;2、可选参数:
fetch对象.通过new一个JsonRpc对象,Pass two parameters in the constructor,第一个参数必填,That is, in string formURL(节点的URL地址);第二个参数非必填,即
fetch对象,一般在nodejspassed on,其他(例如:vue端)不需要.代码如下:
const rpc = new JsonRpc('http://172.0.0.1:8888', { fetch });
api
Send transactions and trigger actions on the blockchain,必须有一个
Api实例,The instance is received in its constructor SignatureProvider 对象.SignatureProvider The object must contain the private key corresponding to the actor performing the operation and the permission requirements.获取到一个api的完整代码如下:
const defaultPrivateKey = "5JWuxonweDjwWFuXRwt4sqj5YriEc8ehZh6EKszYYcf3Puh6gAa"; // bob
const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);
const rpc = new JsonRpc('http://172.0.0.1:8888', { fetch });
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
SignatureProviders 通过
dist/eosjs-api-interfaces.SignatureProvider接口实现.如下所示:
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig');
This method is a simple option provided by the developer to the signature provider,Mainly as an example,For security reasons,Recommended for development use only.
在生产代码中,A secure vault is recommended(即
eosjs-api-interfaces.SignatureProvider接口),Ensure security when signing transactions,官方推荐的库:
Ledger Signature Provider**
.
(四)基本用法
1、在nodejs中使用
eosjs
:通过commonjs 语法导入.
关键代码如下:
const { Api, JsonRpc } = require('eosjs');//引入eosjsThere are two core objects
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig'); // Signature provider,只能在开发环境中使用
const fetch = require('node-fetch'); // node only; not needed in browsers,只有nodejs中需要,Not required in the browser.node-fetchversion is required2.6.6版
const { TextEncoder, TextDecoder } = require('util'); //转码器
const defaultPrivateKey = "5JWuxonweDjwWFuXRwt4sqj5YriEc8ehZh6EKszYYcf3Puh6gAa"; //The private key for the chain of operations
const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);//Sign the private key
const rpc = new JsonRpc('http://172.0.0.1:8888', { fetch }); // http://172.0.0.1:8888is the address of the chain
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() }); //实例化api,通过apiYou can operate the chain directly
//The following self-executing function is a trading operation
(async () => {
const result = await api.transact({
actions: [{
account: 'eosio.token',
name: 'transfer',
authorization: [{
actor: 'eosio',
permission: 'active',
}],
data: {
from: 'eosio',
to: 'user2',
quantity: '0.0001 SYS',
memo: 'test',
},
}]
}, {
blocksBehind: 3,
expireSeconds: 30,
});
console.dir(result);
})();
2、在浏览器中使用
eosjs
.
首先将eosjsPulled from the official repository,仓库地址为:https://github.com/EOSIO/eosjs.git .在cmdExecute the following code in sequence in the manager:(1)从远程仓库拉取代码.
git clone https://github.com/EOSIO/eosjs.git
(2)进入到eosjs文件夹下.
cd ./eosjs
(3)加载依赖包.
npm install
(4)Run export compressedeosjs.
npm run build-web
或
yarn build-web
这将创建
dist-web文件夹和 Web 分发模块.确保
externals.min.js包含 eosjs External packages used.(5)在目标html里使用
<script>标签进行引入
dist-web文件夹里的文件.代码如下:
<pre style="width: 100%; height: 100%; margin:0px; "></pre>
<script src='dist-web/externals.min.js'></script>
<script src='dist-web/eosjs-api.min.js'></script>
<script src='dist-web/eosjs-jsonrpc.min.js'></script>
<script src='dist-web/eosjs-jssig.min.js'></script>
Come back after importingscriptAdd the following code to the tag:
<script>
let pre = document.getElementsByTagName('pre')[0];
const privateKey = '5JWuxonweDjwWFuXRwt4sqj5YriEc8ehZh6EKszYYcf3Puh6gAa';
const rpc = new eosjs_jsonrpc.JsonRpc('http://172.0.0.1:8888');
const signatureProvider = new eosjs_jssig.JsSignatureProvider([privateKey]);
const api = new eosjs_api.Api({ rpc, signatureProvider });
(async () => {
const result = await api.transact({
actions: [{
account: 'eosio.token',
name: 'transfer',
authorization: [{
actor: 'eosio',
permission: 'active',
}],
data: {
from: 'eosio',
to: 'user2',
quantity: '0.0001 SYS',
memo: 'test',
},
}]
}, {
blocksBehind: 3,
expireSeconds: 30,
});
console.dir(result);
pre.textContent += '\n\nTransaction pushed!\n\n' + JSON.stringify(result, null, 2)
})();
</script>
在浏览器中点击html,will run after success pre.textContent,The serialization of the result returned after the transaction is printed out on the page.在
dist-web文件夹和 Web After the distribution module is created,在eos的文件夹下新建一个html,Then copy the code of the above two parts into it,Open it in a browser to see the running result.
3、在vue项目中使用
eosjs
:通过
ES 模块语法
导入.
具体代码如下:
import { Api, JsonRpc } from 'eosjs';
import { JsSignatureProvider } from 'eosjs/dist/eosjs-jssig';
//The following code can be encapsulated into a methodcreatedCall it directly in the periodic function,或者直接扔createdIt also works in periodic functions.
const defaultPrivateKey = "5JWuxonweDjwWFuXRwt4sqj5YriEc8ehZh6EKszYYcf3Puh6gAa";
const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);
const rpc = new JsonRpc('http://172.0.0.1:8888');
const api = new Api({ rpc, signatureProvider });
(async () => {
const result = await api.transact({
actions: [{
account: 'eosio.token',
name: 'transfer',
authorization: [{
actor: 'eosio',
permission: 'active',
}],
data: {
from: 'eosio',
to: 'user2',
quantity: '0.0001 SYS',
memo: 'test',
},
}]
}, {
blocksBehind: 3,
expireSeconds: 30,
});
console.dir(result);
})();
4、在react项目中使用
eosjs
:通过
ES 模块语法
导入.
在react项目中使用eosjs,code with invueItems are the same,需要注意的一点是react-script的版本问题:因为是通过react的脚手架创建项目,默认使用的react-scripts是最新版本,It will be reported during the transactionbuffer错误,这就需要将 "react-scripts"的版本更改为"react-scripts": "4.0.3".
边栏推荐
- Memory mapping principle and mmap
- 背后的力量 | 开启智能化教学新体验 华云数据助力天长市工业学校打造新型IT实训室
- Kernel implementation of buddy allocator
- IEEE Fellow 徐鹰:AI 生命科学的 30 年快意人生
- 子网掩码和子网划分
- R语言ggplot2可视化:使用ggpubr包的ggsummarytable函数可视化dataframe数据的描述性统计量、ggtheme参数设置可视化图像使用的主题
- The power behind | Open up a new experience of intelligent teaching Huayun Data helps Tianchang Industrial School to build a new IT training room
- Source code analysis 2 Model conversion export.py
- -ST表模板
- pyspark实现csv文件转parquet格式(最优解决方案)
猜你喜欢
随机推荐
JS—动画
-ST表模板
Qt实现多国语言切换
[CUDA study notes] What is GPU computing
5G ToB业务介绍及时延需求
Redis5.0的安装和配置
链表面试题-刷题
思科交换机命令大全,含巡检命令,网工建议收藏!
国密是什么意思?属于商密还是普密?
Docker study notes - cluster deployment based on example projects (5) Docker builds MySQL cluster | PXC cluster
华为设备Smart Link和Monitor Link配置命令
'proxy' config is set properly, see "npm help config"
伙伴分配器的内核实现
14, the regular expression - section after class exercises and answers
[vulhub]PostGresql远程代码执行漏洞复现(CVE-2018-1058)
Some understanding of multithreading
字节跳动 Flink 状态查询实践与优化
用友U8各版本操作系统是数据库支持情况
OPENCV学习DAY9
华为分析&联运活动,助您提升游戏总体付费









