Skip to content

Commit

Permalink
resolving conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiohild committed Feb 9, 2024
2 parents 040443e + 0fa33c3 commit 5746f0b
Show file tree
Hide file tree
Showing 84 changed files with 1,530 additions and 1,217 deletions.
6 changes: 3 additions & 3 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
Copyright (C) 2017 DappHub, LLC
Copyright (C) 2017 DappHub, LLC
Copyright (C) 2018 Rain <rainbreak@riseup.net>
Copyright (C) 2018 Lev Livnev <lev@liv.nev.org.uk>
Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
Copyright (C) 2020 Reflexer Labs, INC.
Copyright (C) 2015-2020 DappHub, LLC
Copyright (C) 2023 Wonderland
Copyright (C) 2015-2020 DappHub, LLC
Copyright (C) 2023 Reflexer Labs, INC.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
Expand Down
38 changes: 38 additions & 0 deletions docs/src/detailed/auctions/dah.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Debt Auction House

See [DebtAuctionHouse.sol](/src/contracts/DebtAuctionHouse.sol/contract.DebtAuctionHouse.html) for more details.

## 1. Introduction

The Debt Auction House contract plays a crucial role in the protocol by managing and auctioning off bad debt. To achieve this, the contract mints protocol tokens, which are auctioned off to users in exchange for system coins. These system coins are then used to annihilate the corresponding bad debt from the system.

The Debt Auction House utilizes a descending bidding model. In this model, a predetermined amount of debt is up for auction. Participants bid by specifying how many protocol tokens they are willing to accept in exchange for taking on this debt. As the auction progresses, the number of protocol tokens a bidder is willing to accept decreases, leading to a more favorable exchange rate for the protocol.

This system ensures that bad debts are efficiently cleared from the protocol, while also incentivizing participants to compete for the most favorable exchange rates.

## 2. Contract Details

### Key Methods:

**Public**

- `restartAuction`: Allows for the resumption of an expired auction that has received no bids. This restarts the auction and increases the initial quantity of protocol tokens to be minted as an incentive for participation.
- `decreaseSoldAmount`: Enables users to participate in the auction by bidding. System coins are transferred during this operation.
- `settleAuction`: Finalizes an auction, distributing the protocol tokens to the winning bidder.
- `terminateAuctionPrematurely`: Ends an auction before its scheduled completion. This method creates an unbacked debt entry in the Accounting Engine and returns the system coins to the highest bidder. Note that this action can only be performed when the contract is disabled.

**Authorized**

- `startAuction`: Initiates a new debt auction.

### Contract Parameters:

- **Accounting Engine**: The address of the Accounting Engine contract that handles the system's financial records.

These methods and parameters provide a comprehensive control structure for managing bad debt through auctions, balancing both protocol and user interests.

## 3. Key Mechanisms & Concepts

## 4. Gotchas

## 5. Failure Modes
44 changes: 44 additions & 0 deletions docs/src/detailed/intro/protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# HAI Protocol 101

## HAI Framework Mechanics

### What is HAI?

- **Low-Cost**: The HAI protocol is deployed on the Optimism network, offering significantly low gas fees for transactions.
- **Dollar-Denominated**: Both the system coin and the collaterals are denominated in US Dollar.
- **Collateral-Backed**: A diverse basket of collateral types backs the minting of the system coin.
- **Control-Pegged**: A PID controller dynamically adjusts the funding rate to balance value transfer between minters (debtors) and holders (creditors).
- **Settleable**: The system can undergo a Global Settlement, during which all debts are squared and HAI holders can redeem tokens for a share of the collateral pool, regardless of whether they have outstanding debts.

### Glossary

#### Units of Measurement

- `WEI`: The base unit for raw ERC20 amounts.
- `WAD`: A unit with **18 decimal places**, used for representing balances.
- `RAY`: A unit with **27 decimal places**, utilized for rate computations.
- `RAD`: A unit with **45 decimal places**, employed for calculating owed amounts.
> **Note**: The [Math Library](/src/libraries/Math.sol/library.Math.html) handles all unit multiplications and divisions.
#### Tokens

- `systemCoin`: The ERC20 stablecoin issued by HAI.
- `protocolToken`: The ERC20 governance token, used for system parameter voting and participating in debt/surplus auctions.
- `collateral`: Any ERC20 token that serves as collateral, enhancing the corresponding `cType` balance.

