# Introduction

Hashstack allows users to take under-collateralized loans. The loans can be spent on various dapps like AMMs, Vaults, DEXs allowing you to increase your capital efficiency. The project broadly contains the following stakeholders:

1. Suppliers
2. Borrowers
3. Liquidators

We first discuss about how the deposits and borrows are handled in the system. The system has a provision to spend the loan on pre-configured integrations, which we call as Layer-3 (L3) Integrations. The loans given to users stay within the Open protocol and users have the right to spend these loans on supported integrations via Open.&#x20;

The profit or loss made through spending on these integrations is on the user and Open shall recover the loan anytime by liquidating the collateral if the loan falls below a certain threshold. Any user is allowed a maximum debt of 5x the collateral. This is to ensure proper risk management and protection of user deposits/supplies.


# Permissible CDR

The following documentation outlines a code implementation for a function that calculates the creditworthiness and loan-to-value (LTV) ratio of a borrower based on several input parameters. The code also includes a function to calculate the overall market risk based on three input parameters.

The code implementation consists of two functions: **`calculate_creditworthiness()`** and **`calculate_market_risk()`**. The **`calculate_creditworthiness()`** function assesses the borrower's creditworthiness by considering the user's repayment history, collateral to debt correlation, and the overall market risk. The function returns both the creditworthiness score and the LTV ratio. The **`calculate_market_risk()`** function estimates the general market risk based on the effective asset flow rate, volatility, and price variation, and returns the assessed risk.

The documentation provides additional information about the input parameters used in both functions and their relationship to market risk.

### **Parameters:**

1. **`collateral_debt_correlation`**: This parameter represents the correlation between the value of the collateral and the borrower's debt. In other words, it assesses the likelihood that the value of the collateral will decrease below the borrower's debt level. The lower the correlation, the riskier the loan.
2. **`effective_asset_flow_rate`**: This parameter represents the effective flow rate of assets, which is the rate at which assets can be converted to cash in the market. It evaluates the liquidity of assets and their ability to be sold quickly at a reasonable price. A low effective asset flow rate indicates a riskier market, which is represented as a boolean as of this version.
3. **`volatility`**: This parameter represents the degree of variation of an asset's price over time. It measures the risk of the asset's price fluctuating in the market. Higher volatility indicates a riskier market.
4. **`price_variation`**: This parameter represents an asset's price variation in a given time period. It measures the magnitude of the change in the asset's price. A higher price variation indicates a riskier market.
5. **`wallet_history`**: This parameter represents the user's repayment history. It tracks the status of the borrower's previous loans, indicating their consistency in repaying loans. A good repayment history indicates a lower credit risk for the borrower.

All of these parameters, except for **`wallet_history`**, are market-associated and evaluate the market risk at the time of loan request. Understanding the relationships between these parameters and market risk is critical to assessing the borrower's creditworthiness.

```jsx
def calculate_creditworthiness(collateral_debt_correlation, effective_asset_flow_rate, volatility, price_variation):
    //Step 1: User repayment history
    wallet_history = "A track of loan's status as in success or failed loans" 
    //Consistency of the user's loan repayment justifies the trust in lending the funds
	    // A score from this can be taken with a discounting factor to older status. (Rn + delta*Rn-1 + delta^2*Rn-2 +...)
    // Step 2: Calculate credit risk
    credit_score= score*[collateral_debt_correlation + calculate_market_risk(effective_asset_flow_rate, volatility, price_variation)]/2
    
    // Step 3: Calculate loan-to-value (LTV) ratio
    ltv_ratio = 3 * credit_score
    
    // Step 4: Return creditworthiness score and LTV ratio
    return credit_score, ltv_ratio

def calculate_market_risk(effective_asset_flow_rate, volatility, price_variation):
    // Calculate overall market risk using a weighted average of effective asset flow rate, volatility, and price variation
    weights = [0.4, 0.3, 0.3] // Adjust weights as desired
    market_risk = np.average([effective_asset_flow_rate, volatility, price_variation], weights=weights)
    
    return market_risk
```


# Automated Liquidity Provision

We intended for the entire loan amount to be divided and allocated to the user's preferred liquidity pool. Ideally, there should be virtually nothing left because it complicates the way we record everything. So, if someone takes out a $1000 loan and subsequently selects the USDT: ETH pool, the entire $1,000 must be added as liquidity to this USDT: ETH pool.

Based on the problem statement above, we concluded that the following should provide us with what we seek.

get\_amount\_out(x) = quote(1000 - x) \[JediSwap functions]

Opening this up results in a quadratic equation for x which then needs to be solved.

We’ve referred to the implementation from JediSwap’s Zapper contract \[[Link to the page](https://github.com/mesh-finance/zapper-starknet/blob/initial_poc/contracts/Zapper.cairo)].

The equation must be tested under extreme values so as to validate that the solution doesn’t turn out either negative or complex.

$$(997\*x) / ((reserveIn \* 1000) + (997 \* x)) + x = (1000-x)/reserveIn$$

From the equation, ‘x’ represents the swapped amount, thus defining that x is a non-negative real number.

Let’s generalize the equation:

997 → 99.7% of loan amount as the protocol takes 0.3% as fees

$$(0.997*loan*x) / ((reserveIn \* loan) + (0.997\*loan \* x)) + x = (loan - x)/reserveIn$$

Readjusting the equation to the standard form would give:

$$0.997*loan*x^2 + \[1.997*loan*reserveIn-0.997*loan^2]x - loan^2*reserveIn = 0$$

Here since the ‘c’ is negative, 4ac is always negative thus, it’s safe to say discriminant is non-negative i.e. roots are real.

Given the constraints, the roots won’t have the same sign that is both + or - \[c/a is negative → Roots have opposite signs]

Assumption: loan == 1000

* Case 1: reserveIn == loan

  x = 618.55

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2FtV7mF9VbPcHzJN2PFmm6%2Fimage.png?alt=media&amp;token=1642eb4d-dad7-480a-addf-3b93b5eb37a3" alt=""><figcaption></figcaption></figure>

* Case 2: ReserveIn(10b) >>> loan

  x = 500.75

From a practical relational value from reserveIn, the loan amount has been taken from 0 to reserveIn and represented through GIF.

Here, the **black line shows the loan\_amount, red graph is our equation** and it can be seen that x (at y=0) doesn’t cross loan\_amount.

{% embed url="<https://i.ibb.co/kXxwtNN/Automated-Liquidity-Provision.gif>" %}


# Slippage Control

Slippage is the gap between a trade's expected or requested price and the price at which the trade was executed. It usually happens in markets with high volatility or low liquidity.

**Factors to consider:**

* **Liquidity**: Pools must have enough liquidity to handle the expected trading volume. Pools with higher volume and longer/deep order books tend to have low slippage.
* **Slippage tolerance**: Users with higher tolerance can be willing to trade in pools with low liquidity, but those with low tolerance would prefer a more elevated liquidity pool.
* **Token pairs**: Tokens that are in demand tend to have higher liquidity → lower slippage
* **Price Volatility:** If the token in the pool is highly volatile then it leads to a higher chance of slippage which ends up being a poor user experience.

**Controlling Slippage Threshold:**

Under a practical slippage tolerance, the contract checks the execution price during the trade and breaks/stops the trade in cases where the execution price has deviated beyond the tolerable slippage set. →\[0.5, 3]%

Note: Due to low TVL at the initial phase higher slippage cases are bound to occur thus blocking a trade ultimately results in a dissatisfied user experience which is a trade-off to this approach. Thus, until the TVL of that asset grows to healthy liquidity, larger slippage is authorized as of this version.


# Integrations

Hashstack allows users to spend their loan on supported integrations in a variety of ways like swapping, staking and last but not the least adding liquidity. This list of integrations will only grow along with the growth of the Starknet ecosystem and the birth of new protocols.

While supporting these integrations we also monitor activity on these pools because they introduce a certain level of risk to the system. Protection of the users deposits is paramount so we have certain measures in place to be able to disable user activity on certain pools if it increases the risk taken on by the protocol and likewise only stable pools are currently whitelisted to be used as a part of risk management.

## Adding Liquidity

Of the user actions mentioned above, swapping and staking are fairly simple, but adding liquidity to an AMM pool is not that straightforward. Adding liquidity can be roughly broken down into two scenarios -

1. Loan market A is adding liquidity to pool BC: For this scenario, there is no common market between loan market A and the pool of markets B and C. Therefore, the first step is to swap A to either B or C, which is done to achieve the best result/route.

The liquidity split of B and C to the pool BC while ensuring the least/no amount of loan is left over is done through simplifying the equation -

$$getAmountOut(x) = quote(loan - x);$$

Here `get_amount_out(x)` and `quote(x)` are common view functions used in AMM’s which operate on the reserves of the pool and return the values. The simplification of the above equation is used to calculate the liquidity split for the best performance. It will resolve to a quadratic equation in x, which is then solved by calculating the determinant.


# Proxy/Upgrade Structure

Given the nature of Hashstack's integrations, there was a requirement to have an upgrade structure robust enough to handle additions of integrations over time and the addition of new functionality frequently, while maintaining previous user balances without the need for migration. Therefore, the Open protocol is designed using the Modular Smart Contract standard, which closely mirrors the Diamond standard outlined in <https://eips.ethereum.org/EIPS/eip-2535>.&#x20;

There are two diamonds: the Open protocol diamond, which contains core Open functionality, and the L3-Integrations diamond, which contains all integration functionality, allowing us to independently add integrations or new functionality in a modular and seamless fashion.


# Mainnet Deployed Contracts

List of all contracts related to the tokens for the Mainnet V1.

| Name | rToken                                                                                                                                                               | dToken                                                                                                                                                               | Address                                                                                                                                                              |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BTC  | [0x1320a9910e78afc18be65e4080b51ecc0ee5c0a8b6cc7ef4e685e02b50e57ef](https://starkscan.co/contract/0x1320a9910e78afc18be65e4080b51ecc0ee5c0a8b6cc7ef4e685e02b50e57ef) | [0x2614c784267d2026042ab98588f90efbffaade8982567e93530db4ed41201cf](https://starkscan.co/contract/0x2614c784267d2026042ab98588f90efbffaade8982567e93530db4ed41201cf) | [0x3fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac](https://starkscan.co/contract/0x3fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac) |
| ETH  | [0x436d8d078de345c11493bd91512eae60cd2713e05bcaa0bb9f0cba90358c6e](https://starkscan.co/contract/0x436d8d078de345c11493bd91512eae60cd2713e05bcaa0bb9f0cba90358c6e)   | [0x1ef7f9f8bf01678dc6d27e2c26fb7e8eac3812a24752e6a1d6a49d153bec9f3](https://starkscan.co/contract/0x1ef7f9f8bf01678dc6d27e2c26fb7e8eac3812a24752e6a1d6a49d153bec9f3) | [0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7](https://starkscan.co/contract/0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7) |
| USDT | [0x5fa6cc6185eab4b0264a4134e2d4e74be11205351c7c91196cb27d5d97f8d21](https://starkscan.co/contract/0x5fa6cc6185eab4b0264a4134e2d4e74be11205351c7c91196cb27d5d97f8d21) | [0x12b8185e237dd0340340faeb3351dbe53f8a42f5a9bf974ddf90ced56e301c7](https://starkscan.co/contract/0x12b8185e237dd0340340faeb3351dbe53f8a42f5a9bf974ddf90ced56e301c7) | [0x68f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8](https://starkscan.co/contract/0x68f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8) |
| USDC | [0x3bcecd40212e9b91d92bbe25bb3643ad93f0d230d93237c675f46fac5187e8c](https://starkscan.co/contract/0x3bcecd40212e9b91d92bbe25bb3643ad93f0d230d93237c675f46fac5187e8c) | [0x21d8d8519f5464ec63c6b9a80a5229c5ddeed57ecded4c8a9dfc34e31b49990](https://starkscan.co/contract/0x21d8d8519f5464ec63c6b9a80a5229c5ddeed57ecded4c8a9dfc34e31b49990) | [0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8](https://starkscan.co/contract/0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8) |
| DAI  | [0x19c981ec23aa9cbac1cc1eb7f92cf09ea2816db9cbd932e251c86a2e8fb725f](https://starkscan.co/contract/0x19c981ec23aa9cbac1cc1eb7f92cf09ea2816db9cbd932e251c86a2e8fb725f) | [0x7eeed99c095f83716e465e2c52a3ec8f47b323041ddc4f97778ac0393b7f358](https://starkscan.co/contract/0x7eeed99c095f83716e465e2c52a3ec8f47b323041ddc4f97778ac0393b7f358) | [0x0da114221cb83fa859dbdb4c44beeaa0bb37c7537ad5ae66fe5e0efd20e6eb3](https://starkscan.co/contract/0x0da114221cb83fa859dbdb4c44beeaa0bb37c7537ad5ae66fe5e0efd20e6eb3) |

### Peripherals

* Staking Address: [`0x5950cbbb7dbdb2303671515bb9e41ca0bf8937dc5ba929eebd276a3db3f854`](https://starkscan.co/contract/0x5950cbbb7dbdb2303671515bb9e41ca0bf8937dc5ba929eebd276a3db3f854)
* Diamond Address: [`0x1b862c518939339b950d0d21a3d4cc8ead102d6270850ac8544636e558fab68`](https://starkscan.co/contract/0x1b862c518939339b950d0d21a3d4cc8ead102d6270850ac8544636e558fab68)
* L3 Diamond Address: [`0x5bc2d5f739fd82c176fc420b7acdbbf856d35597bdc575338664e84379245df`](https://starkscan.co/contract/0x5bc2d5f739fd82c176fc420b7acdbbf856d35597bdc575338664e84379245df)


# Frontend Tech Stack

#### Technologies Used

* Next js (<https://nextjs.org/docs>)
* Typescript (<https://www.typescriptlang.org/docs/>)
* Testing- Jest (<https://jestjs.io/docs/getting-started>)
* Redux Toolkit (<https://redux-toolkit.js.org/introduction/getting-started>)
* Apex charts (<https://apexcharts.com/docs/installation/>)

#### Ui Framework and Styling

* Chakra UI (<https://chakra-ui.com/docs/components>)
* Chakra UI is a popular open-source UI component library for React applications. It provides a set of customizable and accessible components that can significantly speed up the frontend development process.
* Custom styling using native css for some components.

<img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2F4WgJxHaK9dAHkXgnQa8S%2Fimage.png?alt=media&amp;token=0961524d-2ca3-4443-bf72-0750c44eeb68" alt="" data-size="original">

#### State Management

* Redux (<https://redux-toolkit.js.org/introduction/getting-started>)
* Implemented Redux for comprehensive state management across the project, ensuring seamless integration and facilitation of global state changes, enhancing overall implementation and user experience.

#### Animation and Motion

* Framer Motion
* Utilized Framer Motion to elevate user experience by seamlessly integrating animations with button clicks, enhancing visual engagement during transactions.

#### Toast Notifications

* React Toastify (<https://fkhadra.github.io/react-toastify/introduction>)
* Toasts enhance the user experience by providing concise updates on transaction outcomes, ensuring users are informed about successes and failures without disrupting their workflow. These unobtrusive notifications promote user satisfaction and informed decision-making.

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2FOtv5KwAXaKMdWANDiQb8%2Fimage.png?alt=media&amp;token=704d0615-fe2e-4373-b104-0779dc21c201" alt=""><figcaption><p>failure toast</p></figcaption></figure>

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2Fp4jNUkoNNCZ1P4B48DeD%2Fimage.png?alt=media&amp;token=5631dfa5-47c5-45a9-b6b3-2ff478ce89ba" alt=""><figcaption></figcaption></figure>

#### Web3 Interactions

* Starknet react hooks (<https://apibara.github.io/starknet-react/>)
* Leveraged Starknet React hooks to seamlessly interface with smart contracts, enabling both data retrieval and blockchain data recording through intuitive function calls. Streamlining interactions, it facilitated efficient data management on the blockchain.

#### Coding Standards

* Consistent Naming
* Modularization
* Formatting
* Typescript (<https://www.typescriptlang.org/docs/>)
* Linting
* Version Control
* We used TypeScript as our primary programming language for frontend development. TypeScript extends JavaScript by adding static types, enabling us to catch errors and enhance code quality during development.

#### Future Considerations

* Optimized load times and performance management by streamlining library usage, effectively reducing the number of dependencies.


# Introduction

The protocol allows anyone to be a supplier. These supplied funds are then used to issue loans for the borrower. We make use of the ERC 4626 standard for our supply vault. When a user deposits funds to the corresponding vault, rTokens of that particular asset (Representational tokens) are minted to the user. These rTokens represent user shares in the deposit vault. We follow a similar logic in borrow token contract, though it is not designed to follow the 4626 standard (as it is not a vault). User will receive dTokens (Debt tokens) for borrowing and these tokens represent the share of total debt owed by the user to the protocol.

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2FTwfgFp9NW2JaDNI1Tdo2%2Fv1-supply_deposit.png?alt=media&amp;token=18fc5280-de20-4ebb-b8f6-3e4191c46c87" alt=""><figcaption><p>Fig. 1 - Interaction between supply and borrow contracts</p></figcaption></figure>

The above diagrams describe the basic actions a supplier and borrow can do. It shows how to borrow and supply contracts interact with each other.


# Supply

When a user supplies funds to the protocol, they receive rTokens. We use the following formula (as per EIP 4626) to calculate the number of tokens minted to the user.

$$
rTokens\_{new} = \frac{Asset\_{new} \cdot rTokens\_{total}}{Asset\_{total}}
$$

The formula uses existing total rTokens supply and Total asset supply to decide the quantity of rTokens to be minted as per the user deposit.

$$
Asset\_{total} = Asset.balanceOf(contract) + Assets\_{lent} + Interest\_{accrued}
$$

```jsx
// Definitions
Assets_lent => Assets borrowed by borrower contract to issue loans to the user
Interest_accrued => Interest recievable by suppliers since last update
```

The contract exposes the following features for user and open contracts to interact with:

1. **User:** Technically, a user can usually perform 3 main actions with supplier contract: Deposit, Withdraw & Transfer. User can further use the received rTokens as collateral to borrow or stake to earn higher yield.

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2FXHidU7aeYhCDMHaS4oJu%2Fimage.png?alt=media&amp;token=de279616-e186-4378-bf68-72218508ad10" alt=""><figcaption><p>Fig. 2 - Supply use-cases</p></figcaption></figure>

2. **Open:** The supply contract provides special privileges to the Open contract to allow it for some book-keeping. These options include:

* Accrue the interest
* Lock/unlock supply - to prevent the transfer of collateralised supply
* Transfer & withdraw supplied funds on the users behalf - to liquidate the loan
* Borrow and repay - to utilise funds to issue & close loans


# Borrow

Borrow contracts follows ERC20 standard while using some mathematics of EIP 4626 to maintain the relationship between total debt and dTokens issued. dTokens are debt tokens that are issues when a user takes a loan and burnt on repayment/liquidation of loan. dTokens represent the share of total debt issued by the contract. They help determine the amount to be paid by user during repayment.


# Use Cases

We currently provide the following options to allow users to spend the loans:

1. Leveraged Swap: User can swap the borrowed token to a supported token on popular AMMs, effectively shorting the loan token and taking a long on swapped token.
2. Leveraged Liquidity mining: Use loan to provide liquidity to your favourite LP on popular AMMs.
3. Yield aggregators: Use the loan to earn yield on yield aggregators, increasing your returns by 5x.
4. Leveraged trading: Use the loan amount to do leveraged trading on DEXs.

<figure><img src="https://84867213-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEVOQHsfy83WcYZwHX4bB%2Fuploads%2Fiy6AXMLqYsRigVuXJC1U%2Fimage.png?alt=media&amp;token=dd89f468-2398-461d-b514-36eb5a3bfa29" alt=""><figcaption><p>Fig. 3 - Borrow use-cases</p></figcaption></figure>


# Isolated margin

All loans issued on hashstack are isolated margin loans. User has to choose the supply market along with their quantity to be used as collateral. Protocol then verifies the rTokens quantity to assure enough supply is pledged to use as collateral. These pledged rTokens cannot be transferred till loan is closed. (We call this as locking rTokens). Only borrow contracts can lock/unlock the rTokens.


# Debt management

Each borrow contract maintains the tokens associated with its lending activity. Borrow contracts have special rights to interact with supply contracts to borrow assets to issue loans, liquidate collateral to close loan. The borrow contract is liable to return the funds to respective supply vault along with interest on loan closure and free up any remaining collateral.

To explain the details, assume two rTokens - 1) rETH 2) rUSDC. and a borrow token dUSDC.

Assume users wants to borrow 300 USDC using 1 ETH as collateral (1 ETH = 100 USDC).

1. On Borrow: dUSDC contract will request 300 USDC from rUSDC contract. rUSDC contract shall use its supply reserves to full-fill the requests. rUSDC uses `lent_assets` variable to track the borrowing it has done. dUSDC shall also call the rETH contract requesting it to lock users 1rETH as collateral.

2. **On Repay:** This has 2 cases:

   a) Loan has sufficient funds to close the loan without liquidating any collateral. dUSDC contract shall repay the loan including interest owned by the user to the protocol (fees) and rUSDC contract. Any remaining loan funds are sent back to the user. And finally, dUSDC will call rETH contract requesting it to unlock the users 1rETH.

   b) Current loan amount is insufficient to close the loan by itself. This could be because of the extra interest accrued on the loan and any losses made be user when spending the loan. Hashstack provides two options to deal with this:

   * Repay deficit amount: Allow user to pay the deficit amount. If the total debt during repayment is 310 USDC, and protocol only has 300 USDC of the loan, user can send the remaining 10 USDC to avoid collateral liquidation. In this case, entire collateral is unlocked
   * Self liquidate: User can use this option to request the protocol to use their collateral to close the loan. In this protocol will roughly sell 0.1 ETH worth of user’s rTokens (for 10 USDC, assuming no price change) and close the loan. Finally, it will unlock the remaining 0.9 ETH worth rETH of the user.

3. **On Spend:** Assume the user decides to spend the loan on an AMM to buy ETH. This results in shorting USDC and longing ETH. With about 230 USDC in current loan amount, user will receive roughly 2.3 ETH.

<pre class="language-rust"><code class="lang-rust"><strong>actual_debt: 300 USDC + interest
</strong>current_loan_amount: 2.3 ETH
current_collteral: 1 ETH
</code></pre>

We call these as spent assets and these assets remain with the respective dToken contracts based on the loans they handle.


# Health factor

We compare the total current debt of the token with underlying loans current value and collateral(s) to determine the health.

$$
Hf = \frac{C\_{cv} + LA\_{cv}}{L\_{net}}
$$

where,

$$Hf =$$ Health factor

$$C\_{cv} =$$ Collateral current value in USD

$$LA\_{cv} =$$ Loan account current value in USD

$$L\_{net} =$$ Net liabilities (Original loan + interest) in USD

Note: For on-chain computations, we use USDT as base value to compute values.

Health is monitored at two levels:

1. dToken level: Determines the total health of the protocol for this asset
2. user loan level: Determines health of a user’s individual loan

### **dToken health:**

$$L\_{net} =$$ total value of the debt issued by the contract across the protocol

&#x20;$$C\_{cv} = \Sigma\_{1}^{n} C\_{icv},$$ n is the total number of supported collaterals, $$C\_{icv}$$ is the net value of the ith collateral locked.

$$LA\_{cv}$$ unspent loan amounts + Sum (spent loan amounts)

### **User loan health:**

For the above loan discussed, the health factor can be computed as below:

1. **Before partial withdrawl**

   * $$C\_{cv} =$$ 1 ETH \* 100 = 100
   * $$LA\_{cv} =$$ 300 USDC = 300
   * Assuming an interest of 2 USDC accrued,

     $$ $L\_{net} =$ $$ 300 + 2 USDC = 302

So, Health factor $$(Hf) =$$ (100 + 300)/302 = **1.32**

***

2. **Post spend**

$$LA\_{cv}$$ = 3 ETH x $100 = $300

So, Health factor $$(Hf) =$$ (100 + 300)/302 = **1.32**

**Health factor determines if a loan can be liquidated. Read Liquidations for more info.**


# Hashstack Layer 3 Integration

## **Introduction**

The Hashstack Layer 3 Integration team aims to actively facilitate the integration of other decentralized finance (DeFi) protocols with Hashstack. Our primary goal is to foster collaboration and create a seamless integration experience that benefits the broader DeFi ecosystem. This document provides an overview of our objectives and the processes involved in achieving successful protocol integrations.

### Objective

The main objective of Hashstack Layer 3 Integration Community Development is to enable the smooth integration of various DeFi protocols with Hashstack. This integration can be accomplished in two ways:&#x20;

1. Proactive Integration: We actively seek out potential integration opportunities with other DeFi protocols. By identifying compatible projects, we can initiate discussions and collaborations to facilitate the integration process.
2. Proposal and Issue Resolution: We provide a platform for other protocols to propose and address any issues related to integrating their protocol with Hashstack. This ensures that all concerns and requirements are effectively communicated and resolved in a timely manner.

####

### Benefits

By fostering integration with Hashstack, both Hashstack and the participating protocols can benefit from the following:

1. Enhanced Functionality: Integration with Hashstack Layer 3 allows protocols to leverage their capabilities and expand their offerings. This enhances the overall functionality and user experience of the integrated protocols.
2. Expanded User Base: Through integration, protocols gain access to Hashstack's user base, which can significantly increase their reach and adoption. This opens up new opportunities for growth and exposure within the DeFi community.
3. Collaborative Ecosystem: Integration promotes collaboration and knowledge sharing among protocols, fostering a vibrant and interconnected DeFi ecosystem. By working together, we can collectively advance the industry and drive innovation.

####

### **Integration Process**

The integration process involves the following steps:

1. **Initial Assessment**: The Integration team evaluates potential integration opportunities based on compatibility, strategic alignment, and technical feasibility. This assessment helps identify suitable protocols for integration.
2. **Collaboration and Proposal**: Once a potential integration opportunity is identified, the team collaborates with the protocol's development team to discuss the integration scope, requirements, and potential benefits. The protocol's team submits a proposal outlining the integration plan.
3. **Technical Integration**: Upon agreement, the technical integration process begins. This involves aligning the protocols' smart contract architectures, data structures, and API compatibility. Developers from both sides work closely to ensure a seamless integration that adheres to best practices and security standards.
4. **Testing and Quality Assurance**: Rigorous testing and quality assurance procedures are conducted to ensure the integrated protocols function as intended. This includes comprehensive unit testing, integration testing, and stress testing to identify and address any potential issues or vulnerabilities.
5. **Deployment and Rollout**: Once the integration passes all testing and quality assurance stages, it is deployed to a test network or staging environment for final verification. After successful verification, the integration is rolled out to the main network, making it available to users.
6. **Ongoing Support and Maintenance**: Post-integration, the Hashstack Layer 3 Integration team provides ongoing support and maintenance to address any issues or improvements that arise. Regular communication and collaboration between the integrated protocols continue to foster successful integration.
7. **Code Contribution**: If you are a developer looking to contribute to the integration process, create an issue on the project's GitHub repository. In the issue, propose your approach and plan of action for the integration. This helps initiate a discussion and ensures transparency in the development process.
8. **Protocols Requesting Integration**: If you represent a protocol and wish to integrate with Hashstack, create an issue on the Hashstack GitHub repository, outlining your integration request and providing the necessary details. This initiates the discussion and collaboration process with the Integration team.

####

### Additional Information for developers

* **Understanding Development Dependencies:** It's important to note that the Hashstack Layer 3 repository has dependencies on Hashstack V1-Core, which is currently a private repository at the time of this writing. To contribute code, developers are requested to reach out to the Hashstack team either by mentioning it in the GitHub issue or through the official Discord channel.
* **Access to V1-Core Repository**: Once you have expressed your interest in contributing code, the Hashstack team will provide access to the V1-Core repository. This access allows you to understand and work with the necessary dependencies required for the integration.
* **Understanding the Project Structure**:
  1. Before creating an issue, it's recommended to have a good understanding of the overall structure and architecture of the Hashstack Layer 3 Integration project.
  2. Start by reading the README file on the repository's main page. The README provides an overview of the project, its purpose, and the key components involved.
  3. Familiarize yourself with the project's documentation, including any developer guides or technical specifications available.
  4. All the test cases are written with Protostar and are in V1-Core.

####

### **Conclusion**

Hashstack Layer 3 Integration team is committed to facilitating seamless integration between Hashstack and other DeFi protocols. By leveraging collaboration and providing a platform for proposal and issue resolution, we aim to create an interconnected DeFi ecosystem that benefits all participants. We encourage protocol developers to explore integration opportunities with Hashstack and work together to push the boundaries of decentralized finance.


# Creating Proposals on Github

How to create an Issue in github?

This guide will walk you through the process of creating an issue on GitHub. By following these steps, you can effectively propose an integration of another DeFi protocol on the Hashstack's Layer 3.

#### **Step 1: Access the Hashstack Layer 3 Integration** [**GitHub Repository**](https://github.com/0xHashstack/V1-L3)

1. Open your web browser and navigate to the Hashstack Layer 3 Integration GitHub repository.
2. Ensure that you are logged into your GitHub account. If you don't have an account, create one by following the instructions on GitHub's website.

#### **Step 2: Navigate to the "Issues" Section**

1. On the repository page, locate the navigation menu at the top of the page.
2. Click on the "Issues" tab, which will take you to the issues section of the repository.

#### **Step 3: Create a New Issue**

1. On the issues page, locate the "New Issue" button and click on it.
2. You will be presented with a form to create a new issue.

#### **Step 4: Provide Relevant Details**

1. In the title field, enter a concise and descriptive title for your integration proposal. For example, "Proposal: Integration of \[Protocol Name] with Hashstack Layer 3."
2. In the description field, provide a clear and detailed explanation of the integration proposal.
3. Start by introducing the protocol you are proposing to integrate and provide a brief overview of its features and benefits.
4. Explain how the integration with Hashstack Layer 3 can enhance both protocols and the broader DeFi ecosystem.
5. Outline the technical requirements, such as smart contract compatibility, data structure alignment, or API integration.
6. Discuss any potential challenges or considerations that need to be addressed during the integration process.
7. Provide any relevant links or resources that support your proposal, such as the protocol's documentation or GitHub repository.

#### **Step 5: Add Labels and Assignees (if applicable)**

1. Labels help categorize and organize issues. If there are predefined labels available, choose the most appropriate one(s) for your integration proposal.
2. If there are specific team members or contributors you want to assign to the issue, you can use the "Assignees" field to assign them. However, this step is optional.

#### **Step 6: Preview and Submit**

1. Before submitting your issue, use the preview tab to review your description and ensure all the necessary details are included.
2. Once you are satisfied with the content, click the "Submit new issue" button to create the issue.

#### **Step 7: Engage in Discussion**

1. After submitting the issue, other contributors, team members, or community members may engage in the discussion.
2. Stay engaged in the conversation by responding to comments, providing clarifications, or addressing any questions or concerns raised.

Congratulations! You have successfully created an issue on GitHub proposing the integration of another DeFi protocol with the Hashstack Layer 3 Integration project. This enables you to actively participate in the development process, foster collaboration, and contribute to the growth of the DeFi ecosystem. Remember to check back periodically for updates and respond to any additional inquiries related to your issue.&#x20;

Your proposal helps drive innovation and the seamless integration of protocols within Hashstack!


