Skip to content
Muhammad-Jibril edited this page Oct 23, 2021 · 2 revisions

Getting Started

These sections would provide you the information needed to install the @setheum-js/api package, understand the structures, and start using it. It is not a line-by-line documentation of all existing function calls.

Help us improve

If you spot gaps in the information provided, or are uncertain about any areas, please log an issue, or make a pull request to help us improve so we can provide more effective documentations to people.

Installation

Install the API via

yarn add @polkadot/api @setheum-js/api

npm will be made available once it's feature complete and stable.

Basics

For general polkadot-js interactions with the blockchain, e.g. state queries, PRC calls, keyring etc., please refer to the polkadot-js/api documentation for more details. The setheum-js/api provides types and other interactions specific to the Setheum Network.

Create an Instance

import { ApiPromise, WsProvider } from "@polkadot/api";
import { options } from "@setheum-js/api";

async function main() {
  const provider = new WsProvider("wss://setheum.api.onfinality.io/public-ws");
  const api = new ApiPromise(options({ provider }));
  await api.isReadyOrError;

  // use api
}

main().then(() => process.exit(0));

Examples

Setheum's public nodes and web socket info can be found here.

Simple Connect

import { options } from "@setheum-js/api";
import { ApiPromise, WsProvider } from "@polkadot/api";

async function main() {
  const provider = new WsProvider("wss://setheum.api.onfinality.io/public-ws");
  const api = new ApiPromise(options({ provider }));
  await api.isReadyOrError;

  const [chain, nodeName, nodeVersion] = await Promise.all([
    api.rpc.system.chain(),
    api.rpc.system.name(),
    api.rpc.system.version(),
  ]);

  console.log(
    `You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`
  );
}

main().then(() => process.exit(0));

Account Balances

Setheum Network supports multi-currencies. Network native token (SETM) can be queried via system balance, where other tokens can be queried via tokens. Find supported currencies here.

import { options } from "@setheum-js/api";
import { ApiPromise, WsProvider } from "@polkadot/api";

async function main() {
  const provider = new WsProvider("wss://setheum.api.onfinality.io/public-ws");
  const api = new ApiPromise(options({ provider }));
  await api.isReadyOrError;

  const address = "tFBV65Ts7wpQPxGM6PET9euNzp4pXdi9DVtgLZDJoFveR9F";
  const accountData = await api.query.system.account(address);
  console.log(accountData.toHuman());

  const tokenData = await api.query.tokens.accounts(address, {
    Token: "SETM",
  });
  console.log(tokenData.toHuman());
}

main().then(() => process.exit(0));

Transfer

Setheum Network can use balances.transfer(dest, value) for native token (SETM) transfers. It is also possible to transfer all token using currencies.transfer(dest, currency_id, amount)

import { options } from "@setheum-js/api";
import { ApiPromise, WsProvider } from "@polkadot/api";
import { createTestPairs } from "@polkadot/keyring/testingPairs";

async function main() {
  const provider = new WsProvider("wss://setheum.api.onfinality.io/public-ws");
  const api = new ApiPromise(options({ provider }));
  await api.isReadyOrError;

  const testingPair = createTestPairs();

  const fromAddress = testingPair.alice.address;
  const toAddress = "rXMrmePtNnyZ61hvpjfEEZ1zmKzueUnTqijDncTzE8Wa2sJ";

  const beforeAccountData = await api.query.system.account(fromAddress);
  console.log(beforeAccountData.toHuman());

  const hash = await api.tx.currencies
    .transfer(
      toAddress,
      {
        Token: "SETM",
      },
      "1000000000000"
    )
    .signAndSend(testingPair.alice);

  console.log("Transfer sent with hash", hash.toHex());
}

main()
  .then(() => process.exit(0))
  .catch((err) => {
    console.log(err);
    process.exit(1);
  });

Create an SETUSD Loan

When borrowing SETUSD, a debit amount is stored on-chain to account for SETUSD owed etc. A debitExchangeRate is provided to calculate exchange rate between SETUSD and debit amount.

The same method api.tx.honzon.adjustLoan is used to payback the load, deposit more collateral or withdraw.

Read more on keyring here. Get test token here.

const { ApiPromise } = require('@polkadot/api');
const { WsProvider } = require('@polkadot/rpc-provider');
const { options } = require('@setheum-js/api');

const { Keyring } = require('@polkadot/api');