#### Key Concepts

- `cType`: Represents a unique identifier for a collateral type within the HAI system.
- `COIN`: An internal balance of system coins convertible to `systemCoin` on a `1:1` basis.
- `DEBT`: An internal ledger entry representing unbacked debt, erasable with `COIN` on a `1:1` basis.
- `SAFE`: A vault-like contract holding collateral and generating `COINs`, which may also accrue `DEBT`.
- `lockedCollateral`: The collateral amount held within a `SAFE`.
- `generatedDebt`: The debt incurred by a `SAFE` during the `COIN` generation process. Note that it does **NOT** correlate directly to the amount of `COINs` generated.
- **Liquidation**: A process triggered for under-collateralized SAFEs, wherein their `generatedDebt` is moved to the system's `DEBT` and collateral is seized for auction to cancel out the `DEBT`.
- `redemptionPrice`: The internal price at which system coins can be exchanged for collateral.
- `targetPrice`: A reference price utilized to adjust the `redemptionPrice`, often aligned with market price.
- `redemptionRate`: Governs how the `redemptionPrice` changes over time, essentially functioning as the system's funding rate.
- `stabilityFee`: A separate interest rate, unconnected to the `redemptionRate`, applied to user debts and collected by the system.
- `accumulatedRate`: Reflects the compounded `stabilityFee` applied to a `cType`, determining the relationship between `generatedDebt` and the `COINs` produced.

This guide aims to provide a comprehensive understanding of HAI's framework and its intricacies. Armed with this knowledge, you'll be better equipped to interact with the protocol effectively.
98 changes: 98 additions & 0 deletions docs/src/detailed/modules/acc_engine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Accounting Engine

See [AccountingEngine.sol](/src/contracts/AccountingEngine.sol/contract.AccountingEngine.html) for more details.

## 1. Introduction

The Accounting Engine serves as the system's financial management hub, overseeing tasks such as:

- Tracking system surplus and deficit.
- Managing system debt through auctions.
- Dealing with system surplus via auctions or transfers.
- Accepting COINs (for instance, from auctions) and using them to offset DEBT.

## 2. Contract Details

### Key Methods:

**Public**

- `popDebtFromQueue`: Removes a certain amount of debt from the time-sensitive queue after the `popDebtDelay` duration has elapsed, for either settlement or auction.
- `settleDebt`: Utilizes coin balance to settle debt.
- `cancelAuctionedDebtWithSurplus`: Utilizes coins to settle debt that's in the queue.
- `auctionDebt`: Triggers an auction to liquidate portions of unsettled debt.
- `auctionSurplus`: Triggers an auction to liquidate surplus once all debt has been settled.
- `transferExtraSurplus`: Allocates (instead of auctioning it) excess surplus following debt settlement.
- `transferPostSettlementSurplus`: Allocates all remaining surplus when a Global Settlement event occurs.

**Authorized**

- `pushDebtToQueue`: Adds a specified amount of debt to a time-sensitive queue.
- `disableContract`: Deactivates both Debt and Surplus Auction Houses, clears as much debt as possible, and transfers (after `disableCooldown` delay) any leftover surplus to a designated drain address.

### Required Authorities:

- **LiquidationEngine**: needs authorization to call `pushDebtToQueue`.
- **Debt Auction House**: needs authorization to call `cancelAuctionedDebtWithSurplus`.
- **Surplus Auction House**: needs approval to modify the contract's state in the SAFE Engine.
- **Global Settlement**: needs authorization to call `disableContract`.

### Contract Parameters:

**Global**

- **SAFE Engine**: Holds the coin and debt balance, is called to settle debt.
- **Surplus Auction House**: Is called to start surplus auctions.
- **Debt Auction House**: Is called to start debt auctions.
- `postSettlementSurplusDrain`: Address to which surplus is sent following Global Settlement.
- `surplusIsTransferred`: Whether the surplus should be either auctioned off or transferred.
- `surplusDelay`: Time lag before the surplus becomes eligible for either auction or transfer.
- `popDebtDelay`: Time interval after which debt can be popped from the time-sensitive queue.
- `disableCooldown`: The waiting period following Global Settlement, after which any remaining surplus should be transferred.
- `surplusAmount`: Amount of surplus eligible for auction or transfer during each operation.
- `surplusBuffer`: Minimum surplus reserve to be maintained in the contract following an auction or transfer.
- `debtAuctionMintedTokens`: Initial quantity of Protocol Tokens offered for minting in debt auctions.
- `debtAuctionBidSize`: Chunk of debt that can be offered in each individual debt auction.

