Skip to content

Library Initialization

3 edited this page Jan 13, 2023 · 13 revisions

You can install API JS library using npm or any other NodeJS package manager. See Readme for reference.

npm install adamant-api

Initialize the library, passing list of ADAMANT nodes and log object. It's better to initialize API library in a separate module api.js, and then refer to it.

// api.js
const adamantApi = require('adamant-api');
const customLogger = require('./logger.js');

const nodesList = [
  'http://localhost:36666',
  'https://endless.adamant.im',
  'https://clown.adamant.im',
  'http://23.226.231.225:36666',
  'http://88.198.156.44:36666',
  'https://lake.adamant.im'
];

const callback = () => console.log(
    'ADAMANT API is ready to use!'
);

const options = {
  node: nodesList,
  logLevel: 'info',
  checkHealthAtStartup: false, // default is true
  checkNodeTimeout: 10000, // 10 seconds, default value is 4000
};

module.exports = adamantApi(options, customLogger, callback);

List of ADAMANT nodes options.node is an array including nodes you want to connect.

The library will use verbosity according to options.logLevel parameter: it can be none < error < warn < info < log.

If options.checkHealthAtStartup is set to false, the API library will update node statuses only when request is failed

By default, adamant-api will consider node as unavailable if it doesn't respond within 4 seconds. You can control the time by setting options.checkNodeTimeout in milliseconds. Set it to 0 for infinite wait

Object customLogger is used to log current operations. It must implement error, info, warn an log methods. See an example. If no logger provided, the library uses the system console.

The callback function is a callback that will be called after initialization and health check if options.checkHealthAtStartup is not false. It also can be set using the setStartupCallback method:

api.setStartupCallback(() => {
  // ...
})

Then refer to JS API in other modules:

// file blockChecker.js
const api = require('./api');

api.get('blocks').then(response => {
  console.log(response.data)
})

If you want to use WebSocket connections, initialize socket:

// file app.js
const api = require('./api');

api.socket.initSocket({
  socket: true,
  wsType: 'ws',
  onNewMessage: txParser,
  admAddress: 'U6386412615727665758'
});

Set socket to true to activate socket connections. Param wsType is one of "ws" or "wss", depending on your host.

Function onNewMessage will be executed when new transaction appears for given admAddress with transaction object passed. In this example, txParser(transaction) will be called.

Clone this wiki locally