async function main() {
    const provider = new WsProvider('wss://setheum.api.onfinality.io/public-ws');
    const api = new ApiPromise(options({ provider }));
    await api.isReady;

    const keyring = new Keyring({ type: 'sr25519' });
    const newPair = keyring.addFromUri('yourinput');
    const address = newPair.address;
    console.log(newPair.address); // you need to get test tokens

    // Query SETM Token balance
    const accountData = await api.query.system.account(address);
    console.log(accountData.toHuman());

    // Query other tokens e.g. RENBTC balance
    const tokenData = await api.query.tokens.accounts(address, 'RENBTC');
    console.log(tokenData.toHuman());

    // Query BTC price
    const oracleData = await api.query.oracle.values('RENBTC');
    console.log(oracleData.toHuman());

    const debitExData = await api.query.cdpEngine.debitExchangeRate('RENBTC');
    console.log(debitExData.toHuman());
    
    // Open an SETUSD loan with RENBTC as collateral
    const collateralAmt = '1000000000000000000';
    const debitAmt = '3635270000000000000000';
    await api.tx.honzon.adjustLoan('RENBTC', collateralAmt, debitAmt).signAndSend(newPair);
    
    const loanData = await api.query.loans.debits('RENBTC', address);
    console.log(loanData.toHuman());
}

main()

Monitor and bid for auctions

const { ApiPromise } = require('@polkadot/api');
const { WsProvider } = require('@polkadot/rpc-provider');
const { options } = require('@setheum-js/api');
const { Fixed18, convertToFixed18 } = require('@setheum-js/app-util');

const { Keyring } = require('@polkadot/api');

async function main() {
    const provider = new WsProvider('wss://setheum.api.onfinality.io/public-ws');
    const api = new ApiPromise(options({ provider }));
    await api.isReady;

    const keyring = new Keyring({ type: 'sr25519' });
    const newPair = keyring.addFromUri('yourinput');
    const address = newPair.address;
    console.log(newPair.address); // you need to get test tokens
  	
    const auctionId = 1;

    // Query Collateral Auction Info of auction 1
    const auction = api.query.auctionManager.collateralAuctions(auctionId);
    console.log(auction.toHuman());
  
    // Query Auction Bid Info
    const bid = api.query.auction.auctions(auctionId);
    console.log(bid.toHuman());
  
    // Query minimumIncrementSize
    const minimumIncrementSize = api.consts.auctionManager.minimumIncrementSize;
  
    // Calcaule Bit Amount
    const bitAmount = convertFixed18(bid?.bid[2]).mul(Fixed18.fromNature(1).add(convertFixed18(minimumIncrementSize));
  
    // Bit
    await api.tx.auction.bid(auctionId, bitAmount.innerToString()).signAndSend(newPair);
}

main()

Swap on SetSwap

const { ApiPromise } = require('@polkadot/api');
const { WsProvider } = require('@polkadot/rpc-provider');
const { options } = require('@setheum-js/api');
const { Fixed18, convertToFixed18, calcSwapTargetAmount } = require('@setheum-js/app-util');

const { Keyring } = require('@polkadot/api');

async function main() {
    const provider = new WsProvider('wss://setheum.api.onfinality.io/public-ws');
    const api = new ApiPromise(options({ provider }));
    await api.isReady;

    const keyring = new Keyring({ type: 'sr25519' });
    const newPair = keyring.addFromUri('yourinput');
    const address = newPair.address;
    console.log(newPair.address); // you need to get test tokens
  	
    // DNAR -> SETUSD
  	
    // Set Supply Amount
    const supply = 1
    
    // Query Dex Pool
    const pool = await api.derive.dex.pool('DNAR');
  
    // Query Exchange Fee
    const exchangeFee = api.consts.dex.getExchangeFee;
    
    // Calculate Target Currency Amount
    const target = calcSwapTargetAmount(
        supply,
        convertToFixed18(pool.base),
        convertToFixed18(pool.other),
        convertToFixed18(exchangeFee),
        Fixed18.fromNature(0.005)
    );
  
    // Exec Exchange
    await api.tx.dex.swapCurrency(
        'DNAR',
        Fixed18.fromNatural(supply).innerToString(),
        'SETUSD',
        Fixed18.fromNatural(target).innerToString()
    ).signAndSend(newPair);

    // Ensure Amount
    const dotAccount = await api.query.tokens.accounts(address, 'DNAR');
    console.log(dotAccount.toHuman());
  
    const SETUSDAccount = await api.query.tokens.accounts(address, 'SETUSD');
    console.log(SETUSDAccount.toHuman());
}

main()