## 3. Key Mechanisms & Concepts

### Queued Debt, On Auction Debt & Unqueued Unauctioned Debt

Within the SAFE Engine's scope, the Accounting Engine maintains a single debt balance associated with the contract address. This balance is the summation of three components: the queued debt, representing debt in line for auctioning; the unqueued debt, which is currently being auctioned; and the remaining debt not undergoing auction at the moment.

The unqueued-unauctioned debt can be calculated as follows:

```
unqueuedUnauctionedDebt = debtBalance - queuedDebt - onAuctionDebt
```

Once the `unqueuedUnauctionedDebt` debt reaches the specified `debtAuctionBidSize` threshold and the cooldown period elapses, a debt auction is initiated. During this process, the overall debt of the contract remains unchanged, but the `onAuctionDebt` metric increases as the debt enters the auction phase. Simultaneously, the calculation for `unqueuedUnauctionedDebt` decreases as the debt undergoing auction is accounted for.

## 4. Gotchas

### Unqueued Unauctioned Debt underflow

The `queuedDebt` is modified through the `pushDebtToQueue` (authorized) and `popDebtFromQueue` (public) methods. They don't exclusively mirror the `debtBalance` recorded in the SAFE Engine. If an authorized contract uses `pushDebtToQueue` without transferring debt to the Accounting Engine, it could lead to an underflow issue (if `queuedDebt` exceeds `debtBalance`). This situation could potentially disrupt the contract's ability to auction debt as the `unqueuedUnauctionedDebt` calculation might underflow and revert.

## 5. Failure Modes

### Parameters misconfiguration

- High `surplusDelay` slows surplus actions.
- Low `surplusDelay` rushes surplus auctions.
- High `popDebtDelay` delays debt auctions.
- Low `popDebtDelay` risks double debt coverage.
- High `surplusAmount` risks unfilled surplus auctions.
- Low `surplusAmount` hampers surplus actions.
- High `surplusBuffer` blocks surplus auctions.
- Low `surplusBuffer` risks uncovered new debt.
- High `debtAuctionMintedTokens` dilutes protocol tokens.
- Low `debtAuctionMintedTokens` risks failed debt auctions.
- High `debtAuctionBidSize` risks unfilled debt auctions.
- Low `debtAuctionBidSize` slows debt auctions.
- Low `shutdownCooldown` risks premature surplus moves.
- High `shutdownCooldown` delays post-shutdown surplus actions.

### Post Settlement Surplus Drain misconfiguration

The `postSettlementSurplusDrain` address should be configured after the system is deployed. It's permissible to leave it unset, but doing so comes with implications: if Global Settlement is activated while this address is not specified, any surplus remaining after the settlement won't be drained. Instead, this surplus can only be used for debt elimination. It's worth noting that once Global Settlement is triggered, the address for `postSettlementSurplusDrain` becomes immutable and can't be changed.
98 changes: 98 additions & 0 deletions docs/src/detailed/modules/liq_engine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Liquidation Engine

See [LiquidationEngine.sol](/src/contracts/LiquidationEngine.sol/contract.LiquidationEngine.html) for more details.

## 1. Introduction

The Liquidation Engine is the component responsible for managing the liquidation processes of SAFEs. Its primary duties include:

- Determining the liquidation status of a SAFE.
- Initiating a SAFE Saviour action to enhance the SAFE's financial health, if applicable.
- Assessing the amount of collateral required to be confiscated from a SAFE to offset its debt.
- Activating the process to seize collateral from a SAFE.
- Initiating collateral auctions.

## 2. Contract Details

### Key Functions:

**Public**

- `liquidateSAFE`: Evaluates the condition of a SAFE and commences the liquidation process if the SAFE is eligible for liquidation (and if SAFE Saviour intervention fails).

**Permissioned**

