Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

dfuse JavaScript/TypeScript Client Library

A GraphQL, WebSocket and HTTP REST client library to consume dfuse API https://dfuse.io (dfuse docs).

Installation

Using Yarn:

yarn add @dfuse/client
# Use this command if you are using npm
#npm install --save @dfuse/client

Features

What you get by using this library:

  • Full dfuse API coverage (GraphQL, REST & WebSocket)
  • API Token issuance & management (auto-refresh, expiration handling, storage, etc)
  • Automatic re-connection on socket close
  • Stream progress management and auto-restart at last marked location on socket re-connection
  • Full customization power

Quick Start

Notice You should replace the sequence of characters Paste your API key here in the script above with your actual API key obtained from https://app.dfuse.io. You are connecting to a local dfuse for EOSIO instance or to a dfuse Community Edition? Replace apiKey: "<Paste your API key here>" with authentication: false so authentication is disabled.

EOSIO

See examples/basic/eosio/stream-transfers-graphql.ts

const{ createDfuseClient }=require("@dfuse/client")constclient=createDfuseClient({apiKey: "<Paste your API key here>",network: "mainnet.eos.dfuse.io",})conststreamTransfer=`subscription($cursor: String!) { searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) { undo cursor trace { matchingActions { json } } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){constdata=message.data.searchTransactionsForwardconstactions=data.trace.matchingActionsactions.forEach(({ json }: any)=>{const{ from, to, quantity, memo }=jsonconsole.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)})stream.mark({cursor: data.cursor})}if(message.type==="complete"){console.log("Stream completed")}})

Ethereum

See examples/basic/ethereum/stream-transfers.ts

const{ createDfuseClient }=require("@dfuse/client")conststreamTransfer=`subscription($cursor: String) { searchTransactions(query: "method:'transfer(address,uint256)'", cursor: $cursor) { undo cursor node { hash from to value(encoding: ETHER) } }}`awaitclient.graphql(streamTransfer,(message,stream)=>{if(message.type==="error"){console.log("An error occurred",message.errors,message.terminal)}if(message.type==="data"){const{ cursor, node }=message.data.searchTransactionsconsole.log(`Transfer [${node.from} -> ${node.to}, ${node.value}]`)stream.mark({ cursor })}if(message.type==="complete"){console.log("Stream completed")}})

Node.js

If you target a Node.js environment instead, you will need bring a fetch compatible function and a proper WebSocket client.

You are free to use any compatible library respecting the respective requirements. To make it simple, if fetch and/or WebSocket are available in the global scope (global), they are picked automatically by the library. While polluting the global scope, it's the easiest way to get started.

It's what the examples in this project do using respectively node-fetch and and ws for fetch and WebSocket respectively.

Installation instructions using Yarn would be:

yarn add node-fetch ws

In the bootstrap phase of your application, prior doing any @dfuse/client imports/require, put the following code:

global.fetch = require("node-fetch");
global.WebSocket = require("ws");

You can check the Node.js Configuration example for how to avoid polluting the global scope.

Sane Defaults

The library make sane default assumptions about some of the dependencies the library requires. This section details the choices we think are the most important ones.

Fetch

The library requires a Fetch like interface. In the Browser environment, this is the fetch function that is used (we check that window.fetch is a function).

If window.fetch is undefined, we fallback to check global.fetch variable. This can be set in a Node.js environment to point to a compatible implementation of fetch, like the one provided by the node-fetch package.

If none is provided, the library throw an error. To avoid this error, you should pass the httpClientOptions.fetch option when creating the dfuse Client.

It possible to provide you own implementation using under the cover any HTTP library like axios or even XMLHttpRequest if you wish so.

WebSocket

The library requires a WebSocket client interface having the same semantics as the WebSocket API in the Browser environment.

In the Browser environment, this is the standard WebSocket variable that is used (we check that window.WebSocket is present).

If window.WebSocket is undefined, we fallback to check global.WebSocket variable. This can be set in a Node.js environment to point to a compatible implementation of WebSocket client, like the one provided by the ws package.

If none is provided, the library throw an error. To avoid this error, you should pass the streamClientOptions.socketOptions.webSocketFactory and the graphqlStreamClientOptions.socketOptions.webSocketFactory options when creating the dfuse Client. This factory method receives the full url to connect to the remote endpoint (this will include the API token to use in query parameters of the url) and should return a valid WebSocket client object.

We highly suggest to use ws package straight in a Node.js environment.

API Token Store

The API token store interface is used by the dfuse Client to perform the persistent retrieval and writing of the API token. Indeed, we rate limit the API token issuance endpoint and as such, it's highly important to re-use a valid token instead of generating a new one each time it's required to avoid hitting the API token issue rate limiter.

The library, when no apiTokenStore options is passed to the client will pick a default ApiTokenStore implementation based on your environment.

In a Browser environment, the concrete implementation that is used is the LocalStorageApiTokenStore class. This will save and retrieve the token from the browser localStorage (under a dfuse:token key).

In a Node.js environment, the concrete implementation that is used is the OnDiskApiTokenStore class. This will save and retrieve the token from a local file on the disk at ~/.dfuse/<sha256-api-key>/token.info.

Note Depending on your deployment target (Docker, VM, etc.), it's possible that the home directory (~) is not writable, causing the default OnDiskApiTokenStore instance on Node.js environment to not work correctly. In those cases, simply define yourself the apiTokenStore instance to use and pick the location where the token should be saved. Instantiate a FileApiTokenStore instance and use it as the apiTokenStore configuration value when instantiating the dfuse Client:

import { createDfuseClient, FileApiTokenStore } from "@dfuse/client";
const client = createDfuseClient({
...,
apiTokenStore: new FileApiTokenStore("/tmp/dfuse-token.json"),
...,
});

API

The full API reference can be found at https://dfuse-io.github.io/client-js/.

This site is generated by running typedoc on this repository. The full API reference being rather exhaustive, here a quick index pointing to the most important entities' documentation section that should be read to understand the various part of the library:

Factories
Interfaces
Options
Implementations

NoteDefaultStreamClient, DefaultHttpClient, DefaultSocket, DefaultApiTokenManager are all private implementations not exposed.

Examples

Note You can run the examples straight from this repository quite easily. Clone it to you computer, run yarn install && yarn build in the project directory. Link the local build so it's usable by the examples:

yarn link # Adds a symlink of this project to your global installation
yarn link @dfuse/client # Adds `@dfuse/client` in this project's `node_modules` folder (global symlink)

Ensures you have an environment variable DFUSE_API_KEY set to your dfuse API Key value. Then simply issue the following command (pick the example file you want to run):

yarn run:example examples/basic/eosio/stream-transfers-graphql.ts

Browser Example

For the browser example to work, you need to edit the browser.html file:

  • Edit the browser.html file to put your own API key, search for apiKey: "<Paste API key here!>", in the file.

Once this is done, simply double-click on the browser.html file (open examples/reference/browser.html on Unix/Mac system).

Basic

These are the starter examples showing a concrete use case you can solve using @dfuse/client library. Those toy examples have low to no error handling, check the Advanced section for production grade details on efficiently use @dfuse/client

EOSIO
Ethereum

Advanced

You will find examples leveraging the full power library with all the correct patterns to consume the Blockchain data efficiently, with strict data integrity and how to properly deal with error and edge cases (like micro-forks!).

Common

Those are examples that are general concepts applicable to all chains we support or about some specifities of the client-js library like configuring the WebSocket connection or the behavior of the client instance itself.

EOSIO

Reference

In this folder, you will get full reference examples. Those are used to showcase the actual full data you receive with each call. It's also there where you can check the flow of messages that can be handled in each dfuse Stream and full configuration options for the library itself and all the API calls.

Common
EOSIO (REST API)
EOSIO (WebSocket API)
Ethereum (GraphQL API)

Development

The best way to develop this library is through modifying and adding examples to the project.

To run the examples, it's quite simple, follow these instructions:

  1. Install project dependencies so that you get development tools at the same time:

    yarn install
    
  2. Link the project inside itself, that will be necessary to correct run the examples which import @dfuse/client:

    yarn link
    yarn link @dfuse/client
    
  3. Start the build watcher so distribution files are always up-to-date. Forgetting to do that will prevent examples from picking latest changes you've made to source files!

    yarn start
    
  4. Last step is to add .env file containing the dfuse API key required to run the examples. Create a file .env at the root of the project with the following content:

    DFUSE_API_KEY=Replace this with API key!
    
  5. Final check, let's run an example to ensure everything is working:

    yarn run:example examples/basic/eosio/state-check-balance.ts
    

Publishing

First step is to update the change log (CHANGELOG.md) by updating the ## In Progress header to change to ## <Version> (<Month> <Day>, <Year>) (i.e. ## 0.11.11 (March 26, 2019)) and the commit that.

Assuming you have been granted access rights to publish this package, the command to perform is simply:

yarn run publish:latest

This command will automatically perform a clean build followed by the execution of the full test suite then a publish the package followed by a publish of the docs and finally push the commits and tag to the remote repository.

Pre-release

If you want to publish a pre-release version not flagged as the latest so that people still pulls the current stable version unless they opt-in explicitly, use the following invocation:

yarn run publish:next

Does the same work as publish:latest but the docs is not published by this step.

Credits / Acknowledgement

A big thanks (and hug) to our dear friend Denis Carriere from EOS Nation for creating the initial version of this project.

License

MIT

About

dfuse JavaScript/TypeScript Client Library for dfuse API

Resources

Stars

52 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages