Acala Wiki
LearnBuildMaintain
  • Acala & Karura Wiki
  • Acala 2.0
    • Overview
    • Execution Roadmap
    • aUSD SEED (aSEED)
      • aSEED Integration Guide
    • ACA
      • ACA/KAR Staking
    • Universal Asset Hub (UAH)
    • Euphrates DApp
  • Learn
    • Acala Introduction
      • Acala Dollar
      • AcalaSwap
      • Homa Liquid Staking
      • Redenomination of ACA
    • Trilogy Networks
    • Flexible Fees
      • How to change default fee token
    • Governance Overivew
      • Participate in Democracy
      • How to Verify a Runtime Upgrade
      • How to Verify Referendum Proposal
    • Treasury
    • Acala EVM+
      • Why Acala EVM+
      • Existing Solutions
      • Acala EVM+
        • Composable DeFi Stack
        • Flexible Fees
        • EVM Account
        • On-chain Scheduler
        • Queryable & Lightweight
        • Upgradable Contracts
        • Compatible Toolings
        • No Dust Account
      • How does it work?
  • Get started
    • Acala Network
      • Acala Launch Phases
      • Wallet & Account
        • Account Generation
          • Polkadot{.js} Browser Extension
          • Polkawallet Mobile App
          • Ledger Hardware Wallet
        • Exchange Withdraw/Deposit
        • Balance Type and Vesting
        • Check Address for Different Chains
      • Acala's DOT Bridge
      • Acala Assets
      • Governance
      • Acala Web Apps
      • Acala Mobile
    • Karura Network
      • Karura Launch Phases
      • Check Distribution
      • Wallets & Account
        • Account Generation
          • Polkadot{.js} Browser Extension
          • Polkawallet Mobile App
          • Ledger Hardware Wallet
        • Exchange Withdraw/Deposit
        • Balance Type & Vesting
        • Check Address for Different Chains
      • Inter Kusama Transfer
      • Karura Assets
      • Karura Web Apps
      • Governance
      • Transaction Fees
    • Mandala Testnet
  • Integrate
    • Acala Network
      • Protocol Info
      • Token Transfer
      • Node Interaction
      • Full Node
      • Collator
    • Karura Network
      • Protocol Info
      • Token Transfer
      • Node Interaction
      • Full Node
      • Collator
  • Build
    • EVM+ documentation
    • SDKs
      • Acala Stablecoin
      • Homa Liquid Staking
      • AcalaSwap
      • Homa Staking
    • Guides
      • Node Interaction
      • Transaction Construction
    • Build DApps
      • Deploy Ecosystem Modules
      • Composable Chains
        • Open HRMP Channel
        • Bridge Tokens
        • Cross-chain Listing
      • Open-Web3-Stack & ORML
      • Smart Contracts
        • Acala EVM Overview
        • Get Started
          • Connect to a Node
            • Use MetaMask with EVM+
          • Setup EVM Account
          • Polkadot Explorer
          • EVM Playground
          • Use Remix
          • Use Waffle
          • Use Hardhat
          • Deploy Contracts
        • Advanced
          • Use Native & Cross-chain Tokens
          • Use On-chain Scheduler
            • Tutorial
          • Use Oracle Feeds
          • Upcoming Features
        • Acala EVM Hacker Guide
          • Try Acala DApp
    • Tools
    • Indexers
      • SubQuery
    • Miscellaneous
      • Runtime Events
      • Modules
    • Cross Chain DeFi
  • Ecosystem
    • General Info
    • Alliance
    • Community
    • Contribution & Rewards
      • Acala Old Friend NFT
    • Ecosystem
    • Media Kits
    • Ledger Generic App Migration
  • Crowdloans
    • What are crowdloans
    • Acala Crowdloan
      • Crowdloan Event
      • Crowdloan Rewards
      • Claim ACA
      • How to Crowdloan
      • FAQ
      • Acala Quests
        • Attaching Polkawallet to Polkadot.js Extension
      • DOT Address
        • Creating a New DOT Account
        • Becoming a DOT Holder
        • Unstaking Your DOT
          • Unstaking Your DOT Tokens on Polkadot.{js} Extension
          • Unstaking Your DOT Tokens on Polkawallet
    • Karura Crowdloan
      • Crowdloan Event
      • Crowdloan Rewards
      • Claim KAR
      • How to Crowdloan
      • FAQ
      • KSM Address
        • Creating a New KSM Account
        • Check KSM Address
        • Unstaking Your KSM
          • Unstaking Your KSM Tokens on Polkawallet
          • Unstaking Your KSM Tokens on Polkadot.{js} Extension
      • Finding Tokens and NFTs
  • Misc
    • aUSD Incident
    • Contributing
    • Glossary