- `protectSAFE`: Selects a SAFE Saviour to defend a SAFE against liquidation.

**Authorized**

- `connectSAFESaviour`: Permits a SAFE Saviour contract to associate with a SAFE for the purpose of preventing its liquidation.
- `disconnectSAFESaviour`: Revokes permission for a SAFE Saviour contract to be linked to SAFEs.
- `removeCoinsFromAuction`: Adjusts the accounted amount of coins that are currently under auction.

### Required Authorities:

- **Collateral Auction Houses**: need authorization to call `removeCoinsFromAuction`.
- **Global Settlement**: needs authorization to call `disableContract` (and block further liquidations).

### Contract Parameters:

**Global**

- **SAFE Engine**: Holds the SAFE state, is called to confiscate the SAFE collateral and debt.
- **Accounting Engine**: The confiscated debt is transferred to the Accounting Engine balance, and pushed to its queue to be auctioned.
- `onAuctionSystemCoinLimit`: Maximum amount of system coins that can be simultaneously auctioned.

**Per Collateral Type**

- **Collateral Auction House**: Is called to start collateral auctions.
- `liquidationPenalty`: Penalty applied to the debt of the SAFE that is being liquidated. This penalty represents an excess in the amount of debt that the collateral auction needs to cover.
- `liquidationQuantity`: Max amount of debt that can be liquidated in each liquidation.

## 3. Key Mechanisms & Concepts

### Liquidation Penalty

If a SAFE is subject to liquidation carrying a specific debt amount, the Liquidation Engine initiates a collateral auction. The target debt to be covered in the auction is determined by the following equation:

```
debtToAuction = debtToCover * liquidationPenalty
```

> **Example**: Alice has a SAFE with 1000 TKN locked and a 500 COINs debt. The TKN price drops, and Alice's SAFE gets liquidated. The liquidation penalty is `1.1`, so the collateral auction will auction off Alice's 1000 TKNs, to try to cover 550 COINs of debt.
### Liquidation Quantity

The quantity of collateral and debt seized from a SAFE during liquidation is decided based on the following criteria:

- If the SAFE's debt is smaller than `liquidationQuantity`, the SAFE undergoes full liquidation.
- If the SAFE's debt surpasses `liquidationQuantity`, the SAFE is only partially liquidated, and residual debt remains.
- If the SAFE's outstanding debt crosses the `onAuctionSystemCoinLimit`, partial liquidation occurs, and any remaining debt stays in the SAFE.
- In cases of partial liquidation, a corresponding slice of collateral is seized, leaving the remaining collateral intact within the SAFE.

### SAFE Saviours

These are smart contracts authorized to intervene on a user's behalf to improve the SAFE's financial condition and prevent liquidation. To become operational, SAFE Saviour contracts must receive authorization and must be chosen by each individual user.

## 4. Gotchas

### System Coin Limit

This parameter establishes a shared upper limit for the total quantity of coins—equivalent to debt—that can be simultaneously auctioned for all kinds of collateral. Once this collective cap is reached, no additional debt auctions can occur, regardless of the type of collateral in question.

Reaching this ceiling can set off a chain reaction of consequences. For example, if a specific collateral type is unusually volatile and maxes out the debt limit through numerous auctions, it could essentially monopolize the available auction capacity, preventing other types of collateral from being auctioned. Furthermore, reaching this ceiling can freeze all new collateral auctions, affecting the liquidity and stability of the system until remedial actions are taken.

Therefore, it's vital for both users and system administrators to closely monitor how near the system is to hitting the `onAuctionSystemCoinLimit`. Breaching this limit could disrupt a wide range of operations.

> **Notice**: The `onAuctionSystemCoinLimit` is a number with RAD precision.
## 5. Failure Modes

### Parameters misconfiguration:

- High `onAuctionSystemCoinLimit` risks mass collateral liquidation.
- Low `onAuctionSystemCoinLimit` slows SAFE liquidations.
- High `liquidationPenalty` amplifies user losses.
- Low `liquidationPenalty` encourages overleveraging.
- High `liquidationQuantity` favors full SAFE liquidations.
- Low `liquidationQuantity` makes small auctions gas-inefficient.
Loading

0 comments on commit 5746f0b

Please sign in to comment.