Giter Site home page Giter Site logo

descent-collective / descent-sdk Goto Github PK

View Code? Open in Web Editor NEW
3.0 0.0 1.0 1.65 MB

Descent JS is a javaScript library that makes it easy to build applications on top of Descent's smart contracts

License: MIT License

TypeScript 97.85% JavaScript 1.68% HTML 0.48%

descent-sdk's Introduction

Descent Library

Descent SDK is a Typescript library that makes it easy to build applications on top of Descent's multi-currency Stablecoin System. You can use Descent's contracts to open Collateralized Debt Positions, withdraw loans in xNGN, trade tokens on Onboard Exchange, and more.

The library features a pluggable, service-based architecture, which allows users maximal control when integrating the Descent protocol's functionality into existing infrastructures. It also includes convenient configuration presets for out-of-the-box usability, and support for both front-end and back-end applications.

Descent's entire suite of contracts will eventually be accessible through this library—including the DAO governance and the current alpha version is limited to the following areas:

  • Managing Vault Positions
  • Locking and unlocking collateral
  • Withdrawing and repaying xNGN
  • Automated token conversions
  • Buying and selling $DSN and $xNGN with built-in DEX integration

TODO

  • ✅ Improve presets and configuration settings
  • ✅ Make configuration services oriented
  • ✅ Perform getters using MultiStaticCall in the protocol-periphery contract to interact with the VaultGetter contract
  • ✅ Perform state change calls using the VaultRouter protocol-periphery contract
  • Enable listening of events for state changes
  • Add functionality for automated token conversions (V2)
  • Add functionality for buying and selling of $DSN and $xNGN in DEXs (V2)
  • Add USD onramp and xNGN offramp functionalities (V2)

Installation

Install the package with npm in your terminal:

npm install @descent-protocol/sdk

Once it's installed, import the module into your project as shown below.

import Descent from '@descent-protocol/sdk';
// or
const Descent = require('@descent-protocol/sdk');

UMD

This library is also usable as a browser module

<script src="./descent.js" />

<script>
  // once the script loads, window.Descent is available
</script>

Quick examples

Look up information about a vault

This code uses getVaultInfo to look up a vault that was created in the Descent protocol UI. Since this code is only reading data, not creating any transactions, it is not necessary to provide a private key or connect a wallet.

// you provide these values
const infuraKey = 'your-infura-api-key';
const ownerAddress = '0xf00...';

const descent = await Descent.create('https', {
  url: `https://mainnet.infura.io/v3/${infuraKey}`
  collateral: 'USDC'
});

const vaultInfo = descent.getVaultInfo(ownerAddress);
console.log(
  vault.depositedCollateral, // amount of collateral tokens deposited
  vault.collateralLocked, // amount of collateral locked in the system
  vault.borrowedAmount, // amount of currency(xNGN) debt
  vault.accruedFees, // amount of fees accrued by the vault
  vault.currentCollateralRatio, // collateralValue  to debt ratio
  vault.healthFactor, // vaults health factor to determine liquidatable status
  vault.availableCollateral, // amount of collateral in the system available
  vault.availablexNGN, // amount of xNGN in the system ready to be minted
  vault.currentRate, // current accumulated rate of vault
);

Descent.create

You can configure the behavior of descent.js by passing different arguments to Descent.create. The first argument is the name of a preset, and the second is an options object.

Presets

  • 'browser' Use this preset when using the library in a browser environment. It will attempt to connect using window.ethereum or window.web3. Make sure you pass in the connected browser provider instance

  • 'https' Connect to a JSON-RPC node. Requires url to be set in the options.

const descentBrowser = await Descent.create('browser');

const descentHttp = await Descent.create('httpsRA_PROJECT_ID'
});

Options

  • privateKey

    • Optional. The private key used to sign transactions. If this is omitted, the first account available from the Ethereum provider will be used. Only used with the 'https' preset.
    • If this is omitted and the provider does not have an unlocked account, the descent object will start in read-only mode.
  • url

    • The URL of the node to connect to. Only used with the 'http' preset.
  • ethereum

    • For advanced users. You can inject your own custom instance of a Web3 provider with this, instead of using the default HttpProvider.
// It doesn't necessarily make sense to set all these
// options at the same time (e.g. `url` and `inject`),
// this is just meant to illustrate the shape of the
// options object.
const descent = await Descent.create('https', {
  privateKey: YOUR_PRIVATE_KEY, // '0xabc...'
  url: 'http://some-ethereum-rpc-node.net',
  ethereum: someProviderInstance
  },
});

API Reference

  1. Methods

  2. UTILITY METHODS

methods

getVaultInfo

descent.getVaultInfo(ownerAddress: string): Promise<{}>

Gets detailed information about a vault specified by the owner's address.