Powered by GitBook
On this page
  • Source Code of Karura Stablecoin
  • Read-Only Functions (State queries)
  • Get Vault for specific Account for given Collateral Type
  • Get total amount of collateral and borrowed kUSD for Collateral Type
  • Get Risk Parameters for given Collateral type.
  • Get Debt Exchange Rate for given collateral type
  • State-Changing Functions
  • Create and manage the Vault
  • Grants permission for transferring loan
  • Removes permission for transferring loan
  • Removes permissions for ALL accounts to transfer the vault
  • Transfering Vault to another account
  • Closing caller's Vault by swapping collateral in DeX

Was this helpful?

Edit on GitHub
  1. Build
  2. SDKs

Acala Stablecoin

PreviousSDKsNextHoma Liquid Staking

Last updated 3 years ago

Was this helpful?

To interact with Acala or Karura from Javascript you can use @polkadot/api along with @acala-network/api. You can learn more about @polkadot/api [here]. ().

We do also provide a which provides more some automation around stablecoins.

Source Code of Karura Stablecoin

Read-Only Functions (State queries)

These functions only read information from the chain, and thus don't require signing transactions with a private key. Read more about state queries here:

Get Vault for specific Account for given Collateral Type

Returns amount of collateral and amount of minted stablecoin as debit for specific collateral type and account.

Note debit reflects the only amount of minted kUSD. The amount of debt is higher as it includes accumulated interest. To calculate the total amount to payback you need to use debitExchangeRate parameter (the example for fetching debitExchangeRate is shown below).

positions(currencyId: CurrencyId, accountId: AccountId):
    Promise<{collateral: number, debit: number}>

Arguments

Name
Type

currencyId

CurrencyId

collateral currency Id

accountId

AccountId

account to fetch vaults for, can be passed as string

Example:

    const result = await api.query.loans.positions(
        { TOKEN: "KSM" },
        "<ACCOUNT>"
    );
  console.log(result.toHuman());

Full code snippet:

Get total amount of collateral and borrowed kUSD for Collateral Type

Returns total amount of collateral and amount of borrowed stablecoin as debit for specific collateral type.

totalPositions(currencyId: CurrencyId):
    Promise<{collateral: number, debit: number}>

Arguments

Name
Type

currencyId

CurrencyId

identificator for currency used as collateral

Example:

    const result = await api.query.loans.totalPositions(
        { TOKEN: "KSM" }
    );
  console.log(result.toHuman());

Full code snippet:

Get Risk Parameters for given Collateral type.

Each accepted by Karura Collateral Type can have different risk parameters. These values are controlled by Karura Governance.

collateralParams(currencyId: CurrencyId):
    Promise<{
    maximumTotalDebitValue: number,
    interestRatePerSec: number, 
    liquidationRatio: number,
    liquidationPenalty: number,
    requiredCollateralRatio: number,

    }>

Arguments

Name
Type

currencyId

CurrencyId

identificator for currency used as collateral

Return values

Name
Type

maximumTotalDebitValue

Number

maximum amount of KUSD that can be borrowed for one vault

interestRatePerSec

Percent

the percentage of borrowed kUSD to be paid each next block. This amount should be added to globalInterestRatePerSec to calculate the debt

liquidationRatio

Percent

collateral ratio (collateral value / debt value) reaching which the vault gets liquidated

liquidationPenalty

Percent

penalty that is charged from the vault if the vault gets liquidated

requiredCollateralRatio

Percent

Minimum collateral ratio till which user can borrow kUSD

Example:

    const result = await api.query.cdpEngine.collateralParams({ 
      TOKEN: "KSM" 
    });
    console.log(result.toHuman());

Full code snippet:

Get Debt Exchange Rate for given collateral type

This parameter is used to calculate the debt. The amount of minted kUSD should be multiplied by this parameter. As the Interest rate is accumulated depends on block number, it makes sense to fetch this parameter for a certain block.

debitExchangeRate(currencyId: CurrencyId):
    Promise<number}>

Arguments

Name
Type

currencyId

CurrencyId

identificator for currency used as collateral

Example:

  const result = await api.query.cdpEngine.debitExchangeRate.at(
      '<BLOCK_HASH'
      { TOKEN: "KSM" }
  );
  console.log(result.toHuman());

Full code snippet:

State-Changing Functions

These transactions write data on-chain and require a private key to sign the transaction. To perform run test code snippets ensure that you have SEED_PHRASE environment variable defined in your .env file.

Create and manage the Vault

All operations: creating a vault, adding/removing collateral, borrowing, paying back kUSD can be done using a single method: honzon.adjustLoan

adjustLoan(currency_id: CurrencyId, collateral_adjustment: Number, debit_adjustment: Number): Extrinsic

Arguments

Name
Type

currencyId

CurrencyId

collateral CurrencyId

collateral_adjustment

Signed Amount

positive means to deposit collateral currency into Vault, negative means withdraw collateral currency from the Vault

