Shelf.Network JavaScript SDK

The Shelf.Network JavaScript SDK facilitates client integration with the Shelf.Network auction platform.

Table of content

  1. Javascript SDK

  2. Development Guide

  3. Troubleshooting

JavaScript SDK

Installation

npm install -S shelf-network-sdk

Webpack

If you use webpack as your build system, you'll need to exclude the optional native module ed25519

  plugins: [
    new webpack.IgnorePlugin(/ed25519/)
  ]

You can also check out package's webpack config.

Prebuilt Minified Scripts

The package also ships prebuilt minified scripts for browsers in the /dist folder.

<script type="text/javascript" src="https://<sdk-dist-url>"></script>
<script type="text/javascript">
  (async () => {
    let sdk = await Sdk.ShelfNetwork.create({
      gatewayUrl: 'https://api.staging.shelf.network'
    })
    // ...
  })()
</script>

Shelf.Network SDK

To get started, create a Shelf.Network SDK instance:

import { ShelfNetwork } from 'shelf-network-sdk'

const sdk = await ShelfNetwork.create({
  gatewayUrl: 'https://api.staging.shelf.network'
})

You can configure different environment setting such as proxy configuration via options.

Response Format

All HTTP responses share the following format:

{
  httpStatus: 200,

  // Flattened and camel-cased response data
  data: [
    {
      resourceType: 'deposits',
      id: '209529',
      accountId: 'GDWF6Q7MAFWGJG2NFP75RESDKL33QUVPREP4MGSZ3BGS5BYWOHU3GJ2A',
      amount: '4267.00',
      currency: 'GEL',
      state: 2,
      stateStr: 'paid'
    }
  ],

  // Response headers
  headers: {...},

  // Parsed links and relations
  fetchNext: () => {...},
  fetchPrev: () => {...},
  fetchAccount: () => {...}
}

The links and relations that are returned with the responses are converted into functions you can call on the returned object. For example you can use them for simple pagination through collections:

const page = await sdk.horizon.balances.getPage()
console.log('Page', page.data)

const prevPage = await page.fetchPrev()
console.log('Previous page', prevPage.data)

Errors

Common errors

Wrappers for error responses

All the error responses subclass ServerErrorBase and share the following format:

{
  httpStatus: 403,
  // Human readable title
  title: 'Forbidden',
  // Detailed explanation
  detail: 'Additional factor required.',
  // Additional relevant data
  meta: {
    factorId: 275,
    factorType: 'password',
    ...
  },
  // Raw unparsed error
  originalError: {...},
  // Retry request. Handy for 2FA handling
  retryRequest: () => {...}
}

Interceptors

SDK allows you to use request and response interceptors:

sdk.api.useRequestInterceptors(
  request => {
    // Track user's actions, transform request data, etc
  },
  err => {
    // Log, handle errors, retry requests, etc
  }
)

sdk.api.useResponseInterceptor(
  config => {
    // Parse and transform response data, show notifications, etc
  },
  err => {
    // Track errors, try to retry requests, show 2FA prompts, etc
  }
)

Authentication

Each request is authenticated to each service via JWT. A token is represented by the base64 string stored in Authorization header with syntax Bearer {token}.

A client passes his credentials upon registration. Later this credentials will be used to retrieve temporary JWTs.

Retrieve and use the token to authenticate requests

const token = await sdk.auth.getToken('my@email.com', 'MyPassw0rd', platformId)
sdk.useToken(token)

Refresh a token

const newToken = await sdk.auth.refreshToken()
sdk.useToken(newToken)

Change password

await sdk.auth.changePassword('oldPassword', 'newPassword')

Request password recovery

await sdk.auth.requestRecovery('my@email.com')

Confirm recovery

// accountId, token are parsed from the recovery link
await sdk.auth.confirmRecovery(accountId, token, 'newPassword')

Services and Resource Groups

Each backend service has an associated object attached to an SDK instance that inherits ServerBase class. It contains methods that encapsulate endpoint calls and may also have some associated resource groups.

List of services and associated resource groups:

Building and Submitting Transactions

WARNING: deprecated for the web apps. Use only for dev tools.

Blockchain transactions must have:

  • Source - user's account ID
  • One or more operations
  • User's signature

Building and signing

import { base } from 'shelf-network-sdk'

let tx = new base.TransactionBuilder(sdk.wallet.accountId)
  .addOperation(base.Operation.payment(paymentParamsObject))
  .build();

tx.sign(sdk.wallet.keypair);

Submitting

let response = await sdk.horizon.transactions.submit(tx)

Handling XDR encoded fields in responses

The transaction endpoints will return some fields in raw XDR form. You can convert this XDR to JSON using the .fromXDR() method.

An example of re-writing the txHandler from above to print the XDR fields as JSON:

import { base } from 'shelf-network-sdk'

let envelope = response.data.envelopeXdr
console.log(base.xdr.TransactionEnvelope.fromXDR(envelope, 'base64'))

let result = response.data.resultXdr
console.log(base.xdr.TransactionResult.fromXDR(result, 'base64'))

let resultMeta = response.data.resultMetaXdr
console.log(base.xdr.TransactionMeta.fromXDR(resultMeta, 'base64'))

Development Guide

Transpiling

As for now, some handy ES7 features need transpiler in both node.js and browser environments, so the babel transpiler is used.

Build for node.js:

npm run build

Build for browsers:

npm run build:browser

Coding Style

SDK follows JavaScript Standard Style.

All public classes and functions must have JSDoc annotations.

Run linter to check for style violations:

npm run lint

Testing

Node.js tests:

npm test

Browser tests:

npm tests:browser

Test coverage:

npm run coverage

Building XDR Files

SDK repository includes xdr git submodule which contains raw .x XDR files.

To update the JS wrappers:

  1. Check out the xdr submodule to the desired commit
  2. Install Ruby v 2.5.0 if needed
  3. Install rake and bundler:
     gem install rake bundler
  4. Install xdrgen dependencies
     bundle
  5. Build the XDR wrappers:
     rake xdr:update

Generating Docs

npm run docs

Troubleshooting

Problem With Installation on Windows

When installing js-sdk on windows, you might see an error that looks similar to the following:

error MSB8020: The build tools for v120 (Platform Toolset = 'v120 ') cannot be found. To build using the v120 build tools, please install v120 build tools.  Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting "Retarget solution"

To resolve this issue, you should upgrade your version of nodejs, node-gyp and then re-attempt to install the offending package using npm install -g --msvs_version=2015 ed25519. Afterward, retry installing stellar-sdk as usual.