Skip to content
Gregory Luneau edited this page Mar 14, 2022 · 16 revisions

Getting Started

These sections would provide you the information needed to install the @acala-network/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 @acala-network/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 acala-network/api provides types and other interactions specific to the Acala Network.

Create an Instance

import { ApiPromise, WsProvider } from "@polkadot/api";
import { options } from "@acala-network/api";

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

  // use api
}

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

Examples

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

Simple Connect

import { options } from "@acala-network/api";
import { ApiPromise, WsProvider } from "@polkadot/api";

async function main() {
  const provider = new WsProvider("wss://karura.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

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

import { options } from "@acala-network/api";
import { ApiPromise, WsProvider } from "@polkadot/api";

async function main() {
  const provider = new WsProvider("wss://karura.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: "KSM",
  });
  console.log(tokenData.toHuman());

  // LCDOT
  const liquidCrowdloanData = await api.query.tokens.account(address, { LiquidCrowdloan: 13 });
  console.log(liquidCrowdloanData.toHuman());

  // taiKSM
  const stableAssetPoolData = await api.query.tokens.account(address, { StableAssetPool: 0 });
  console.log(stableAssetPoolData.toHuman());

  // RMRK
  const foreignAssetData = await api.query.tokens.account(address, { ForeignAsset: 0 });
  console.log(foreignAssetData.toHuman());
}

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

Transfer

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

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

async function main() {
  const provider = new WsProvider("wss://karura.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: "KSM",
      },
      "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 aUSD Loan

When borrowing aUSD, a debit amount is stored on-chain to account for aUSD owed plus accumulated interest etc. A debitExchangeRate is provided to calculate exchange rate between aUSD 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('@acala-network/api');

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

async function main() {
    const provider = new WsProvider('wss://karura.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 ACA Token balance
    const accountData = await api.query.system.account(address);
    console.log(accountData.toHuman());

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

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

    const debitExData = await api.query.cdpEngine.debitExchangeRate('XBTC');
    console.log(debitExData.toHuman());
    
    // Open an aUSD loan with XBTC as collateral
    const collateralAmt = '1000000000000000000';
    const debitAmt = '3635270000000000000000';
    await api.tx.honzon.adjustLoan('XBTC', collateralAmt, debitAmt).signAndSend(newPair);
    
    const loanData = await api.query.loans.debits('XBTC', 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('@acala-network/api');
const { Fixed18, convertToFixed18 } = require('@acala-network/app-util');

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

async function main() {
    const provider = new WsProvider('wss://karura.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 DeX

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

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

async function main() {
    const provider = new WsProvider('wss://karura.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
  	
    // DOT -> aUSD
  	
    // Set Supply Amount
    const supply = 1
    
    // Query Dex Pool
    const pool = await api.derive.dex.pool('DOT');
  
    // 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(
        'DOT',
        Fixed18.fromNatural(supply).innerToString(),
        'AUSD',
        Fixed18.fromNatural(target).innerToString()
    ).signAndSend(newPair);

    // Ensure Amount
    const dotAccount = await api.query.tokens.accounts(address, 'DOT');
    console.log(dotAccount.toHuman());
  
    const aUSDAccount = await api.query.tokens.accounts(address, 'AUSD');
    console.log(aUSDAccount.toHuman());
}

main()