# Ensure existing loans are collateralized

## Overview

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FFiSjuFHG83qd3tYDHv2p%2Fimage.png?alt=media&#x26;token=f4b2b130-41e7-44c0-ac24-509ed1c9d54e" alt=""><figcaption></figcaption></figure>

* [x] <mark style="color:orange;">cache</mark>
* [x] <mark style="color:orange;">updateState</mark>
* [x] get user's AToken balance + amount to withdraw
* [x] validateWithdraw: confirm user has sufficient balance and asset isActive
* [x] <mark style="color:orange;">updateInterestRates</mark>
* [x] collateral check
* [x] burn ATokens
* [ ] Ensure existing loans are collateralized

<img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2F37jB8flDgzKTsHwATb39%2Ffile.excalidraw.svg?alt=media&#x26;token=bbfa8950-d188-4b8a-a91d-0ef83c8961e8" alt="" class="gitbook-drawing">

### isBorrowingAny

This function checks if a user has been borrowing **any** asset.

* Takes `UserConfigurationMap` as input, which contains a bitmap of the user's collaterals and borrows.

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FCT0pPX9TqG76etc295xH%2Fimage.png?alt=media&#x26;token=4bfa86b3-3878-40aa-9ab7-eb70ba3bf9d7" alt=""><figcaption></figcaption></figure>

Uses `BORROWING_MASK`, which is a bitmask that isolates the borrowing bits within `data`. `BORROWING_MASK` has a specific pattern of bits, with **alternating `1` and `0`**.

{% code overflow="wrap" fullWidth="false" %}
```solidity
// UserConfiguration.sol
uint256 internal constant BORROWING_MASK = 
0x5555555555555555555555555555555555555555555555555555555555555555;

// 0x55 -> Binary(1010101)
```
{% endcode %}

The function applies this mask to `data` using a bitwise AND operation (&). This effectively keeps only the bits in `data` that correspond to borrowing positions, while setting all other bits to 0.

If the result of the bitwise AND operation between `self.data` and `BORROWING_MASK` is not equal to `0`, it means that at least one bit in the borrowing position is set to `1`. This indicates that the user has been borrowing from at least one reserve.

<details>

<summary>Illustrated Explanation</summary>

To understand how the BORROWING\_MASK works as a bitmask, let's take a closer look at its binary representation:

**BORROWING\_MASK**: `0x5555555555555555555555555555555555555555555555555555555555555555`

In binary: `0101010101010101010101010101010101010101010101010101010101010101`

Each '0' represents a bit that will be set to 0 when the BORROWING\_MASK is applied, and each '1' represents a bit that will be preserved. When the BORROWING\_MASK is applied to the data field using a bitwise AND operation (&), the resulting value will have only the borrowing-related bits preserved, while all other bits will be set to 0.

For example, let's assume the data field contains the following binary representation:

**data**:\
`1111111111111111111111111111111111111111111111111111111111111111`

Applying the `BORROWING_MASK` using a bitwise AND operation:

**`data & BORROWING_MASK`:**

`1111111111111111111111111111111111111111111111111111111111111111 & 0101010101010101010101010101010101010101010101010101010101010101`

\=> **`0101010101010101010101010101010101010101010101010101010101010101`**

The resulting value preserves only the bits in the borrowing positions, while setting all other bits to 0. In this case, the preserved bits represent the borrowing positions, indicating which assets are borrowed by the user.

</details>

To summarize, `BORROWING_MASK` is a bitmask that preserves only the **borrowing-related bits** within the data field. Applying the BORROWING\_MASK using a bitwise AND operation helps identify the borrowed assets by setting all non-borrowing bits to 0 and preserving the borrowing bits.

If the user is borrowing any asset, AND has been using the asset about to be withdrawn as collateral => need to validate HF and LTV.

## Check loans (validate HF and LTV)

* calls on `validateHealthFactor` to return the bool `hasZeroLTVCollateral`

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2Fa7z0OaSjyR1njo1yPuVJ%2Fimage.png?alt=media&#x26;token=e771ddaa-1333-449c-934c-7d658e37da7c" alt=""><figcaption></figcaption></figure>

Etiher one of the following two conditions must be true for this function to not revert:

1. **`!hasZeroLtvCollateral`**: user has a non-zero LTV value across all assets
2. Asset being withdrawn has an LTV of `0`

Condition 1 serves as a sanity check, given that `validateHFAndLtv` is executed in the context that the user `isBorrowingAny` .

### validateHealthFactor

This function is primarily a wrapper around `.calculateUserAccountDataParams`.

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FOgq4WLxNEZHQNkB1Qbo1%2Fimage.png?alt=media&#x26;token=8d53a406-28b5-4de3-abe9-c89ec15f740d" alt=""><figcaption></figcaption></figure>

The require statement ensures that the calculated health factor (after withdrawal) is above the liquidation threshold. If its not, user will be unable to withdraw asset.

## `.calculateUserAccountDataParams`

This function calculates and returns the following user data across all the assets:

* `totalCollateralInBaseCurrency`
* `totalDebtInBaseCurrency`
* `avgLTV`
* `avgLiquidationThreshold`
* `healthFactor`
* `hasZeroLtvCollateral`

<figure><img src="https://1829638638-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0k7YXwFGMFZcsyqkM4q1%2Fuploads%2FGNp2pU2ppbp44dq6KrQq%2Fimage.png?alt=media&#x26;token=301e6fb8-929c-489a-ac62-90091ea4fc39" alt=""><figcaption></figcaption></figure>

See [calculateUserAccountDataParams](../common-functions/calculateuseraccountdata) for the full breakdown explanation.&#x20;
