Skip to content
This repository has been archived by the owner on Aug 2, 2022. It is now read-only.

Commit

Permalink
Merge pull request #462 from EOSIO/develop
Browse files Browse the repository at this point in the history
EOSJS v20.0.0-beta3
  • Loading branch information
c0d3ster authored Dec 18, 2018
2 parents 68272dd + 251387f commit be370fb
Show file tree
Hide file tree
Showing 28 changed files with 674 additions and 891 deletions.
11 changes: 10 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,14 @@
}
}],
"stage-1"
]
],
"plugins": [
[
"transform-runtime",
{
"polyfill": false,
"regenerator": true
}
]
]
}
1 change: 1 addition & 0 deletions .npmrc.template
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN}
30 changes: 25 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,30 @@
env:
global:
PUBLISH_NPM_LATEST_FROM="master"
sudo: false
language: node_js
node_js:
- '10.0.0'
- '10.0.0'
before_install:
- npm install -g typescript
- npm i -g npm@6.4.1
- yarn global add typescript
- yarn global add webpack
before_script:
- source ./scripts/is_latest.sh
script:
- npm run lint
- npm run test

- yarn run lint
- yarn run test
deploy:
- provider: script
skip_cleanup: true
script:
- ./scripts/publish-edge.sh
on:
branch: develop
- provider: script
skip_cleanup: true
script:
- ./scripts/publish-tag.sh $PUBLISH_NPM_LATEST_FROM
on:
tags: true
condition: $TRAVIS_IS_LATEST_TAG = true # sourced from ./scripts/is_latest.sh
54 changes: 30 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,43 @@ Documentation can be found [here](https://eosio.github.io/eosjs)

## Installation

### NodeJS
### NodeJS Dependency

`npm install eosjs@beta`
`npm install eosjs@beta` or `yarn add eosjs@beta`

## Basic Usage
### Browser Distribution

Clone this repository locally then run `npm run build-web` or `yarn build-web`. The browser distribution will be located in `dist-web` and can be directly copied into your project repository. The `dist-web` folder contains minified bundles ready for production, along with source mapped versions of the library for debugging. For full browser usage examples, [see the documentation](https://eosio.github.io/eosjs/guides/1.-Browsers.html).

### Browser
## Import

### ES Modules

Importing using ES6 module syntax in the browser is supported if you have a transpiler, such as Babel.
```js
import { Api, JsonRpc, RpcError, JsSignatureProvider } from 'eosjs';
import { Api, JsonRpc, RpcError } from 'eosjs';

import JsSignatureProvider from 'eosjs/dist/eosjs-jssig'; // development only
```

### NodeJS
### CommonJS

Importing using commonJS syntax is supported by node out of the box.
Importing using commonJS syntax is supported by NodeJS out of the box.
```js
const { Api, JsonRpc, RpcError, JsSignatureProvider } = require('eosjs');
const { Api, JsonRpc, RpcError } = 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 { TextEncoder, TextDecoder } = require('util'); // node only; native TextEncoder/Decoder
const { TextEncoder, TextDecoder } = require('text-encoding'); // React Native, IE11, and Edge Browsers only
```

### SignatureProvider
## Basic Usage

### Signature Provider

SignatureProvider holds private keys and is responsible for signing transactions.
The Signature Provider holds private keys and is responsible for signing transactions.

***Using the default JsSignatureProvider in the browser is not secure and should only be used for development purposes. Use a secure vault outside of the context of the webpage to ensure security when signing transactions in production***
***Using the JsSignatureProvider in the browser is not secure and should only be used for development purposes. Use a secure vault outside of the context of the webpage to ensure security when signing transactions in production***

```js
const defaultPrivateKey = "5JtUScZK2XEp3g9gh7F8bwtPTRAkASmNrrftmx4AxDKD5K4zDnr"; // useraaaaaaaa
Expand All @@ -47,10 +57,10 @@ const signatureProvider = new JsSignatureProvider([defaultPrivateKey]);

Open a connection to JSON-RPC, include `fetch` when on NodeJS.
```js
const rpc = new JsonRpc('http://127.0.0.1:8000', { fetch });
const rpc = new JsonRpc('http://127.0.0.1:8888', { fetch });
```

### API Constructor
### API

Include textDecoder and textEncoder when using in browser.
```js
Expand All @@ -59,6 +69,8 @@ const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), te

### Sending a transaction

`transact()` is used to sign and push transactions onto the blockchain with an optional configuration object parameter. This parameter can override the default value of `broadcast: true`, and can be used to fill TAPOS fields given `blocksBehind` and `expireSeconds`. Given no configuration options, transactions are expected to be unpacked with TAPOS fields (`expiration`, `ref_block_num`, `ref_block_prefix`) and will automatically be broadcast onto the chain.

```js
(async () => {
const result = await api.transact({
Expand Down Expand Up @@ -100,16 +112,10 @@ try {
...
```
## Browsers
After running `npm run build-web` or `yarn build-web`, the browser distribution will be located in `dist`. For full browser usage examples, [see the documentation](https://eosio.github.io/eosjs/static/3.-Browsers.html).
## How it works
`transact()` is used to sign and push transactions onto the blockchain with an optional configuration object parameter. This parameter can override the default value of `broadcast: true`, and can be used to fill TAPOS fields given `blocksBehind` and `expireSeconds`. Given no configuration options, transactions are expected to be unpacked with TAPOS fields (`expiration`, `ref_block_num`, `ref_block_prefix`) and will automatically be broadcast onto the chain.
## Running Tests
### Automated Test Suite
### Automated Unit Test Suite
`npm run test` or `yarn test`
### Web Integration Test Suite
Run `npm run build-web` to build the browser distrubution then open `src/tests/web.html` in the browser of your choice. The file should run through 6 tests, relaying the results onto the webpage with a 2 second delay after each test. The final 2 tests should relay the exceptions being thrown onto the webpage for an invalid transaction and invalid rpc call.
28 changes: 25 additions & 3 deletions docs/2.-Transaction-Examples.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
## Example: Buy ram
# Transactions

To be able to send transactions and trigger actions on the blockchain, you must have an instance of `Api`.

The signature provider must contains the private keys corresponsing to the actors and permissions of the actions.

```javascript
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() });

```

## Examples

### Buy ram

```javascript
const result = await api.transact({
Expand All @@ -21,7 +43,7 @@ const result = await api.transact({
});
```

## Example: Stake
### Stake

```javascript
const result = await api.transact({
Expand Down Expand Up @@ -71,7 +93,7 @@ const result = await api.transact({
});
```

## Example: Create New Account (multiple actions)
### Create New Account (multiple actions)

```javascript
const result = await api.transact({
Expand Down
13 changes: 8 additions & 5 deletions docs/3.-Browsers.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ Reuse the `api` object for all transactions; it caches ABIs to reduce network us
```html
<pre style="width: 100%; height: 100%; margin:0px; "></pre>

<script src='dist-web/eosjs-api-debug.js'></script>
<script src='dist-web/eosjs-jsonrpc-debug.js'></script>
<script src='dist-web/eosjs-rpcerror-debug.js'></script>
<script src='dist-web/eosjs-jssig-debug.js'></script>
<script src='dist-web/eosjs-api.js'></script>
<script src='dist-web/eosjs-jsonrpc.js'></script>
<script src='dist-web/eosjs-jssig.js'></script>
<script>
let pre = document.getElementsByTagName('pre')[0];
const defaultPrivateKey = "5JtUScZK2XEp3g9gh7F8bwtPTRAkASmNrrftmx4AxDKD5K4zDnr"; // useraaaaaaaa
Expand Down Expand Up @@ -43,12 +42,16 @@ Reuse the `api` object for all transactions; it caches ABIs to reduce network us
pre.textContent += '\n\nTransaction pushed!\n\n' + JSON.stringify(result, null, 2);
} catch (e) {
pre.textContent = '\nCaught exception: ' + e;
if (e instanceof eosjs_rpcerror.default)
if (e instanceof eosjs_jsonrpc.RpcError)
pre.textContent += '\n\n' + JSON.stringify(e.json, null, 2);
}
})();
</script>
```

## Debugging

If you would like readable source files for debugging, change the file reference to the `-debug.js` files inside `dist-web/debug` directory. These files should only be used for development as they are over 10 times as large as the minified versions, and importing the debug versions will increase loading times for the end user.

## IE11 and Edge Support
If you need to support IE11 or Edge you will also need to install a text-encoding polyfill as eosjs Signing is dependent on the TextEncoder which IE11 and Edge do not provide. Pass the TextEncoder and TextDecoder to the API constructor as demonstrated in the [ES 2015 example](#node-es-2015). Refer to the documentation here https://github.com/inexorabletash/text-encoding to determine the best way to include it in your project.
158 changes: 158 additions & 0 deletions docs/4.-Reading blockchain-Examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Reading blockchain

Reading blockchain state only requires an instance of `JsonRpc` connected to a node.

```javascript
const { JsonRpc } = require('eosjs');
const fetch = require('node-fetch'); // node only; not needed in browsers
const rpc = new JsonRpc('http://127.0.0.1:8888', { fetch });
```

## Examples

### Get table rows

Get the first 10 token balances of account _testacc_.

```javascript
const resp = await rpc.get_table_rows({
json: true, // Get the response as json
code: 'eosio.token', // Contract that we target
scope: 'testacc' // Account that owns the data
table: 'accounts' // Table name
limit: 10, // maximum number of rows that we want to get
});