debit_adjustment

Signed Amount

positive means to mint some amount of stablecoin to the caller; negative means that caller will pay back stablecoin to the Vault

Example

  const currencyId = { TOKEN: "KSM" };
  const collateralAdjustment = <DESIRED_ADJUSTMENT>;
  const debitAdjustment = <DESIRED_ADJUSTMENT>;

  const extrinsic = api.tx.honzon.adjustLoan(
    currencyId,
    collateralAdjustment,
    debitAdjustment
  );
  const hash = await extrinsic.signAndSend(signer);
  console.log('hash', hash.toHuman());

Full code snippet:

Grants permission for transferring loan

Sets permission to transfer caller's loan to another Account (to).

authorize(curencyId: CurrencyId, to: AccountId): Extrinsic

Returns Extrinsic type that should be signed with a private key.

Arguments

Name
Type

currencyId

CurrencyId

collateral CurrencyId

to

AccountId

sets permission to transfer loan for this accountId

Example:

  const accountId = "<ACCOUNT_ID>";
  const extrinsic = api.tx.honzon.authorize(
    { TOKEN: "KSM" }, 
    accountId
  );
  const hash = await extrinsic.signAndSend(signer);
  console.log("hash", hash.toHuman());

Full code snippet:

Removes permission for transferring loan

Removes permission to transfer caller's loan to another Account (to). This method can be used to decline previously given permission.

unauthorize(curencyId: CurrencyId, to: AccountId): Extrinsic

Returns Extrinsic type that should be signed with a private key.

Arguments

Name
Type

currencyId

CurrencyId

collateral CurrencyId

to

AccountId

removes permission to transfer loan for this accountId

Example:

  const accountId = "<ACCOUNT_ID>";
  const extrinsic = api.tx.honzon.unauthorize(
    { TOKEN: "KSM" }, 
    accountId
  );
  const hash = await extrinsic.signAndSend(signer);
  console.log("hash", hash.toHuman());

Removes permissions for ALL accounts to transfer the vault

Removes permission to transfer caller's vault to ALL accounts for all Collateral types. This method can be used to decline previously given permission.

unauthorizeAll(): Extrinsic

Returns Extrinsic type that should be signed with a private key.

Example:

  const extrinsic = api.tx.honzon.unauthorizeAll();
  const hash = await extrinsic.signAndSend(signer);
  console.log("hash", hash.toHuman());

Transfering Vault to another account

Transfers Vault to the caller's account if it has permissions (if authorize was called previously by from account).

transferLoanFrom(currency_id, from): Extrinsic

Returns Extrinsic type that should be signed with a private key.

Arguments

Name
Type

currencyId

CurrencyId

collateral CurrencyId

from

AccountId

transfers collateral from this account to the caller

Example:

    const fromAccountId = "<ACCOUNT_ID>";
    const extrinsic = api.tx.honzon.transferLoanFrom(
      { TOKEN: "KSM" },
      fromAccountId
    );
    const hash = await extrinsic.signAndSend(signer);
    console.log("hash", hash.toHuman());

Closing caller's Vault by swapping collateral in DeX

This action can be done with adjustLoan, but there is a shortcut created for this purpose which is applied only to safe vaults (where the collateral ratio is above liquidation level) and where the debt amount is positive.

This method closes the caller's Vault by selling a sufficient amount of collateral on Karura Dex.

closeLoanHasDebitByDex(
    currency_id: CurrencyId, 
    max_collateral_amount: number, 
    maybe_path?: CurrencyId[]
): Extrinsic

Returns Extrinsic type that should be signed with a private key.

Arguments

Name
Type

currencyId

CurrencyId

collateral CurrencyId

max_collateral_amount

number

the maximum collateral that's allowed to be swapped in DeX to pay back the Vault

maybe_path

CurrencyId[]

swap path that can be used for swapping collateral for kUSD in DeX

Example:

    const extrinsic = api.tx.honzon.closeLoanHasDebitByDex(
      { TOKEN: "KSM" },
      // large number, allows swapping almost any amount
      1 * 10 ** 30,
      [{ TOKEN: "KSM" }, { TOKEN: "KUSD" }]
    );
    const hash = await extrinsic.signAndSend(signer);
    console.log("hash", hash.toHuman());

Full code snippet:

Note the supply amount should be denormalised with KAR decimals for this example

⚠️
⚠️
https://polkadot.js.org/docs/api
Stablecoin SDK
https://github.com/AcalaNetwork/Acala/tree/master/modules/honzon
State queries docs
loan-examples/get-positions.js
loan-examples/total-positions.ts
loan-examples/collateral-params.ts
loan-examples/debit-exchange-rate.ts
loan-examples/adjustLoan.ts
loan-examples/authorize.ts
loan-examples/close-vault-with-dex.ts