citvydex

0.6.8 • Public • Published

citvydex

Package for work with Citvy DEX. The main class in the package is Citvy. All you need is in it. There are a couple more helper classes, but they are not really designed for use outside of the Citvy class.

The Citvy class consists of static methods intended for working with the Citvy public blockchain API. Using the Citvy class, you can create an object whose methods provide access to the private part of the Citvy blockchain API.

Setup

If you use npm

This library can be obtained through npm:

$ npm install citvydex

If you want use REPL-mode:

$ npm install -g citvydex

If you use browser

Include this in html-file:

<script src="citvydex.min.js"></script>

After that in console available Citvy class.

Usage

citvydex package contain class Citvy:

const Citvy = require('citvydex')

To connect to the Citvy network, you must call connect method:

await Citvy.connect();

By default, Citvy connected to wss://Citvy.openledger.info/ws. If you want set another node to connect:

await Citvy.connect("wss://<url>/ws")

You can also connect to the network using the event system.

Public API

After the connection, you can use any public method from official documentation (if the method is still relevant!).

Database API

To access the Database API, you can use the Citvy.db object.

An example of methods from the Database API:

get_objects(const vector <object_id_type> & ids) const

list_assets(const string & lower_bound_symbol, uint32_t limit) const

To use them:

let obj = await Citvy.db.get_objects(["1.3.0"])
let citvy = await Citvy.db.list_assets("CIV", 100)

History API

To access the Account History API, you can use the Citvy.history object.

Example of a method from the Account History API:

get_account_history (account_id_type account, operation_history_id_type stop = operation_history_id_type (), unsigned limit = 100, operation_history_id_type start = operation_history_id_type ()) const

To use it:

let ops = await Citvy.history.get_account_history("1.2.849826", "1.11.0", 10, "1.11.0")

Private API

If you want to have access to account operations, you need to create a Citvy object.

If you know privateActiveKey:

let acc = new Citvy(<accountName>, <privateActiveKey>)

or if you know password:

let acc = Citvy.login(<accountName>, <password>)

or if you have bin-file:

let buffer = fs.readFileSync(<bin-file path>);
let acc = Citvy.loginFromFile(buffer, <wallet-password>, <accountName>)

While this object can not much: buy, sell, transfer, cancel order, asset reserve, asset issue and more.

Signatures of methods:

acc.buy(buySymbol, baseSymbol, amount, price, fill_or_kill = false, expire = "2020-02-02T02: 02: 02")
acc.sell(sellSymbol, baseSymbol, amount, price, fill_or_kill = false, expire = "2020-02-02T02: 02: 02")
acc.cancelOrder(id)
acc.transfer(toName, assetSymbol, amount, memo)
acc.assetIssue(toName, assetSymbol, amount, memo)
acc.assetReserve(assetSymbol, amount)

Examples of using:

await acc.buy("BTC", "CIV", 0.002, 140000)
await acc.sell("CIV", "USD", 187, 0.24)
await acc.transfer("mindfulme", "BTS", 10)
await acc.assetIssue("mindfulme", "ABC", 10)
await acc.assetReserve("ABC", 12)

If you want to send tokens with memo and get acc from constructor (use new Citvy()), then before that you need to set a private memo-key:

bot.setMemoKey(<privateMemoKey>)
await bot.transfer("mindfulme", "USD", 10, "Thank you for CIV DEX!")

Transaction Builder

Each private transaction is considered accepted after being included in the block. Blocks are created every 3 seconds. If we need to perform several operations, their sequential execution can take considerable time. Fortunately, several operations can be included in a single transaction. For this you need to use transaction builder.

For create new transaction:

let tx = Citvy.newTx([<activePrivateKey>,...])

or if you have account object acc:

let tx = acc.newTx()

For get operation objects:

let operation1 = await acc.transferOperation("mindfulme", "CIV", 10)
let operation2 = await acc.assetIssueOperation("mindfulme", "ABC", 10)
...

Added operation to transaction:

tx.add(operation1)
tx.add(operation2)
...

If you want to know the cost of the transaction:

let cost = await tx.cost()
console.log(cost) // { BTS: 1.234 }

After broadcast transaction:

await tx.broadcast()

or

await acc.broadcast(tx)

The account has a lot more operations available than an instance of the Citvy class. If you know what fields the transaction you need consists of, you can use the transaction builder for that.

For example:

let Citvy = require("citvydex")

Citvy.subscribe("connected", start)

async function start() {
  let acc = await Citvy.login(<accountName>, <password>)

  let params = {
    fee: {amount: 0, asset_id: "1.3.0"},
    name: "trade-bot3",
    registrar: "1.2.21058",
    referrer: "1.2.21058",
    referrer_percent: 5000,
    owner: {
      weight_threshold: 1,
      account_auths: [],
      key_auths: [[<ownerPublicKey>, 1]],
      address_auths: []
    },
    active: {
      weight_threshold: 1,
      account_auths: [],
      key_auths: [[<activePublicKey>, 1]],
      address_auths: []
    },
    options: {
      memo_key: <memoPublicKey>,
      voting_account: "1.2.5",
      num_witness: 0,
      num_committee: 0,
      votes: []
    },
    extensions: []
  };

  let tx = acc.newTx()
  tx.account_create(params) // 'account_create' is name operation
  await tx.broadcast()
}

Event system

Very often we have to expect, when there will be some action in the blockchain, to which our software should respond. The idea of ​​reading each block and viewing all the operations in it, seemed to me ineffective. Therefore, this update adds an event system.

Event types

At the moment, citvydex has three types of events:

  • connected - works once after connecting to the blockchain;
  • block - it works when a new block is created in the blockchain;
  • account - occurs when the specified account is changed (balance change).

