【eosjs】
Javascript API,用于帮助访问与 EOSIO RPC API.
1、安装
npm install eosjs@beta
2、Signature Provider
The Signature Provider holds private keys and is responsible for signing transactions.
const defaultPrivateKey = "5JtUScZK2XEp3g9gh7F8bwtPTRAkASmNrrftmx4AxDKD5K4zDnr"; // useraaaaaaaa const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);
SignatureProvider是一个接口,不能直接使用。
JsSignatureProvider 实现了 SignatureProvider接口。是唯一实现了 SignatureProvider 接口的类。应当使用这个类。
JsSignatureProvider只两个方法:
3、JSON-RPC
Open a connection to JSON-RPC, include fetch
when on NodeJS.
const rpc = new JsonRpc('http://127.0.0.1:8888', { fetch });
JSON-RPC 实现了 AuthorityProvider、AbiProvider 两个Interface。
RPC 提供以下的方法:
4、API
实现了签名相关功能的类。
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
transact()
is used to sign and push transactions onto the blockchain with an optional configuration object parameter.
通常使用 transaction 方法,发起一个交易:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
(async () => { const result = await api.transact({ actions: [{ account: 'eosio.token', name: 'transfer', authorization: [{ actor: 'useraaaaaaaa', permission: 'active', }], data: { from: 'useraaaaaaaa', to: 'useraaaaaaab', quantity: '0.0001 SYS', memo: '', }, }] }, { blocksBehind: 3, expireSeconds: 30, }); console.dir(result); })();
transact是一个 async主法:
API 对象提供以下主法:
5、通常的使用流程。
使用 JsonRpc 对象、JsSignatureProvider 对象来创建一个 Api对象。
const { Api, JsonRpc } = require('eosjs'); const JsSignatureProvider = require('eosjs/dist/eosjs-jssig'); // development only const fetch = require('node-fetch'); // node only; not needed in browsers const { TextDecoder, TextEncoder } = require('text-encoding'); // node, IE11 and IE Edge Browsers const privateKeys = [privateKey1]; const signatureProvider = new JsSignatureProvider(privateKeys); const rpc = new JsonRpc('http://127.0.0.1:8888', { fetch }); const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
后续就使用 api.transact 来发起交易:
const result = await api.transact({ actions: [{ account: 'eosio', name: 'buyrambytes', authorization: [{ actor: 'useraaaaaaaa', permission: 'active', }], data: { payer: 'useraaaaaaaa', receiver: 'useraaaaaaaa', bytes: 8192, }, }] }, { blocksBehind: 3, expireSeconds: 30, });
参考:
1、https://eosio.github.io/eosjs/
2、https://github.com/EOSIO/eosjs/tree/08b474e8c25ccccf2701ca04268fa5149728baa1