Pocket JS

The Pocket-JS is the core client used for sending relays to any network that is currently supported on the Pocket Network.

Prerequisites:

Installing Pocket-JS

To install the Pocket-JS library in your project, run the following NPM command or add pocket-js in your package.json:

npm install --save @pokt-network/pocket-js

Import Pocket Library

To create a relay we have to import our @pokt-network/pocket-js module and declare some variables.

// Import PocketJS and declare the following variables
const PocketJS = require('@pokt-network/pocket-js');
const Pocket = PocketJS.Pocket;
const Configuration = PocketJS.Configuration;
const Provider = PocketJS.HttpRpcProvider;
const PocketAAT = PocketJS.PocketAAT;

Create Pocket Instance With Base Configurations:

Below are the required instances that need to be set up in order to send a relay. To connect your application to mainnet, please see the list of mainnet dispatchers and change the dispatchers variable at line 5.

/*
Create an array of dispatchers that will be connecting you to a Pocket Node. A list of Dispatchers can be found here: https://docs.pokt.network/v2.1/docs/known-dispatcher-list
*/

const dispatchers = [new URL("https://node3.testnet.pokt.network:443"), new URL("https://node2.testnet.pokt.network:443")];

/* 
The chain of the blockchain you wish to connect to. See Supported Networks(https://docs.pokt.network/v2.1/docs/supported-networks) 
*/
const blockchain = "0022";


/*
(optional)Configuration stores multiple properties used to interact with the Pocket Network. 
   - maxDispatchers - (optional) Maximun amount of dispatchers urls to stored in rounting table, default 0.
   - maxSessions - (optional) Maximun amount of sessions to stored for the session manager, default 0.
   - maxConsensusNodes - (optional) Maximun amount of nodes for local consensus, mandatory ODD number, default 0.
   - requestTimeOut - (optional) Maximun timeout for every request in miliseconds, default 0.
   - acceptDisputedResponses - (optional) Accept or reject responses based on having a full consensus, default false.
   - sessionBlockFrequency - (optional) Amount of blocks that need to elapse for a new session to be tumbled, look at https://github.com/pokt-network/pocket-network-genesis for more information
   - blockTime - (optional) Amount of time (in milliseconds) for a new block to be produced in the Pocket Network
   - maxSessionRefreshRetries - (optional) Amount of times to perform a session refresh in case of getting error code 1124 (Invalid Session)
   - validateRelayResponses - (optional) If True the relay responses are validated againt's the relay request information, False will not validate
   - rejectSelfSignedCertificates - (optional) If True the HTTP RPC provider will force certificates to come from CAs, False will allow self signed
*/
const configuration = new Configuration(5, 1000, 5, 4000,true,undefined, undefined, undefined, undefined, false)

// create RPC provider 
const rpcProvider = new Provider(dispatchers)

/*
 create a pocket instance and stores muliple configuration options for your node
    - dispatchers: Array holding the initial dispatcher url(s).
  - rpcProvider:(optional) Provider which will be used to reach out to the Pocket Core RPC interface.
  - configuration:(optional) configuration object
  - store: (optional)Save data using a Key/Value relationship. This object save information in memory.
*/

const pocket = new Pocket(dispatchers, rpcProvider, configuration)

Adding Your Account to Send Relays

There are two ways you can start using the Pocket-JS library to connect your application to the network and that is by inserting your Application Authentication Token(AAT) or private key(s).

Using the AAT To Connect:

📘

What is a AAT?

An Application Authentication Token is a token signed by an account that has staked for bandwidth as an App on the Pocket blockchain. You can create an Application Authentication Token (AAT) for multiple clients using the Pocket Core CLI or the retrieve your App's AAT from the Pocket Dashboard App Detail page.

An example of a properly-formed AAT:

{
   "version": "0.0.1",
   "clientPublicKey": "78219c51f6157e629948166d3af8c90cf4c4f5b245513b47806ed4dbdb28d0b6",
   "applicationPublicKey": "a85ffc9026d9c9f7e302785f3f9ddd15c85ddc85eeaa3b24e23b9e736d66361d",
   "applicationSignature": "727d8bb9167861413b5c85a7f220b7464f05e3740d6f8dc78734fa764a3093ba7b84e81fae4e5574e300177564d93a1ca5b6f0e2bf594367fa39e99510bf800f"
 }

Once you have your AAT, include it with your project as a JSON file and import it.

const aat = require('./aat.json')

Next, we are going to obtain the Private Key File(PPK) from the dashboard or through the Pocket Core CLI.

A properly-formed ppk.json file will start with {"kdf":"scrypt"

Once you have obtained your key, we are going to import the key file into the project as a JSON file along with the passphrase used when creating it:

const accountPPK = require('./ppk.json')
const accountPassphrase = 'Qwerty1234!'

Now, we are going to unlock out acct and create the pocket instance so we can start relaying to our external blockchain.

// This is only called once to setup the Pocket Instance and AAT
async function unlockAAT(aat, accountPPK, accountPassphrase) {
    try {
        const account = await pocketInstance.keybase.importPPKFromJSON(
            accountPassphrase,
            JSON.stringify(accountPPK),
            accountPassphrase
        )
        await pocketInstance.keybase.unlockAccount(account.addressHex, accountPassphrase, 0)
        return await PocketAAT.fromSignature(
            aat.version,
            account.publicKey.toString('hex'),
            aat.applicationPublicKey,
            aat.applicationSignature
        )
    } catch(e) {
        console.log(e)
    }
}

Last, we will be sending a relay with our new pocket instance to our desired blockchian:

// Call this every time you want to fetch RPC data
async function sendRelay(rpcQuery, blockchain, pocketAAT) {
    try {
        return await pocketInstance.sendRelay(rpcQuery, blockchain, pocketAAT)
    } catch (e) {
        console.log(e)
    }
}

unlockAAT(aat, accountPPK, accountPassphrase).then(pocketAAT => {
    rpcQuery = '{"jsonrpc":"2.0","id":1,"method":"net_version","params":[]}'
    sendRelay(rpcQuery, blockchain, pocketAAT).then(result => {
        console.log(result.payload);
    })
})

Use Private Keys to Connect to Any Blockchain:

🚧

Security Risk

It is recommended as best practice to secure your account private key safe by using AAT to ensure your account is not compromised in any way. Please use it at your own risk and discretion.

The first thing we are going to do in our project is to declare our:

  • Application Private key
  • Application Public Key
  • Passphrase - To locally encrypt the account
const accountPrivateKey = '25a42ad8ef4b5...'
const accountPublicKey = '6e2cda5a6b6709...'
const accountPassphrase = 'Qwerty1234!'

Next, we are going to unlock our account and create our pocket instance

// This is only called once to setup the Pocket Instance and AAT
async function unlockAccount(accountPrivateKey, accountPublicKey, accountPassphrase) {
    try {
        const account = await pocketInstance.keybase.importAccount(
            Buffer.from(accountPrivateKey, 'hex'),
            accountPassphrase
        )
        await pocketInstance.keybase.unlockAccount(account.addressHex, accountPassphrase, 0)
        return await PocketAAT.from(
            "0.0.1",
            accountPublicKey,
            accountPublicKey,
            accountPrivateKey
        )
    } catch(e) {
        console.log(e)
    }
}

Last, we are going to send a relay to our external blockchain.

// Call this every time you want to fetch RPC data
 async function sendRelay(rpcQuery, blockchain, pocketAAT) {
     try {
         return await pocketInstance.sendRelay(rpcQuery, blockchain, pocketAAT)
     } catch (e) {
         console.log(e)
     }
 }

 unlockAccount(accountPrivateKey, accountPublicKey, accountPassphrase).then(pocketAAT => {
     rpcQuery = '{"jsonrpc":"2.0","id":1,"method":"net_version","params":[]}'
     sendRelay(rpcQuery, blockchain, pocketAAT).then(result => {
         console.log(result.payload);
     })
 })

Updated 7 days ago


Pocket JS


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.