For example:

const Citvy = require("citvydex");

Citvy.subscribe('connected', startAfterConnected);
Citvy.subscribe('block', callEachBlock);
Citvy.subscribe('account', changeAccount, 'trade-bot');

async function startAfterConnected() {/* is called once after connecting to the blockchain */}
async function callEachBlock(obj) {/* is called with each block created */}
async function changeAccount(array) {/* is called when you change the 'trade-bot' account */}
The connected event

This event is triggered once, after connecting to the blockchain. Any number of functions can be subscribed to this event and all of them will be called after connection.

Citvy.subscribe('connected', firstFunction);
Citvy.subscribe('connected', secondFunction);

Another feature of the event is that when you first subscription call the method Citvy.connect(), i.e. will be an automatic connection. If by this time the connection to the blockchain has already been connected, then it will simply call the function.

Now it's not necessary to explicitly call Citvy.connect(), it's enough to subscribe to the connected event.

const Citvy = require("citvydex");

Citvy.subscribe('connected', start);

async function start() {
  // something is happening here
}
The block event

The block event is triggered when a new block is created in the blockchain. The first event subscription automatically creates a subscription to the connected event, and if this is the first subscription, it will cause a connection to the blockchain.

const Citvy = require("citvydex");

Citvy.subscribe('block', newBlock);

// need to wait ~ 10-15 seconds
async function newBlock(obj) {
  console.log(obj); // [{id: '2.1.0', head_block_number: 17171083, time: ...}]
}

As you can see from the example, an object with block fields is passed to all the signed functions.

The account event

The account event is triggered when certain changes occur (balance changes). These include:

  • If the account sent someone one of their assets
  • If an asset has been sent to an account
  • If the account has created an order
  • If the account order was executed (partially or completely), or was canceled.

The first subscriber to account will call a block subscription, which in the end will cause a connection to the blockchain.

Example code:

const Citvy = require("citvydex");

Citvy.subscribe('account', changeAccount, 'mindfulme');

async function changeAccount (array) {
  console.log(array); // [{id: '1.11.37843675', block_num: 17171423, op: ...}, {...}]
}

In all the signed functions, an array of account history objects is transferred, which occurred since the last event.

REPL-mode

If you install citvydex-package in global storage, you may start citvydex exec script:

$ citvydex
>|

This command try autoconnect to mainnet Citvy. If you want to connect on testnet, try this:

$ citvydex --testnet
>|

or use --node key:

$ citvydex --node wss:<websocket endpoint to connect>
>|

It is nodejs REPL with several variables:

  • Citvy, main class Citvy package
  • login, function to create object of class Citvy
  • generateKeys, to generateKeys from login and password
  • accounts, is analog Citvy.accounts
  • assets, is analog Citvy.assets
  • db, is analog Citvy.db
  • history, is analog Citvy.hostory
  • network, is analog Citvy.network
  • fees, is analog Citvy.fees

For example

$ citvydex
> assets["citvy"].then(console.log)

Shot request

If need call only one request, you may use --account, --asset, --block, --object, --history or --transfer keys in command-line:

$ citvydex --account <'name' or 'id' or 'last number in id'>
{
  "id": "1.2.5992",
  "membership_expiration_date": "1970-01-01T00:00:00",
  "registrar": "1.2.37",
  "referrer": "1.2.21",
  ...
}
$ citvydex --asset <'symbol' or 'id' or 'last number in id'>
{
  "id": "1.3.0",
  "symbol": "BTS",
  "precision": 5,
  ...
}
$ citvydex --block [<number>]
block_num: 4636380
{
  "previous": "0046bedba1317d146dd6afbccff94412d76bf094",
  "timestamp": "2018-10-01T13:09:40",
  "witness": "1.6.41",
  ...
}
$ citvydex --object 1.2.3
{
  "id": "1.2.3",
  "membership_expiration_date": "1969-12-31T23:59:59",
  "registrar": "1.2.3",
  "referrer": "1.2.3",
  ...
}
$ citvydex --history <account> [<limit>] [<start>] [<stop>]
[
  {
    "id": "1.11.98179",
    "op": [
      0,
  ...
}]
$ citvydex --transfer <from> <to> <amount> <asset> [--key]
Transfered <amount> <asset> from '<from>' to '<to>' with memo '<memo>'

Helper classes

There are a couple more helper classes, such as Citvy.assets and Citvy.accounts:

let usd = await Citvy.assets.usd;
let btc = await Citvy.assets["OPEN.BTS"];
let citvy = await Citvy.assets["citvy"];

let iam = await Citvy.accounts.mindfulme;
let tradebot = await Citvy.accounts["trade-bot"];

The returned objects contain all the fields that blockchain returns when the given asset or account name is requested.

Some examples:

const Citvy = require('citvydex')
KEY = 'privateActiveKey'

Citvy.subscribe('connected', startAfterConnected)

async function startAfterConnected() {
  let bot = new Citvy('trade-bot', KEY)

  let iam = await Citvy.accounts['trade-bot'];
  let orders = await Citvy.db.get_full_accounts([iam.id], false);
  
  orders = orders[0][1].limit_orders;
  let order = orders[0].sell_price;
  console.log(order)
}

Documentation

For more information, look wiki or in docs-folder.

Contributing

Bug reports and pull requests are welcome on GitHub. For communication, you can use the Telegram-channel.

master-branch use for new release. For new feature use dev branch. All pull requests are accepted in dev branch.

License

The package is available as open source under the terms of the MIT License.

Readme

Keywords

Package Sidebar

Install

npm i citvydex

Weekly Downloads

1

Version

0.6.8

License

MIT

Unpacked Size

20.3 kB

Total Files

6

Last publish

Collaborators

  • mindfulme