console.log(resp.rows);
```
Output:

```json
{
"rows": [{
"balance": "100.0000 HAK"
}
],
"more": false
}
```

### Get one row by index

```javascript
const resp = await rpc.get_table_rows({
json: true, // Get the response as json
code: 'contract', // Contract that we target
scope: 'contract' // Account that owns the data
table: 'profiles' // Table name
lower_bound: 'testacc' // Table primary key value
limit: 1, // Here we limit to 1 to get only the
});
console.log(resp.rows);
```
Output:

```json
{
"rows": [{
"user": "testacc",
"age": 21,
"surname": "Martin"
}
],
"more": false
}
```

### Get one row by secondary index

```javascript
const resp = await rpc.get_table_rows({
json: true, // Get the response as json
code: 'contract', // Contract that we target
scope: 'contract' // Account that owns the data
table: 'profiles' // Table name
table_key: 'age' // Table secondaray key name
lower_bound: 21 // Table secondary key value
limit: 1, // Here we limit to 1 to get only the
});
console.log(resp.rows);
```
Output:

```json
{
"rows": [{
"user": "testacc",
"age": 21,
"surname": "Martin"
}
],
"more": false
}
```

### Get currency balance

```javascript
console.log(await rpc.get_currency_balance('eosio.token', 'testacc', 'HAK'));
```
Output:

```json
[ "1000000000.0000 HAK" ]
```

### Get account info

```javascript
console.log(await rpc.get_account('testacc'));
```
Output:

```json
{ "account_name": "testacc",
"head_block_num": 1079,
"head_block_time": "2018-11-10T00:45:53.500",
"privileged": false,
"last_code_update": "1970-01-01T00:00:00.000",
"created": "2018-11-10T00:37:05.000",
"ram_quota": -1,
"net_weight": -1,
"cpu_weight": -1,
"net_limit": { "used": -1, "available": -1, "max": -1 },
"cpu_limit": { "used": -1, "available": -1, "max": -1 },
"ram_usage": 2724,
"permissions":
[ { "perm_name": "active", "parent": "owner", "required_auth": [] },
{ "perm_name": "owner", "parent": "", "required_auth": [] } ],
"total_resources": null,
"self_delegated_bandwidth": null,
"refund_request": null,
"voter_info": null }
```

### Get block

```javascript
console.log(await rpc.get_block(1));
```
Output:

```json
{ "timestamp": "2018-06-01T12:00:00.000",
"producer": "",
"confirmed": 1,
"previous": "0000000000000000000000000000000000000000000000000000000000000000",
"transaction_mroot": "0000000000000000000000000000000000000000000000000000000000000000",
"action_mroot": "cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f",
"schedule_version": 0,
"new_producers": null,
"header_extensions": [],
"producer_signature": "SIG_K1_111111111111111111111111111111111111111111111111111111111111111116uk5ne",
"transactions": [],
"block_extensions": [],
"id": "00000001bcf2f448225d099685f14da76803028926af04d2607eafcf609c265c",
"block_num": 1,
"ref_block_prefix": 2517196066 }
```
Loading

0 comments on commit be370fb

Please sign in to comment.