Skip to content

dispatchlabs/dispatch-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@dispatchlabs/dispatch-js NPM version NPM monthly downloads NPM total downloads

The Dispatch SDK for Node and JavaScript developers.

Please consider following this project's author, LinkedIn Profile, and consider starring the project to show your ❤️ and support.

Install

Install with npm:

$ npm install --save @dispatchlabs/dispatch-js

CDN

The JavaScript version of the SDK may be included on the pae with the following CDN location:

<script src="https://cdn.jsdelivr.net/npm/@dispatchlabs/dispatch-js/dist/dispatch.js"></script>

Migrating from disnode_sdk

If you are moving from our previous SDK (disnode_sdk) to this version you will need to replace all occurrences of DisNodeSDK and/or DisJS to Dispatch.

Usage

Node:

var Dispatch = require('@dispatchlabs/dispatch-js');
// or
import Dispatch from '@dispatchlabs/dispatch-js';

JavaScript:

For JavaScript, the top-level object is Dispatch.

Running examples

Examples are contained in the examples folder and can be executed in Node using:

$ npm install && npm run examples

To execute the JavaScript examples, open the examples/js/index.html file in a browser window.

Changing the network the SDK talks to

In node_modules/@dispatchlabs/dispatch-js/lib/config.json you will see the various environments. Use development for building and testing,

To change the environment set NODE_ENV:

$ NODE_ENV=development node myScript.js

By default the SDK talks to the production network.

Models

Account

Account constructor. Create an instance of an account, which can then be used to interact with the network.

  • returns {Object}: instance of Account

Examples

// Create an empty account
let account = new Dispatch.Account();
account.init();
// Create an account using a known address
let account = new Dispatch.Account('fa61c18114f8ff8aafbeb5d32e1b108e3f6cf30d');
// Create an account using a private key (the address and public key will be filled in automatically)
let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});

Refreshes the account balance and access info (created and updated dates) from a delegate.

  • returns {Promise}: Promise that will return the result of the Delegate request after updating account object.

Example

let account = new Dispatch.Account('fa61c18114f8ff8aafbeb5d32e1b108e3f6cf30d');
account.refresh()
  .then(() => {
    console.log(account);
  })
  .catch((err) => {
    console.error(err);
  });

Generaes a new private key for the account object (replacing one if present).

  • returns {Account}: Returns the account object for use in chaining.

Example

let account = new Dispatch.Account();
account.init();
console.log(account);

Creates and sends a transaction that will transfer tokens from the source account, to the target account.

Params

  • {string|Account}: to - The address or Account to send the tokens to.
  • {number}: The number of Divitos to send. 1 Divvy = 100,000,000 Divitos
  • returns {Transaction}: Returns a transaction which has already been sent.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
// Send one (1) token
let tx = account.sendTokens(new Dispatch.Account().init(), 1);

// Or - to send to an address without making an account
let tx = account.sendTokens("dbf2bb4792c1ae1338b1cdc55a9f68e0e62c0fb8", 1);

Creates and sends a transaction from the account that will create a new Smart Contract.

Params

  • {string}: code - Bytecode of a compiled contract.
  • {string|array}: code - The ABI of the contract.
  • returns {Transaction}: Returns a transaction which has already been sent.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi);

Calls a Smart-Contract from the account that will emulate executing a method and return the result without costing hertz or writing a transaction to the ledger.

Params

  • {string|Account|Transaction}: to - The address of an existing contract, an Account representing the contract, or the contract creation Transaction.
  • {string}: method - The method in the contract to call.
  • {array}: params - The parameters to use during the method call.
  • returns {Transaction}: Returns a transaction which has already been sent.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});

let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi);
contract.whenStatusEquals('Ok')
  .then(() => {
    account.executeRead(contract, 'g', [])
        .then((result) => {
            console.log('Contract Read result:\n' + JSON.stringify(result) + '\n');
        }, (err) => {
            console.log('Contract Read result error:\n' + JSON.stringify(err) + '\n');
        });
  })
  .catch((err) => {
    console.error(err);
  });

// Or - to call a method on a deployed contract
account.executeWrite("dbf2bb4792c1ae1338b1cdc55a9f68e0e62c0fb8", 'g', []);

Creates and sends a transaction from the account that will execute a method on an existing Smart Contract.

Params

  • {string|Account|Transaction}: to - The address of an existing contract, an Account representing the contract, or the contract creation Transaction.
  • {string}: method - The method in the contract to call.
  • {array}: params - The parameters to use during the method call.
  • returns {Transaction}: Returns a transaction which has already been sent.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});

let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
let contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi);
contract.whenStatusEquals('Ok')
  .then(() => {
    account.executeWrite(contract, 'g', [])
        .whenStatusEquals('Ok')
            .then((result) => {
              console.log('Contract Write result:\n' + JSON.stringify(result) + '\n');
            }, (err) => {
              console.log('Contract Write result error:\n' + JSON.stringify(err) + '\n');
            });
  })
  .catch((err) => {
    console.error(err);
  });

// Or - to call a method on a deployed contract
account.executeWrite("dbf2bb4792c1ae1338b1cdc55a9f68e0e62c0fb8", 'g', []);

Transaction

Transaction constructor. Create an instance of a transaction, which can then be sent to a delegate.

  • returns {Object}: instance of Transaction

Example

// Create a new transaction
let account = new Dispatch.Account().init();
let tx = new Dispatch.Transaction({from: account});

Sends the transaction to a delegate.

  • returns {Promise}: Promise that will return the result of the Delegate request.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
let tx = new Dispatch.Transaction({from: account});
tx.send()
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.error(err);
  });

Requests the current status of the transaction from a delegate.

  • returns {Promise}: Promise that will return the result of the status check.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
let tx = new Dispatch.Transaction({from: account});
tx.send();
tx.status()
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.error(err);
  });

Waits until the status of the transaction matches the value provided, then resolves. Rejects after 5 seconds or when the transaction hits a non-matching final state.

Params

  • {string}: status - Desired status for the transaction to acheive.
  • returns {Promise}: Promise that will return the result of the status check. If a timeout occured, the returned data will be the latest known state along with a key of SDKTimeout: true.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
let tx = new Dispatch.Transaction({from: account});
tx.send();
tx.whenStatusEquals('Ok')
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.error(err);
  });

Static method to compile Solidity code directly.

Params

  • {string}: source - Solidity source code containing one or more contracts.
  • returns {compiledSource}: Compiled output JSON.

Example

let account = new Dispatch.Account({
 name: 'MyAccount',
 privateKey: '472ba91402425b58a2eebf932812f20c6d7f6297bba1f83d9a58116ae6512d9e'
});
let compiled = Dispatch.Transaction.compileSource('contract x { function g() { } }');
if (compiled.errors.length > 0) {
  // Errors are fatal
  console.error(compiled.errors);
} else {
  // Warnings are non-fatal
  if (compiled.warnings.length > 0) {
    console.log(compiled.warnings);
  }
  // compiled.contracts contains the name, bytecode, and abi for each contract contained within the source
  const contract = account.createContract(compiled.contracts[0].bytecode, compiled.contracts[0].abi);
}

Static method to compile complex Solidity JSON structures.

Params

Example

let compiled = Dispatch.Transaction.compile({language: 'Solidity', sources: { source: { content: 'contract x { function g() { } }' }}});

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Author

David Hutchings at Dispatch Labs

License

Copyright © 2018, Dispatch Labs. Released under the LGPL-2.1 License.


This file was generated by verb-generate-readme, v0.8.0, on October 16, 2018.

About

Dispatch JavaScript SDK - Both browser and node

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published