> For the complete documentation index, see [llms.txt](https://mars-protocol.gitbook.io/mars-protocol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mars-protocol.gitbook.io/mars-protocol/contracts-core/red-bank.md).

# Red Bank

The Red Bank contract exposes all interactions that are done between the user and the money market. It also holds all protocol liquidity.

## Links

* package (msgs and types): <https://github.com/mars-protocol/mars-core/tree/master/packages/mars-core/src/red_bank>
* contract: <https://github.com/mars-protocol/mars-core/blob/master/contracts/mars-red-bank/src/contract.rs>
* schema: <https://github.com/mars-protocol/mars-core/tree/master/contracts/mars-red-bank/schema>

## Config

| Key                        | Type          | Description                                                                |
| -------------------------- | ------------- | -------------------------------------------------------------------------- |
| `owner`                    | CanonicalAddr | Contract owner                                                             |
| `address_provider_address` | CanonicalAddr | Address provider returns addresses for all protocol contracts              |
| `ma_token_code_id`         | u64           | maToken code id used to instantiate new tokens                             |
| `close_factor`             | Decimal       | Maximum percentage of outstanding debt that can be covered by a liquidator |

## InstantiateMsg

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
    pub config: CreateOrUpdateConfig
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "config": {
    "owner": "terra...", 
    "address_provider_address": "terra...", 
    "ma_token_code_id": 123,
    "close_factor": 0.01
  }
}
```

{% endtab %}
{% endtabs %}

### `CreateOrUpdateConfig`

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct CreateOrUpdateConfig {
    pub owner: Option<String>,
    pub address_provider_address: Option<String>,
    pub ma_token_code_id: Option<u64>,
    pub close_factor: Option<Decimal>
}
```

| Key                          | Type    | Description                                                                |
| ---------------------------- | ------- | -------------------------------------------------------------------------- |
| `owner`\*                    | String  | Contract owner                                                             |
| `address_provider_address`\* | String  | Address provider returns addresses for all protocol contracts              |
| `ma_token_code_id`\*         | u64     | maToken code id used to instantiate new tokens                             |
| `close_factor`\*             | Decimal | Maximum percentage of outstanding debt that can be covered by a liquidator |

\* = optional

## ExecuteMsg

### `UpdateConfig`

Update contract config (only owner can call).

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    UpdateConfig {
        config: CreateOrUpdateConfig
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "update_config": {
    "config": {
      "owner": "terra...", 
      "address_provider_address": "terra...", 
      "ma_token_code_id": 123,
      "close_factor": 0.01
    }
  }
}
```

{% endtab %}
{% endtabs %}

### `Receive`

Implementation of cw20 receive msg.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    Receive(Cw20ReceiveMsg)
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "receive": 
}
```

{% endtab %}
{% endtabs %}

### `InitAsset`

Initialize an asset on the money market (only owner can call).

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    InitAsset {
        asset: Asset, 
        asset_params: InitOrUpdateAssetParams,
        asset_symbol: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "init_asset": {
    "asset": "terra...",
    "asset_params": {
      "initial_borrow_rate": 0.01, 
      "reserve_factor": 0.01, 
      "max_loan_to_value": 0.01,
      "liquidation_threshold": 0.01,
      "liquidation_bonus": 0.01, 
      "interest_rate_model_params": {}, 
      "active": true, 
      "deposit_enabled": true, 
      "borrow_enabled": true
    }, 
    "asset_symbol": "optional_string"
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type                    | Description                                                                                                                                       |
| -------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `asset`        | String                  | Asset related info                                                                                                                                |
| `asset_params` | InitOrUpdateAssetParams | Asset parameters                                                                                                                                  |
| `asset_symbol` | String                  | Asset symbol to be used in maToken name and description. If none is provided denom will be used for native and token symbol will be used for cw20 |

### `InitOrUpdateAssetParams`

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InitOrUpdateAssetParams {
    pub initial_borrow_rate: Option<Decimal>, 
    pub reserve_factor: Option<Decimal>, 
    pub max_loan_to_value: Option<Decimal>, 
    pub liquidation_threshold: Option<Decimal>, 
    pub liquidation_bonus: Option<Decimal>, 
    pub interest_rate_model_params: Option<InterestRateModelParams>,
    pub active: Option<bool>, 
    pub deposit_enabled: Option<bool>, 
    pub borrow_enabled: Option<bool>
}
```

| Key                            | Type                             | Description                                                                                                                                    |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `initial_borrow_rate`\*        | Option\<Decimal>                 | Initial borrow rate                                                                                                                            |
| `reserve_factor`\*             | Option\<Decimal>                 | Portion of the borrow rate that is kept as protocol rewards                                                                                    |
| `max_loan_to_value`\*          | Option\<Decimal>                 | Max uusd that can be borrowed per uusd of collateral when using the asset as collateral                                                        |
| `liquidation_threshold`\*      | Option\<Decimal>                 | uusd amount in debt position per uusd of asset collateral that if surpassed makes the user's position liquidatable.                            |
| `liquidation_bonus`\*          | Option\<Decimal>                 | Bonus amount of collateral liquidator get when repaying user's debt (Will get collateral from user in an amount equal to debt repayed + bonus) |
| `interest_rate_model_params`\* | Option\<InterestRateModelParams> | Interest rate strategy to calculate borrow\_rate and liquidity\_rate                                                                           |
| `active`\*                     | Option\<bool>                    | If false cannot do any action (deposit/withdraw/borrow/repay/liquidate)                                                                        |
| `deposit_enabled`\*            | Option\<bool>                    | If false cannot deposit                                                                                                                        |
| `borrow_enabled`\*             | Option\<bool>                    | If false cannot borrow                                                                                                                         |

\* = optional

### `InitAssetTokenCallback`

Callback sent from maToken contract after instantiated.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    InitAssetTokenCallback {
        reference: Vec<u8>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "init_asset_token_callback": {
    "reference": [
      [123], 
      [123] 
    ]
  }
}
```

{% endtab %}
{% endtabs %}

| Key         | Type     | Description                                                                    |
| ----------- | -------- | ------------------------------------------------------------------------------ |
| `reference` | Vec\<u8> | Either the denom for a terra native asset or address for a cw20 token in bytes |

### `UpdateAsset`

Update an asset on the money market (only owner can call).&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    UpdateAsset {
        asset: Asset, 
        asset_params: InitOrUpdateAssetParams
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "update_asset": {
    "asset": "terra...", 
    "asset_params": {
      "initial_borrow_rate": 0.01, 
      "reserve_factor": 0.01, 
      "max_loan_to_value": 0.01,
      "liquidation_threshold": 0.01,
      "liquidation_bonus": 0.01, 
      "interest_rate_model_params": {}, 
      "active": true, 
      "deposit_enabled": true, 
      "borrow_enabled": true
    }
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type                    | Description        |
| -------------- | ----------------------- | ------------------ |
| `asset`        | String                  | Asset related info |
| `asset_params` | InitOrUpdateAssetParams | Asset parameters   |

### `UpdateUncollateralizedLoanLimit`

Update uncollateralized loan limit for a given user and asset. Overrides previous value if any. A limit of zero means no uncollateralized limit and the debt in that asset needs to be collateralized (only the owner can call).

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    UpdateUncollateralizedLoanLimit {
        user_address: String, 
        asset: Asset, 
        new_limit: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "update_uncollateralized_loan_limit": {
    "user_address": "terra...", 
    "asset": "terra...", 
    "new_limit": 123
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type    |                                       |
| -------------- | ------- | ------------------------------------- |
| `user_address` | String  | Address that receives the credit      |
| `asset`        | String  | Asset the user receives the credit in |
| `new_limit`    | Uint128 | Limit for the uncolateralize loan     |

### `DepositNative`

Deposit Terra native coins.&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    DepositNative {
        denom: String, 
        on_behalf_of: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "deposit_native": {
    "denom": "uusd", 
    "on_behalf_of": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key              | Type   | Description                            |
| ---------------- | ------ | -------------------------------------- |
| `denom`          | String | Denom used in Terra (e.g: uluna, uusd) |
| `on_behalf_of`\* | String | Address that will receive the maTokens |

\* = optional

### `Withdraw`

Withdraw an amount of the asset burning an equivalent amount of maTokens. If asset is a Terra native token, the amount sent to the user is selected so that the sum of the transfered amount plus the stability tax payed is equal to the withdrawn amount.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    Withdraw {
        asset: Asset, 
        amount: Option<Uint128>, 
        recipient: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "withdraw": {
    "asset": {
          "native": {
              "denom": "uusd"
          }
        },
    "amount": "10000", 
    "recipient": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key           | Type    | Description                                                                                                                        |
| ------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `asset`       | String  | Asset to withdraw                                                                                                                  |
| `amount`\*    | Uint128 | Amount to be withdrawn. If None is specified, the full maToken balance will be burned in exchange for the equivalent asset amount. |
| `recipient`\* | String  | The address where the withdrawn amount is sent                                                                                     |

\* = optional

### `Borrow`

Borrow Terra native coins. If borrow allowed, amount is added to caller's debt and sent to the address. If asset is a Terra native token, the amount sent is selected so that the sum of the transfered amount plus the stability tax payed is equal to the borrowed amount.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    Borrow {
        asset: Asset,
        amount: Uint128, 
        recipient: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "borrow": {
    "asset": {
          "native": {
              "denom": "uluna"
          }
        },
    "amount": "1000", 
    "recipient": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key           | Type    | Description                                   |
| ------------- | ------- | --------------------------------------------- |
| `asset`       | String  | Asset to borrow                               |
| `amount`      | Uint128 | Amount to borrow                              |
| `recipient`\* | String  | The address where the borrowed amount is sent |

\* = optional

### `RepayNative`

Repay Terra native coins loan. Coins used to repay must be sent in the transaction this call is made.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    RepayNative {
        denom: String, 
        on_behalf_of: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "repay_native": {
    "denom": "uusd", 
    "on_behalf_of": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key              | Type   | Description                            |
| ---------------- | ------ | -------------------------------------- |
| `denom`          | String | Denom used in Terra (e.g: uluna, uusd) |
| `on_behalf_of`\* | String | Repay the funds for the user           |

&#x20;\* = optional

### `LiquidateNative`

Liquidate under-collateralized native loans. Coins used to repay must be sent in the transaction this call is made.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg { 
    LiquidateNative {
        collateral_asset: Asset, 
        debt_asset_denom: String, 
        user_address: String, 
        receive_ma_token: bool
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "liquidate_native": {
    "collateral_asset": "terra...", 
    "debt_asset_denom": "uusd", 
    "user_address": "terra...", 
    "receive_ma_token": true
  }
}
```

{% endtab %}
{% endtabs %}

| Key                | Type   | Description                                                                                                    |
| ------------------ | ------ | -------------------------------------------------------------------------------------------------------------- |
| `collateral_asset` | String | Collateral asset liquidator gets from the borrower                                                             |
| `debt_asset_denom` | String | Denom used in Terra (e.g: uluna, uusd) of the debt asset                                                       |
| `user_address`     | String | The address of the borrower getting liquidated                                                                 |
| `receive_ma_token` | Bool   | Whether the liquidator gets liquidated collateral in maToken (true) or the underlying collateral asset (false) |

### `UpdateAssetCollateralStatus`

Update (enable / disable) asset as collateral for the caller.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    UpdateAssetCollateralStatus {
        asset: Asset, 
        enable: bool
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "update_asset_collateral_status": {
    "asset": "terra...", 
    "enable": true
  }
}
```

{% endtab %}
{% endtabs %}

| Key      | Type   | Description                                                   |
| -------- | ------ | ------------------------------------------------------------- |
| `asset`  | String | Asset to update status for                                    |
| `enable` | Bool   | Option to enable (true) / disable (false) asset as collateral |

### `FinalizeLiquidityTokenTransfer`

Called by liquidity token (maToken). Validate liquidity token transfer is valid and update collateral status.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum ExecuteMsg {
    FinalizeLiquidityTokenTransfer {
        sender_address: Addr, 
        recipient_address: Addr, 
        sender_previous_balance: Uint128, 
        recipient_previous_balance: Uint128, 
        amount: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "finalize_liquidity_token_transfer": {
    "sender_address": "terra...", 
    "recipient_address": "terra...",
    "sender_previous_balance": 123,
    "recipient_previous_balance": 123,
    "amount": 100000
  }
}
```

{% endtab %}
{% endtabs %}

| Key                          | Type    | Description                                                                                    |
| ---------------------------- | ------- | ---------------------------------------------------------------------------------------------- |
| `sender_address`             | String  | Token sender. Address is trusted because it should have been verified in the token contract    |
| `recipient_address`          | String  | Token recipient. Address is trusted because it should have been verified in the token contract |
| `sender_previous_balance`    | Uint128 | Sender's balance before the token transfer                                                     |
| `recipient_previous_balance` | Uint128 | Recipient's balance before the token transfer                                                  |
| `amount`                     | Uint128 | Transfer amount                                                                                |

## ReceiveMsg

### `DepositCw20`

Deposit sent cw20 tokens.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReceiveMsg {
    DepositCw20 {
        on_behalf_of: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "deposit_cw20": {
    "on_behalf_of": "terra..."
  }
}
```

{% endtab %}

{% tab title="Untitled" %}

```
{
  "withdraw": {
    "asset": {
        "cw20": {
            "contract_addr": "terra1747mad58h0w4y589y3sk84r5efqdev9q4r02pc"
        }
    },
    "amount": "10", 
    "recipient": "terra18mxdzx2mqs335k8avy24c5er0jx88a3gau0r2a"
  }
}
```

{% endtab %}
{% endtabs %}

| Key              | Type   | Description                    |
| ---------------- | ------ | ------------------------------ |
| `on_behalf_of`\* | String | Deposit the funds for the user |

\* = optional

### `RepayCw20`

Repay sent cw20 tokens.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReceiveMsg {
    RepayCw20 {
        on_behalf_of: Option<String>
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "repay_cw20": {
    "on_behalf_of": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key              | Type   | Description                  |
| ---------------- | ------ | ---------------------------- |
| `on_behalf_of`\* | String | Repay the funds for the user |

\* = optional

### `LiquidateCw20`

Liquidate under-collateralized cw20 loan using the sent cw20 tokens.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReceiveMsg {
    LiquidateCw20 {
        collateral_asset: Asset, 
        user_address: String, 
        receive_ma_token: bool
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "liquidate_cw_20": {
    "collateral_asset": "terra...", 
    "user_address": "terra...",
    "receive_ma_token": true
  }
}
```

{% endtab %}
{% endtabs %}

| Key                | Type   | Description                                                                                                    |
| ------------------ | ------ | -------------------------------------------------------------------------------------------------------------- |
| `collateral_asset` | String | Collateral asset liquidator gets from the borrower                                                             |
| `user_address`     | String | The address of the borrower getting liquidated                                                                 |
| `receive_ma_token` | Bool   | Whether the liquidator gets liquidated collateral in maToken (true) or the underlying collateral asset (false) |

## QueryMsg

### `Config`

Get contract config.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    Config {}
}
```

{% endtab %}

{% tab title="JSON" %}

```json
 {
  "config": {}
}
```

{% endtab %}
{% endtabs %}

### `Market`

Get asset market.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    Market {
        asset: Asset
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "market": {
    "asset": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key     | Type   | Description                |
| ------- | ------ | -------------------------- |
| `asset` | String | Asset to return market for |

### `MarketsList`

Get a list of all markets.&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    MarketsList {}
}
```

{% endtab %}

{% tab title="JSON" %}

```json
 {
  "markets_list": {}
}
```

{% endtab %}
{% endtabs %}

### `UncollateralizedLoanLimit`

Get uncollateralized limit for given asset and user.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UncollateralizedLoanLimit {
        user_address: String, 
        asset: Asset
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "uncollateralized_loan_limit": {
    "user_address": "terra...", 
    "asset": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type   | Description                                     |
| -------------- | ------ | ----------------------------------------------- |
| `user_address` | String | User address to get uncollateralized limit for  |
| `asset`        | String | Asset address to get uncollateralized limit for |

### `UserDebt`

Get all debt positions for a user.&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UserDebt {
        user_address: String
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "user_debt": {
    "user_address": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type   | Description                        |
| -------------- | ------ | ---------------------------------- |
| `user_address` | String | Address to get debt positions from |

### `UserAssetDebt`

Get user debt position for a specific asset.&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UserAssetDebt { 
        user_address: String, 
        asset: Asset
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "user_asset_debt": {
    "user_address": "terra...", 
    "asset": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type   | Description                             |
| -------------- | ------ | --------------------------------------- |
| `user_address` | String | Address to get debt position for        |
| `asset`        | String | Specific asset to get debt position for |

### `UserCollateral`

Get info about whether or not user is using each asset as collateral.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg { 
    UserCollateral { 
        user_address: String
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "user_collateral": {
    "user_address": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key            |        |                                     |
| -------------- | ------ | ----------------------------------- |
| `user_address` | String | Address to get collateral info from |

### `UserPosition`

Get user position.&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UserPosition {
        user_address: String
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "user_position": {
    "user_address": "terra..."
  }
}
```

{% endtab %}
{% endtabs %}

| Key            | Type   | Description                 |
| -------------- | ------ | --------------------------- |
| `user_address` | String | Address to get position for |

### `ScaledLiquidityAmount`

Get liquidity scaled amount for a given underlying asset amount (i.e: how much maTokens will get minted if the given amount is deposited).

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    ScaledLiquidityAmount {
        asset: Asset, 
        amount: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "scaled_liquidity_amount": {
    "asset": "terra...",
    "amount": 123
  }
}
```

{% endtab %}
{% endtabs %}

| Key      | Type    | Description                               |
| -------- | ------- | ----------------------------------------- |
| `asset`  | String  | Asset to get liquidity scaled amount for  |
| `amount` | Uint128 | Amount to get liquidity scaled amount for |

### `ScaledDebtAmount`

Get equivalent scaled debt for a given underlying asset amount (i.e: how much scaled debt is added if the given amount is borrowed).&#x20;

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    ScaledDebtAmount {
        asset: Asset, 
        amount: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "scaled_debt_amount": {
    "asset": "terra...",
    "amount": 123
  }
}
```

{% endtab %}
{% endtabs %}

| Key      | Type    | Description                              |
| -------- | ------- | ---------------------------------------- |
| `asset`  | String  | Asset to get equivalent scaled debt for  |
| `amount` | Uint128 | Amount to get equivalent scaled debt for |

### `UnderlyingLiquidityAmount`

Get underlying asset amount for a given maToken balance.

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UnderlyingLiquidityAmount {
        ma_token_address: String, 
        amount_scaled: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "underlying_liquidity_amount": {
    "ma_token_address": "terra...",
    "amount_scaled": 123
  }
}
```

{% endtab %}
{% endtabs %}

| Key                | Type    | Description     |
| ------------------ | ------- | --------------- |
| `ma_token_address` | String  | maToken address |
| `amount_scaled`    | Uint128 | Scaled amount   |

### `UnderlyingDebtAmount`

Get underlying debt amount for a given asset and scaled amounts (i.e: How much underlying asset needs to be repaid to cancel a given scaled debt amount stored in state).

{% tabs %}
{% tab title="Rust" %}

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
    UnderlyingDebtAmount {
        asset: Asset, 
        amount_scaled: Uint128
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
  "underlying_liquidity_amount": {
    "asset": "terra...",
    "amount_scaled": 123
  }
}
```

{% endtab %}
{% endtabs %}

| Key             | Type    | Description                      |
| --------------- | ------- | -------------------------------- |
| `asset`         | String  | Asset to get underlying debt for |
| `amount_scaled` | Uint128 | Scaled amount                    |

## Interests and Scaled Amounts

### Scaled Amounts

For debt and deposits (maAsset balances), the protocol needs to store static amounts while still have interest accrue for those amounts. To achieve these, both debt and deposit balances are stored in `scaled amounts`. Any time user's position change by a given asset amount (e.g: User deposits 1000 UST), the scaled amount is computed in order to store it to state with the following formula:

$$
scaledAmount = \frac{underlyingAssetAmount \* SCALING\_FACTOR}{index}
$$

Where `SCALING_FACTOR` (10^6) is a constant factor used to keep decimal precision and `index` is the respective borrow/liquidity index related to the underlying amount that is being computed.

At any point in time, the underlying asset amount can be computed from the scaled amount with:&#x20;

$$
underlyingAssetAmount = \frac{scaledAmount  \* index}{SCALING\_FACTOR}
$$

There is also a rounding operation that takes place in order for the protocol not to lose liquidity due to accumulated rounding errors:

* Scaled and underlying amount operations for liquidity amounts will always be rounded down (in favor of deposit amounts being lower due to rounding errors).
* Scaled and underlying amount operations for borrow amounts will always ceil (in favor of debt amounts being higher due to rounding errors).

### Liquidity and Borrow Index

Interests are applied to ever growing indexes in order to compute accrued interest rate. `borrow_rate` is applied to the `borrow_index` and `liquidity_rate` is applied to `borrow_index`.

Indexes accrue linearly since the last time updated when computed at a specific point in time but are recomputed and stored to state every time utilization rate changes. This means the more user transactions there are, the more interest will approximate compound interest rate.