Parameters

  • `ownerAddress``: The owner's address of the vault.

Returns:

  • A promise resolving to the vault information.
    {
      healthFactor: 'Safe',
      depositedCollateral: 670000000n,  // returns in 6 decimals - 1e6
      collateralLocked: 227255070n,  // returns in 6 decimals - 1e6
      borrowedAmount: 187391000000000000000000n,  // returns in 18 decimals - 1e18
      accruedFees: 94431149147375637960n,  // returns in 18 decimals - 1e18
      currentCollateralRatio: 25439000155922303400n,  // returns in 18 decimals - 1e18
      availableCollateral: 442744930n,  // returns in 6 decimals - 1e6
      availablexNGN: 365264568850852624362040n  // returns in 18 decimals - 1e18
    }

setupVault

descent.setupVault(): Promise<{}>

Initializes a vault for a first time user and sets up the appropriate configuration for the vault on the ssmart contract

Returns:

  • A promise resolving to the transaction object.

getVaultSetupStatus

descent.getVaultSetupStatus(): Promise<{}>

Checks if a vault has already been initialized for the connected address or owner.

Returns:

  • A boolean.

depositCollateral

descent.depositCollateral('100'): Promise<{}>

Deposits USDC for a particular vault.

Parameters

  • collateralAmount: The amount of unlocked collateral to deposit.

Returns:

  • A promise resolving to the transaction object.

borrowCurrency

descent.borrowCurrency('10000'): Promise<{}>

Borrows xNGN against deposited USDC.

Parameters

  • borrowAmount: The amount of xNGN to borrow.

Returns:

  • A promise resolving to the transaction object.

repayCurrency

descent.repayCurrency('9000'): Promise<{}>

Repays borrowed xNGN for a particular vault.

Parameters

  • amount: The amount of xNGN to repay.

Returns:

  • A promise resolving to the transaction object.

withdrawCollateral

descent.withdrawCollateal('9000'): Promise<{}>

Withdraws USDC for a particular vault.

Parameters

  • collateralAmount: The amount of unlocked collateral to withdraw.

Returns:

  • A promise resolving to the transaction object.

getCollateralInfo

descent.getCollateralInfo(): Promise<{}>

Gets information about the collateral initialized in create().

Returns:

  • A promise resolving to the collateral information.
{
      totalDepositedCollateral: 4004000000n, // returns in 6 decimals - 1e6
      totalBorrowedAmount: 1668492000000000000000000n,  // returns in 18 decimals - 1e18
      liquidationThreshold: '750000000000000000',  // returns in 18 decimals - 1e16 - should be represented in percentage
      debtCeiling: 115792089237316195423570985008687907853269984665640564039457584007913129639935n,  // returns in 18 decimals - 1e18
      rate: 24999999949728000n,  // returns in 18 decimals - 1e16
      minDeposit: 0n,  // returns in 18 decimals - 1e18
      collateralPrice: 1100000000n  // returns in 6 decimals - 1e6
    }

utilities

Helper functions to ease interaction with different token contracts.

getCollateralTokenBalance

descent.getCollateralTokenBalance(ownerAddress: string): Promise<{}>

Gets the balance of USDC for an address

Parameters

  • ownerAddress: The address of the account connected

Returns:

  • The usdc balance of the account

approveCollateral

descent.approveCollateral('100'): Promise<{}>

Approves the vault contract to get allowance of specified amount for the USDC token

Parameters

  • amount: The amount of allowance to give

Returns:

  • Returns transaction object

getxNGNBalance

descent.getxNGNBalance(ownerAddress: string): Promise<{}>

Gets the balance of xNGN for an address

Parameters

  • ownerAddress: The address of the account connected

Returns:

  • The xNGN balance of the account

approvexNGN

descent.approvexNGN('100'): Promise<{}>

Approves the vault contract to get allowance of specified amount for the xNGN token

Parameters

  • amount: The amount of allowance to give

Returns:

  • Returns transaction object

descent-sdk's People

Contributors

njokuscript avatar junhoyeo avatar meisterjustice avatar

Stargazers

Toản Lê avatar Jeon Jinho avatar  avatar

Forkers

junhoyeo

descent-sdk's Issues

Implement payback currency method

Overview

The SDK lacks a payback currency method utilizing the vaultRouter contract. This issue proposes the implementation of the payBack method

Motivation

Adding a payback currency method is essential for users interacting with the Descent protocol vault.

Proposed Changes

Implement a new method in the TypeScript SDK that allows users to pay back the stablecoins borrowed using the vaultRouter contract. The method should handle the necessary interactions and transactions seamlessly.

Implementation Details

  • Introduce a new method specifically for burning currencies/paying back debt.
  • Utilize token names as part of the collateral parameters
  • Consider gas optimization, error handling, and any potential edge cases during the implementation.

Testing Plan

Unit Tests

  • Create comprehensive unit tests to ensure the correct functioning of the mint currency method.

Integration Tests

Conduct integration tests to verify that the method works seamlessly within the SDK and integrates well with other functionalities.

Documentation Updates

Update the Descent documentation to include information on the newly implemented method and it's usage.

Implement mint currency(stablecoin) method

Overview

The SDK lacks a mint currency method utilizing the vaultRouter contract. This issue proposes the implementation of the mintCurrency method

Motivation

Adding a mint currency method is essential for users interacting with the Descent protocol vault.

Proposed Changes

Implement a new method in the TypeScript SDK that allows users to withdraw/mint new stablecoins(currency) using the vaultRouter contract. The method should handle the necessary interactions and transactions seamlessly.

Implementation Details

  • Introduce a new method specifically for minting new currencies.
  • Utilize token names as part of the collateral parameters
  • Consider gas optimization, error handling, and any potential edge cases during the implementation.

Testing Plan

Unit Tests

  • Create comprehensive unit tests to ensure the correct functioning of the mint currency method.

Integration Tests

Conduct integration tests to verify that the method works seamlessly within the SDK and integrates well with other functionalities.

Documentation Updates

Update the Descent documentation to include information on the newly implemented method and it's usage.

Implement getter services using MultiStaticcall

Overview

The SDK lacks efficient mechanisms for retrieving vault information from a peripheral contract. This issue proposes the implementation of getter services using MultiStaticcall to enhance the SDK's capability to fetch vault-related data.

Motivation

Fetching vault information often involves multiple calls to the vaultRouter peripheral contract, resulting in increased latency and decreased efficiency. The integration of MultiStaticcall will allow for a more optimized and streamlined process of retrieving relevant data from the peripheral contract.

Proposed Changes

The proposed changes involve implementing getter services that leverage MultiStaticcall to efficiently retrieve vault information from the peripheral contract.

Implementation Details

  • Introduce a new service or method specifically designed for fetching vault information.
  • Utilize MultiStaticcall to aggregate multiple calls into a single transaction, reducing the number of round trips to the peripheral contract.

Testing Plan

Unit Tests

  • Create comprehensive unit tests to ensure the correct functionality of the newly implemented getter services.

Integration Tests

  • Conduct integration tests to verify that the MultiStaticcall integration works seamlessly with the existing SDK functionality.

Documentation Updates

Update the Descent documentation to include information on the newly implemented getter services and their usage.

Add Support for Base Sepolia Network on SDK

Problem

Currently, the Typescript SDK only supports the Base GOERLI network. We need to enhance the SDK to allow initialization with different networks, enabling it to dynamically interact with contracts on the specified network.

Description

  • Currently, the SDK is limited to the Base Goerli network, restricting its flexibility in working with different blockchain networks.
  • The SDK should be extended to support initialization with a specific network, allowing it to dynamically call contracts on that network.

Acceptance Criteria

  • The SDK should successfully initialize with the specified network(Sepolia).
  • Contract calls should be dynamically routed to the correct network based on the initialization parameter.

Others

  • Find the latest contract deployments for sepolia here => core & periphery

Implement deposit collateral method

Overview

The SDK lacks a deposit collateral method utilizing the vaultRouter contract. This issue proposes the implementation of the depositCollateral method

Motivation

Adding a deposit collateral method is essential for users interacting with the Descent protocol vault.

Proposed Changes

Implement a new method in the TypeScript SDK that allows users to deposit collateral using the vaultRouter contract. The method should handle the necessary interactions and transactions seamlessly.

Implementation Details

  • Introduce a new method specifically for adding collaterals to a vault.
  • Utilize token names as part of the collateral parameters
  • Consider gas optimization, error handling, and any potential edge cases during the implementation.

Testing Plan

Unit Tests

  • Create comprehensive unit tests to ensure the correct functioning of the deposit collateral method.

Integration Tests

Conduct integration tests to verify that the method works seamlessly within the SDK and integrates well with other functionalities.

Documentation Updates

Update the Descent documentation to include information on the newly implemented method and it's usage.

Improve presets and configuration settings

Overview

The current presets lack flexibility and comprehensive coverage for various environments.
This issue proposes an enhancement to the presets and configuration settings to better accommodate different use cases and improve the overall user experience.

Proposed Changes

The proposed changes involve refining and expanding the existing presets in Descent.create({}) to better cater to different scenarios. Additionally, we will introduce improvements to the configuration settings to enhance customization.

Updated Presets:

browser:

  • Use this preset when employing the library in a browser environment.
  • It will attempt to connect using window.ethereum or window.web3.

https:

  • Connect to a JSON-RPC node.
  • Requires the URL to be set in the options.

test:

  • Use a local node (e.g., Ganache) running at http://127.0.0.1:2000/.
  • Sign transactions using node-managed keys.

Implement withdraw collateral method

Overview

The SDK lacks a withdraw collateral method utilizing the vaultRouter contract. This issue proposes the implementation of the withdrawCollateral method

Motivation

Adding a withdraw collateral method is essential for users interacting with the Descent protocol vault.

Proposed Changes

Implement a new method in the TypeScript SDK that allows users to withdraw available collateral using the vaultRouter contract. The method should handle the necessary interactions and transactions seamlessly.

Implementation Details

  • Introduce a new method specifically for withdrawing collaterals to a vault.
  • Utilize token names as part of the collateral parameters
  • Consider gas optimization, error handling, and any potential edge cases during the implementation.

Testing Plan

Unit Tests

  • Create comprehensive unit tests to ensure the correct functioning of the withdrawing collateral method.

Integration Tests

Conduct integration tests to verify that the method works seamlessly within the SDK and integrates well with other functionalities.

Documentation Updates

Update the Descent documentation to include information on the newly implemented method and it's usage.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.