HAI
This repository contains the core smart contract code for HAI, a GEB fork. GEB is the abbreviation of Gödel, Escher and Bach as well as the name of an Egyptian god.
❱ Getting Started
Welcome to the "Getting Started" guide for the HAI Protocol. If you're new to the system or looking for a concise introduction, you've come to the right place. This section is designed to provide you with a straightforward overview of the essential concepts and steps needed to interact with the HAI ecosystem. Whether you're planning to mint stablecoins, or understand the intricacies of our smart contracts, this guide will equip you with the basic knowledge to take your first steps. Let's dive in!
Introduction to HAI
Introduction to HAI: A Framework for Stablecoin Systems
HAI serves as a framework for creating systems capable of issuing stablecoins. These stablecoins not only act as a reliable source of collateral for other DeFi protocols—when compared to assets like ETH or BTC—but also function as a store of value, complete with an integrated funding rate.
For a comprehensive understanding of the HAI framework, this documentation aims to detail each of its components. We strongly recommend reviewing Reflexer's original whitepaper as a precursor to this documentation.
Core Differentiators of HAI from GEB
HAI is an enhanced fork of GEB, but it comes with several key distinctions:
- Advanced System Parameter Controls: HAI features refined mechanisms for managing system parameters, offering superior flexibility and control.
- Enhanced Deployment and Upgradeability: The framework allows for streamlined deployment and upgrades, simplifying system maintenance.
- Robust Testing and Simulation Suite: HAI includes an upgraded testing and simulation environment, aiding in the identification and mitigation of system risks.
- Emphasis on Multi-Collateral Operations: HAI is designed with a focus on handling multiple types of collateral, broadening its application scope.
- Inclusion of Factories for Common Contract Types: The framework comes with pre-built factories for commonly used contract types, reducing the operations needed for collateral setup.
- Standardized Methods and Contract Utilities: HAI standardizes the way contracts and methods are utilized, making it easier for developers to generate changes across the system.
- Revamped Contract Interactions: The framework restructures the way contracts communicate with each other, leading to more efficient and reliable operations.
By incorporating these features, HAI aims to provide a more advanced, reliable, and user-friendly stablecoin system.
RedStone Oracles
HAI uses RedStone Oracles as one of its primary solutions for crypto assets pricing. RedStone is a Modular Oracle that delivers frequently updated, reliable, and diverse data feeds in a few models. HAI utilizes Push model which ensures that data is pushed into on-chain storage via a relayer with set conditions. (heartbeat and deviation threshold)
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 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 correspondingcType
balance.
Key Concepts
cType
: Represents a unique identifier for a collateral type within the HAI system.COIN
: An internal balance of system coins convertible tosystemCoin
on a1:1
basis.DEBT
: An internal ledger entry representing unbacked debt, erasable withCOIN
on a1:1
basis.SAFE
: A vault-like contract holding collateral and generatingCOINs
, which may also accrueDEBT
.lockedCollateral
: The collateral amount held within aSAFE
.generatedDebt
: The debt incurred by aSAFE
during theCOIN
generation process. Note that it does NOT correlate directly to the amount ofCOINs
generated.- Liquidation: A process triggered for under-collateralized SAFEs, wherein their
generatedDebt
is moved to the system'sDEBT
and collateral is seized for auction to cancel out theDEBT
.
redemptionPrice
: The internal price at which system coins can be exchanged for collateral.targetPrice
: A reference price utilized to adjust theredemptionPrice
, often aligned with market price.redemptionRate
: Governs how theredemptionPrice
changes over time, essentially functioning as the system's funding rate.stabilityFee
: A separate interest rate, unconnected to theredemptionRate
, applied to user debts and collected by the system.accumulatedRate
: Reflects the compoundedstabilityFee
applied to acType
, determining the relationship betweengeneratedDebt
and theCOINs
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.
❱ Core Modules
Welcome to the core contracts that make up the HAI Protocol. This is your go-to resource for understanding the architecture and components that underpin the HAI system. From collateral management and stablecoin issuance to governance and global settlement, these contracts are the building blocks that ensure the protocol's stability, scalability, and security.
Whether you're a developer, a system administrator, or just an enthusiast interested in the mechanics of the HAI Protocol, this index provides detailed information on each core contract and its role within the system. Explore how they interact, understand their functionalities, and learn how they contribute to the robust framework that makes HAI a leader in decentralized finance.
SAFE Engine
See SAFEEngine.sol for more details.
1. Introduction
The SAFE Engine serves as the central component of the HAI framework, managing data on user-owned SAFEs (Simplified Agreement for Future Equity) and the interest rates for different forms of collateral. It performs the following functions:
- Monitoring the debt generated at the system level, by a specific collateral type, or by individual SAFEs.
- Facilitating the internal movement of coins, collateral, or debt between accounts.
- Seizing collateral from SAFEs, usually during liquidation events.
- Managing account permissions.
- Implementing debt caps on a global scale, as well as for each type of collateral and individual SAFE.
Users have the ability to alter the status of their SAFEs via the SAFE Engine, provided that the collateralization ratio remains above the designated minimum threshold.
Notice: The SAFE Engine relies on join adapter contracts to hold the balance of ERC20 tokens of the system. Transfers within the system are handled entirely by the SAFE Engine, which does not handle any ERC20 tokens directly.
2. Contract Details
Key Methods:
Permissioned
transferCollateral
: Transfers collateral from one account to another.transferInternalCoins
: Transfers coins from one account to another.transferSAFECollateralAndDebt
: Transfers collateral and debt from one SAFE to another.modifySAFECollateralization
: Locks/Releases collateral in a SAFE, and/or generates/repays a SAFE's debt.
Authorized
updateCollateralPrice
: Updates the prices of a collateral type.updateAccumulatedRate
: Updates the accumulated rate of a collateral type.modifyCollateralBalance
: Modifies the collateral balance of an account.confiscateSAFECollateralAndDebt
: Confiscates collateral and debt from a SAFE.disableContract
: Locks the SAFEs, accumulated rates, and collateral prices from being modified.
Required Authorities:
- Oracle Relayer: needs authorization to call
updateCollateralPrice
. - Tax Collector: needs authorization to call
updateAccumulatedRate
. - Liquidation Engine: needs authorization to call
confiscateSAFECollateralAndDebt
. - Coin Join: needs authorization to call
transferInternalCoins
. - Collateral Join: needs authorization to call
modifyCollateralBalance
. - Global Settlement: needs authorization to call
disableContract
.
Contract Parameters:
Global
globalDebtCeiling
: The max amount of debt that can be generated by the system.safeDebtCeiling
: The max amount of debt that can be generated by a SAFE.
Per Collateral Type
debtCeiling
: The max amount of debt that can be generated globally by the collateral type.debtFloor
: The min amount of debt that can be generated by a SAFE of that collateral type.
Contract Data:
Global
globalDebt
: The amount of debt that was generated by the system.globalUnbackedDebt
: The amount of debt that was generated by the system and is not backed by collateral.
Per Collateral Type
debtAmount
: The amount of debt that was generated by the collateral type.lockedAmount
: The amount of collateral that is locked in all SAFEs using the collateral type.accumulatedRate
: A value that represents the accumulated interest rate.safetyPrice
: The price of the collateral type (vs HAI) at which the SAFE is considered unsafe.liquidationPrice
: The price of the collateral type (vs HAI) at which the SAFE is considered liquidatable.
A user action should never be able to modify the SAFE collateralization resulting in an unsafe state. When an update the
safetyPrice
leaves the SAFE in an unsafe state, the user may only add collateral and/or repay debt in order to restore the SAFE's collateralization to a safe state.Notice: The
lockedAmount
is a storage variable used to visibilize the total amount of collateral that backs thedebtAmount
. However, this value can be artificially increased, by creating a SAFE without debt and locking collateral in it: on the event of Global Settlement, this user would be allowed to withdraw all of his collateral and it would not be accounted for the redemptions.
3. Key Mechanisms & Concepts
ACCOUNTs vs SAFEs
The SAFE Engine handles 2 different types of entities:
- ACCOUNTs:
- May have coins and collateral (non confiscatable) balance
- May have SAFEs (one for each collateral type)
- May have authorized accounts to modify their balance (or SAFEs)
- May have in some cases (unbacked) debt (confiscatable)
- SAFEs:
- Defined by the account's address (owner) and a collateral type
- May only have locked collateral and generated debt
- May be modified by the owner account, or by authorized accounts
Notice: The protocol may be able to confiscate collateral from SAFEs, but not from ACCOUNTs, all debt generated to ACCOUNTs has is considered unbacked. Core contracts of the protocol may have debt, and they should try to settle it by destroying COINs in their balance.
The Collaterals & SAFEs Accountances
A SAFE consists of the following information:
account
: The address of the owner.collateralType
: The collateral type identifier.generatedDebt
: The amount of debt that was generated.lockedCollateral
: The amount of collateral that is locked in.
The SAFE Engine also tracks per collateral type the following information:
accumulatedRate
: A value that represents the accumulated interest rate.safetyPrice
: The price of the collateral type (vs HAI) at which the SAFE is considered unsafe.liquidationPrice
: The price of the collateral type (vs HAI) at which the SAFE is considered liquidatable
A SAFE is considered healthy when the following condition is met:
lockedCollateral * safetyPrice >= generatedDebt * accumulatedRate
COIN, DEBT, and HAI Dynamics
In this system, COINs and DEBT function similarly to matter and antimatter, created and annulled in pairs. The HAI token acts as the ERC20 counterpart of a COIN when it's outside the system, maintaining a redeemable 1:1 ratio. The system enables users to lock COINs to mint HAI or burn HAI to unlock COINs, making them operable within the framework.
DEBT, when unsecured, can be nullified using COINs on a 1:1 basis. However, within SAFEs, the relationship between generatedDebt
and generated COINs diverges from the 1:1 ratio.
Interest Accumulation
The "accumulated rate" represents the constantly accumulating interest or fees on the outstanding HAI-generated debt. Calculated over time, it's based on the amount of HAI minted and the applicable stability fee rate. This ensures that the debt owed by users evolves due to the ongoing addition of the stability fee. Whenever a user mints or repays HAI, the formula for generatedDebt
is:
coinAmount = generatedDebt * accumulatedRate
Here, coinAmount
is the number of coins the user wishes to mint or burn, and accumulatedRate
is the relevant collateral's accumulated interest rate. The coinAmount
could also be a negative figure, indicating debt dissolution.
Example: Assume a 10% annual interest rate on collateral TKN.
Initially, the
accumulatedRate
is 1. When Alice mints 100 HAI tokens (COINs) from the SAFE Engine, her resulting debt is100 * 1 = 100
.After one year, Alice repays her 100 debt. Now, the
accumulatedRate
stands at 1.1, requiring Alice to repay100 * 1.1 = 110
HAI tokens.Concurrently, Bob mints 100 HAI, resulting in a (
100 / 1.1
)90.9
debt.By year two, the
accumulatedRate
becomes 1.21. To repay his debt, Bob needs90.9 * 1.21 = 110
HAI tokens, identical to Alice's amount.Note: Negative interest rates could technically be implemented using the same mechanics.
Whenever the system refreshes the accumulatedRate
, it leads to a surplus of COINs that get allocated to an unspecified address. This surplus emerges from the updateAccumulatedRate
function, invoked by the Tax Collector. Importantly, these additional COINs are not directly extracted from any SAFE; instead, they manifest as a simultaneous debt increment for all SAFEs holding the taxed collateral type.
Transfer Collateral and Coins events
Since the transfer of collateral and coins is handled by the SAFE Engine, the events TransferCollateral
and TransferInternalCoins
are emitted by the SAFE Engine, and not by the ERC20 contracts. The events emitted by the SAFE Engine try to follow the same structure as the ERC20 events, but with the addition of the collateral type identifier in the TransferCollateral
event.
Generating Debt and minting HAI:
- Lock collateral in a SAFE:
- Deposit TKN:
TransferCollateral(TKN, source, ACCOUNT, amount)
- Lock TKN:
TransferCollateral(TKN, ACCOUNT, 0, amount)
TransferCollateral(TKN, 0, SAFE, amount)
- Generate DEBT:
TransferInternalCoins(0, ACCOUNT, amount)
- Mint HAI:
TransferInternalCoins(ACCOUNT, COIN_JOIN, amount)
ERC20.Transfer(0, destination, amount)
- Deposit TKN:
4. Gotchas
Permissioned vs Authorized
Authorized accounts are addresses allowed to call SAFE Engine isAuthorized
methods. While a SAFE can add approval to an account, which gives permission to the account to modify the SAFE's state (on isSAFEAllowed
methods), this account is not authorized to call SAFE Engine authorized methods (isAuthorized
).
SAFE State vs COIN and DEBT
The generatedDebt
and lockedCollateral
of a SAFE is measured in WAD units, while the COINs and DEBT (that gets limited, for example, by the debt ceilings) are measured in RAD units.
Notice: The reason for this is that the resultant
COIN|DEBT
is calculated by:generatedDebt[WAD] * accumulatedRate[RAY] = COIN|DEBT[RAD]
Collateral Balance vs Locked Collateral
As stated before, an ACCOUNT can have collateral balance, and an account's SAFE can have locked collateral. The difference between these two is that the collateral balance is the amount of collateral that the user has available to use (transfer or withdraw), and the locked collateral is the amount of collateral that the user has locked in a SAFE, that the user would need to modify the SAFE collateralization in order to use.
Unbacked Debt and Debt Settlement
Unbacked debt, or debt that is accounted to an ACCOUNT (not a SAFE with locked collateral) is only generated to contracts of the protocol. This debt can only be settled by having an equal an equal amount of COINs in the ACCOUNT's balance, and calling settleDebt
with the amount of DEBT/COINs to destroy.
This debt is only generated when a SAFE gets liquidated, a portion of the SAFE's collateral is transferred to the Collateral Auction House, the SAFE's debt is transferred to the Accounting Engine (unbacked). The Auction House will the transfer COINs to the Accounting Engine in order for the debt to be settled.
Confiscation of Collateral and Debt
An authorized account may call confiscateSAFECollateralAndDebt
to confiscate the locked collateral and/or debt of a SAFE. This method does not perform any checks on the SAFE's state. The flow of value is inversed when it happens during liquidations, than when the system is under global settlement. This means that this method is always authorized to arbitrarily modify the SAFE's state (and the DEBT balance of an account), even after the system was shutdown.
5. Failure Modes
Parameters misconfiguration
- Low
globalDebtCeiling
may limit user borrowing. - High
globalDebtCeiling
risks debt overload. - Low
safeDebtCeiling
hampers individual borrowing. safeDebtCeiling
aboveglobalDebtCeiling
is likely moot.- Low
cType.debtCeiling
curbs borrowing for specific collateral. cType.debtCeiling
aboveglobalDebtCeiling
is typically irrelevant.- Low
cType.debtFloor
raises liquidation risks. - High
cType.debtFloor
deters small borrowers.
Liquidation mechanics
Despite the fact that the SAFE Engine holds the latest collateral prices and SAFE state, the liquidation of a SAFE is handled by the Liquidation Engine. The Liquidation Engine is authorized to call confiscateSAFECollateralAndDebt
, which doesn't perform healthy checks, and allows it to modify the SAFE's state in an arbitrary way. If the Liquidation Engine (or any authorized address) is misconfigured, it may result in the liquidation of SAFEs that are not unsafe, or malicious modifications to any SAFE's state.
Accumulated Rate and Collateral Prices
Both the updateAccumulatedRate
and updateCollateralPrice
are authorized methods that perform no further checks in the validity of the parameters passed. If the Oracle Relayer or the Tax Collector (or any other authorized address) are misconfigured, it may result in the accumulatedRate
or safetyPrice
being set to an arbitrary value.
If the accumulatedRate
for a given collateral type is set to 0
, the collateral type may be bricked beyond repair, as the accumulatedRate
is iteratively calculated by multiplying the previous value to a multiplier.
Accounting Engine
See AccountingEngine.sol 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 thepopDebtDelay
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 (afterdisableCooldown
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.
Liquidation Engine
See LiquidationEngine.sol 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.
Oracle Relayer
See OracleRelayer.sol for more details.
1. Introduction
The Oracle Relayer is the module that handles the quoting mechanism of the system. It is responsible for the following:
- Storing the oracles addresses for each collateral type.
- Fetching and updating the price of the collateral types.
- Updating the redemption price, given the redemption rate.
2. Contract Details
Key Methods:
Public
marketPrice
: Gets the market price of the system coin.redemptionPrice
: Gets and updates the redemption price.calcRedemptionPrice
: View method that calculates (but does not update) the current redemption price.updateCollateralPrice
: Fetchs the price of a collateral type, updates the redemption price, calculates the safety and liquidation prices, and updates them in the SAFE Engine.
Authorized
updateRedemptionRate
: Updates the redemption rate.
Required Authorities:
- PID Rate Setter: needs authorization to call
updateRedemptionRate
.
Contract Parameters:
Global
- SAFE Engine: Is called to update the collateral prices on it.
- System Coin Oracle: Is queried to fetch the market price of the system coin.
redemptionRateLowerBound
: Lower bound of the redemption rate.redemptionRateUpperBound
: Upper bound of the redemption rate.
Per Collateral Type
- Oracle: Is queried to fetch the price of the collateral type.
safetyCRatio
: Ratio applied to the collateral price to define the safety price.liquidationCRatio
: Ratio applied to the collateral price to define the liquidation price.
3. Key Mechanisms & Concepts
Quoting Mechanism
Each collateral type needs to have an associated oracle that quotes the collateral in terms of the denomination currency (in HAI, US Dollars). The System Coin Oracle needs to be also denominated in the same currency.
The Oracle Relayer handles the quoting mechanism, in which collateral types are quoted in terms of HAI, applying a variable rate to HAI price. The collateral price is calculated as follows:
collateralPrice = oraclePrice / redemptionPrice
C Ratios
Safety and liquidation prices are calculated by applying a ratio to the collateral price. The safety price is calculated as follows:
safetyPrice = collateralPrice * safetyCRatio
liquidationPrice = collateralPrice * liquidationCRatio
The safety price is the price at which the SAFE is considered safe, a user may modify the SAFE collateralization as long as the resulting state is above the safety price.
The liquidation price is the price at which the SAFE is considered liquidatable, and the SAFE may be liquidated.
4. Gotchas
5. Failure Modes
Parameters misconfiguration:
- High
safetyCRatio
limits SAFE modifications. safetyCRatio
nearliquidationCRatio
makes it redundant.- High
liquidationCRatio
may cause needless liquidations. - Low
liquidationCRatio
encourages overleveraging.
Tax Collector
See TaxCollector.sol for more details.
1. Introduction
The Tax Collector is the module that handles the collection of taxes. It is responsible for the following:
- Storing the interest rate for each collateral type.
- Storing the tax revenue receivers.
- Calculating and distributing the tax revenue.
2. Contract Details
Key Methods:
Public
taxSingle
: Calculates and distributes the tax revenue for a single collateral type.taxMany
: Calculates and distributes the tax revenue for a set of collateral types.
Contract Parameters:
Global
- SAFE Engine: Is called to update the accumulated rate for each collateral type.
- Primary Tax Receiver: Receives tax revenue for all collateral types.
globalStabilityFee
: Global stability fee applied to all collateral types.maxStabilityFeeRange
: Maximum range for the stability fee to differ from 1 (no fee).
Per Collateral Type
- Secondary Tax Receivers: Addresses (and tax percentage) that receive revenue for the collateral type total stability fees.
stabilityFee
: Stability fee applied only to the collateral type.
3. Key Mechanisms & Concepts
Primary and Secondary Tax Receivers
The contract holds 2 types of tax receivers:
- Primary Tax Receiver: Is a shared address across all the collateral types. It receives the remaining tax revenue after the secondary tax receivers have been paid.
- Secondary Tax Receivers: Is a set of addresses per collateral type, that can be set to receive a fixed percentage amount of the tax revenue of the collateral type.
Global and Per Collateral Stability Fees
The tax (or Stability Fee) can be configured in 2 ways:
- Global Stability Fee: Shared across all the collateral types.
- Per Collateral Stability Fee: Set for each collateral type.
The final stability fee computed for a collateral type is the multiplication of both fees. To avoid retroactivity, the tax collecting routine first reads the previously stored stability fee, and then calculates and stores the new one.
4. Gotchas
5. Failure Modes
Parameters misconfiguration:
maxStabilityFeeRange
too high may result in a bad calculation of the stability fee, resulting in broken collateral types (as their accumulated rate will be too low/high).maxStabilityFeeRange
too low may result in a bounded value for the stability fee, bounding the final stability fee to a value very similar to 1 (no stability fee).maxSecondaryTaxReceivers
too low may result in not being able to add a secondary tax receiver to a collateral type.- Stability fees (
global * perCollateral
) too high may result in users not interested in generating debt. - Stability fees too low may result in the protocol not being able to generate enough revenue to cover the system expenses.
PID Controller
See PIDController.sol and PIDRateSetter.sol for more details.
1. Introduction
The PID Controller is a smart contract that fine-tunes the system's redemption rate by analyzing the deviation
, which is the discrepancy between the market and redemption prices. It performs the following tasks:
- Computes and stores the system's proportional and integral deviations.
- Applies a decay factor to the integral deviation.
- Adjusts the redemption rate by applying proportional and integral gains to the deviation.
The PID Rate Setter schedules and triggers the PID Controller's redemption rate adjustments.
2. Contract Details
2.1 PID Controller
Key Methods:
Authorized
computeRate
: Computes the new redemption rate, applying the proportional and integral gains to the deviation (can only be called by the PID Rate Setter contract).
Contract Parameters:
- Seed Proposer: Authorized address for initiating redemption rate updates.
integralPeriodSize
: Minimum duration required to calculate integral deviation.perSecondCumulativeLeak
: Decay constant for the integral deviation.noiseBarrier
: Lowest deviation percentage considered for redemption rate adjustment.feedbackOutputUpperBound
: Maximum limit for the redemption rate.feedbackOutputLowerBound
: Minimum limit for the redemption rate.proportionalGain
: Gain factor for proportional deviation.integralGain
: Gain factor for integral deviation.
2.2 PID Rate Setter
Key Methods:
Public
updateRate
: Retrieves market and redemption prices from the Oracle Relayer and prompts the PID Controller to compute the new redemption rate.
Contract Parameters:
updateRateDelay
: Time gap between successive redemption rate adjustments.
3. Key Mechanisms & Concepts
Deviation Metrics
The PID Controller monitors the gap between market and redemption prices and stores both the proportional and integral deviations. Whenever the deviation changes, its integral component is decayed to mitigate the impact of historical deviations on future rates.
Proportional Deviation (pTerm
)
It is computed as:
pTerm = (redemptionPrice - marketPrice) / redemptionPrice
Integral Deviation (iTerm
)
It is calculated iteratively:
iTerm_n = (iTerm_(n-1) * decayFactor) + ((pTerm_n - pTerm_(n-1)) / 2)
Gain Parameters
The system owner can configure the gain parameters for proportional (pGain
) and integral (iGain
) deviations. The redemption rate is then adjusted as follows:
redemptionRate = 1 + (pTerm * pGain + iTerm * iGain)
Notice: All of pTerm, iTerm, pGain, iGain can be negative, so the redemption rate can be lesser than 1 (decrease the rate). Yet the redemption rate can never be 0 or negative.
4. Gotchas
5. Failure Modes
- Invalid
seedProposer
risks stale redemption rate. - High
noiseBarrier
hampers redemption rate adjustment. - High
integralPeriodSize
lowers PID responsiveness. - Over-the-top
feedbackOutputUpperBound
is likely disregarded. - Null
feedbackOutputUpperBound
constrains positive control range. - Excessive
feedbackOutputLowerBound
may be overlooked. - Null
feedbackOutputLowerBound
limits negative control range. - High
perSecondCumulativeLeak
quickens integral decay. - Low
perSecondCumulativeLeak
amplifies integral's historical effect. - High
kp
makes controller jittery to current deviations. - High
ki
overemphasizes historical deviations.
Stability Fee Treasury
See StabilityFeeTreasury.sol for more details.
1. Introduction
The Stability Fee Treasury functions as a specialized contract designed for managing protocol fees that are not factored into the system's surplus or deficit calculations. Unlike locked funds, the funds within this contract remain liquid and can be flexibly utilized by the system owner. Its key responsibilities encompass:
- Facilitating the disbursement of rewards for maintenance tasks.
- Utilizing funds to address unbacked debt.
- Managing diverse payments initiated by the system owner.
- Replenishing the system's surplus/deficit sheets when the treasury surpasses its predefined capacity.
2. Contract Details
Key Methods:
Public
settleDebt
: This function efficiently allocates available funds to cover unbacked debt within the treasury's accounting.transferSurplusFunds
: This operation addresses outstanding debt to the maximum extent achievable and transfers any excess funds beyond the capacity back to the system's surplus/deficit sheets.
Permissioned
takeFunds
: Enables the authorized withdrawal of funds from a consenting address to the treasury.pullFunds
: Allows an address with sufficient allowance to withdraw funds from the treasury.
Authorized
setTotalAllowance
: Grant an address the permission to withdraw funds from the treasury up to a specified limit.setPerHourAllowance
: Assign a per-hour withdrawal limit to an address, allowing them to pull funds from the treasury within this constraint.giveFunds
: Move funds from the treasury to a designated address.disableContract
: Swiftly transfer all available funds from the contract to a predetermined drainage address.
Required Authorities:
- Global Settlement: needs authorization to call
disableContract
.
Contract Parameters:
- SAFEEngine: Query and settle the treasury's coin and debt balance.
- Extra Surplus Receiver: Who receives the funds that are above the treasury's capacity (usually Accounting Engine).
- CoinJoin: Used to join ERC20 HAI into the system.
treasuryCapacity
: Maximum amount of funds that the treasury can hold (before transferring to the extra surplus receiver).pullFundsMinThreshold
: Minimum amount of funds that the treasury must hold to be able to pull funds from it.surplusTransferDelay
: Minimum delay between transfers of funds to the extra surplus receiver.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
❱ Auction Houses
Introduction
Auction Houses are core smart contracts in the HAI Protocol that manage debt, surplus, and collateral through automated auctions. Whether you're an active participant or simply interested in HAI's stability mechanisms, understanding these components is crucial.
Types of Auction Houses
- Collateral Auction House: Facilitates the sale of confiscated collateral from liquidated SAFEs, aiming to cover associated debts.
- Debt Auction House: Auctions off the system's debt, offering to mint Protocol Tokens as rewards for debt settlement.
- Surplus Auction House: Manages system surplus, conducting auctions (Protocol Tokens buybacks) to distribute excess funds.
Understanding these mechanisms is essential for navigating the HAI Protocol's automated balance and risk management features.
Collateral Auction House
See CollateralAuctionHouse.sol for more details.
1. Introduction
The Collateral Auction House plays a crucial role in maintaining the stability of the HAI Protocol by handling the auction of collateral seized from undercollateralized SAFEs. The primary objective is to convert this confiscated collateral into system coins, which are then forwarded to the Accounting Engine for debt destruction.
The Collateral Auction House utilizes an increasing discount model. This encourages early bidding by incrementally increasing the discount applied to the collateral over time. The rationale behind this is to expedite the auction process and ensure that debts are covered as swiftly as possible.
2. Contract Details
Key Methods:
Public
buyCollateral
: Enables holders of the system coin to participate in auctions by purchasing available collateral.
Authorized
startAuction
: Initiates a new collateral auction for the contract's specific collateral type.terminateAuctionPrematurely
: Allows for the early termination of an ongoing auction, with any remaining collateral allocated to the caller's address.
Contract Parameters
- Liquidation Engine Address: Specifies the address of the Liquidation Engine, the module responsible for handling the on-auction system coin limit.
- Oracle Relayer Address: Specifies the address of the Oracle Relayer, responsible for providing up-to-date price information.
minimumBid
: Sets the minimum system coin bid required to participate in collateral auctions.minDiscount
: Defines the initial discount rate at which auctions commence.maxDiscount
: Sets the upper limit for the discount rate that auctions can achieve.perSecondDiscountUpdateRate
: Determines the rate at which the discount increases for each second the auction is live.
3. Key Mechanisms & Concepts
Collateral Price Feed and Discount Model
The Collateral Auction House relies on the system's collateral price feed to determine the current market price of the collateral in terms of system coins. Upon establishing this baseline, the contract employs a dynamic discount model to calculate the auction price of the collateral. Here's how the discount model works:
-
Initial Discount: Each auction kicks off with a predefined minimum discount. This discount is set by the
minDiscount
parameter. -
Per-Second Discount Rate: The contract features a rate at which the discount increases on a per-second basis. This rate is determined by the
perSecondDiscountUpdateRate
parameter. -
Maximum Discount Cap: Once the auction reaches the maximum allowable discount, as defined by the
maxDiscount
parameter, the auction remains at this discount level until either all the collateral is bought or the auction is prematurely terminated.
This approach ensures that the auction starts incentivizing early bids but also allows for adjustments over time, ultimately facilitating efficient price discovery and collateral liquidation.
4. Gotchas
5. Failure Modes
Debt Auction House
See DebtAuctionHouse.sol 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
Surplus Auction House
For more details, refer to the SurplusAuctionHouse.sol contract.
1. Introduction
The Surplus Auction House is tasked with auctioning the system's surplus coins in exchange for protocol tokens. A fraction of these protocol tokens is burnt to create a deflationary effect, while the rest is transferred to a specified target address. The auction employs an ascending bidding model: a fixed number of system coins are up for auction, and participants bid by offering increasingly higher amounts of protocol tokens.
2. Contract Details
Key Methods:
Public
increaseBidSize
: Enables users to participate in the auction by offering higher amounts of protocol tokens, which are transferred during this operation.restartAuction
: Resets an expired auction that has not received any bids, making it available for new bids.settleAuction
: Finalizes the auction, transferring the system coins to the winning bidder.terminateAuctionPrematurely
: Aborts an auction before its scheduled completion. This action returns the protocol tokens to the highest bidder but is only possible when the contract is deactivated.
Authorized
startAuction
: Initiates a new surplus auction.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
❱ Settlement
The Settlement Module serves as a critical component in the lifecycle of the HAI protocol, governing its shutdown and the subsequent redemption of HAI tokens for underlying collateral. It activates in circumstances that necessitate the halting of the system—such as critical bugs, governance decisions, or market anomalies—to ensure a smooth and orderly unwinding of positions. The module's primary objective is to provide a transparent and fair mechanism for redeeming HAI tokens, thereby ensuring the protocol's integrity even in its termination phase.
Global Settlement
See GlobalSettlement.sol for more details.
1. Introduction
The Global Settlement contract serves as the emergency brake and ultimate wind-down mechanism for the system. Its responsibilities include:
- Triggering the System Shutdown: Initiating the process to safely halt all operations.
- Processing SAFEs: Settling all Secure, Automated, Flexible, and Efficient (SAFE) accounts to determine each collateral's deficits and surplus.
- Terminating Auctions: Bringing all ongoing auctions to a premature end, ensuring that assets are no longer tied up.
- Calculating Redemption Price: Determining the value at which system coin holders can redeem their coins for backing collateral.
- Redemption: Enabling system coin holders to exchange their coins for the appropriate collateral, completing the shutdown process.
This contract is crucial for ensuring that, in the event of a system shutdown, all parties can walk away with assets that are rightfully theirs, thus maintaining a fair and secure environment.
2. Contract Details
Key Methods:
Public
freezeCollateralType
: Captures the current market price of a specified collateral type and freezes it within the contract. This is crucial for ensuring accurate valuations during the shutdown process.fastTrackAuction
: Allows for the immediate termination of ongoing collateral auctions. This function ensures that assets are returned to their rightful owners as quickly as possible during a shutdown.processSAFE
: This method is responsible for settling the debts associated with SAFEs and determining any collateral deficit that exists. This ensures that all assets and liabilities are properly accounted for.freeCollateral
: Post-processing of SAFEs, this function enables SAFE owners to withdraw any remaining collateral. This ensures that users recover their tied-up assets.setOutstandingCoinSupply
: Sets the global coin supply (which also accounts for the system's debt). This is important for calculating how much collateral can be redeemed for each system coin.calculateCashPrice
: Determines the price at which system coin holders can redeem their coins for backing collateral. This provides clarity and fairness in the redemption process.prepareCoinsForRedeeming
: Allows system coin holders to deposit their coins into the contract in preparation for redemption. This sets the stage for users to reclaim their backing collateral.redeemCollateral
: Executes the redemption process, transferring the appropriate amount of collateral to system coin holders who have previously deposited their coins for redemption. This is the final step in the shutdown and asset recovery process.
Authorized
shutdownSystem
: This function triggers the system shutdown, initiating all the processes mentioned above. This function can only be executed by an authorized entity.
These methods collectively enable a structured and secure way to halt system operations, settle accounts, and distribute assets in the event of a system shutdown.
Contract Parameters:
- Oracle Relayer: The address used to fetch the redemption price and the collaterals price.
- Liquidation Engine: The address used to fetch the collateral auction houses from each collateral type.
- Coin Join: The Coin Join contract (to disable).
- Collateral Join Factory: The Collateral Join Factory contract (to disable).
- Collateral Auction House Factory: The Collateral Auction House Factory contract (to disable).
- Stability Fee Treasury: The Stability Fee Treasury contract, that needs to be disabled before the Accounting Engine to transfer its funds to it.
- Accounting Engine: The Accounting Engine contract, that tries after disablement to settle as much debt as possible, and transfer the remaining surplus to the post settlement drain account.
shutdownCooldown
: The amount of time that must pass after the system shutdown is triggered before the outstanding coin supply can be calculated.
3. Key Mechanisms & Concepts
System Shutdown
The system shutdown is triggered by calling the shutdownSystem
method, that triggers the disableContract
method on the disableable contracts (see Disableable.sol). Disableable contracts implement the following tools:
contractEnabled
: A boolean flag that indicates whether the contract is enabled or disabled._onContractDisable
method: A routine that is triggered when the contract is disabled.whenEnabled / whenDisabled
modifiers: Modifiers that can be used to restrict the execution of a method to when the contract is enabled or disabled.
Collateral Redemption Price Calculation
The calculateCashPrice
method plays a critical role in the Global Settlement contract by determining the rate at which each system coin can be redeemed for its underlying collateral. The method employs a complex formula to arrive at this price, ensuring an equitable distribution of collateral assets based on various dynamic factors.
The formula used to calculate the collateral redemption price (collateralCashPrice
) is as follows:
collateralCashPrice =
(
collateralDebt * accumulatedRate / collateralPrice
- collateralShortfall
) / outstandingCoinSupply
Where:
collateralDebt
: Represents the aggregate debt associated with a specific collateral type, generated by SAFEs.accumulatedRate
: The total accrued rate (like interest or tax rate) applied to the specific collateral type over time.collateralPrice
: The most recent market price for the specific collateral type, usually fetched from a trusted oracle.outstandingCoinSupply
: The total circulation of system coins, essentially the aggregate debt of the system.collateralShortfall
: Quantifies the deficit in terms of system coins for the collateral type.If SAFEs for a particular collateral type are under-collateralized, this value will capture the shortfall. Conversely, if SAFEs are over-collateralized, owners are entitled to withdraw the surplus.
Redemption Mechanism:
Once the collateralCashPrice
is calculated, users can redeem their system coins for the backing collateral using the following formula:
redeemableCollateral = coinAmount * collateralCashPrice
This ensures that each coin is redeemable for a fair portion of collateral, aiming to clear out both coins and collateral from the system by the end of the Global Settlement process.
Notice: The design of this formula is such that by the end of the redemption process, the system should ideally have neither excess coins nor remaining collateral. It provides a balanced mechanism for winding down system operations and returning assets to participants.
4. Gotchas
5. Failure Modes
Parameters Misconfiguration
- A too-low
shutdownCooldown
risks premature shutdown, leading to inaccurate collateral redemption prices due to incomplete auctions and unprocessed SAFEs. - A too-high
shutdownCooldown
prolongs the waiting period for users to redeem their coins for backing collateral, causing potential liquidity issues.
Incorrect Authorizations or State
This contract requires to have authorization in the following contracts:
- SAFEEngine
- OracleRelayer
- LiquidationEngine
- CollateralAuctionHouseFactory
- CoinJoin
- CollateralJoinFactory
- StabilityFeeTreasury
- AccountingEngine
Should one of this authorizations be missing, the contract will not work as expected, reverting on the shutdownSystem
routine.
The routine also requires all above contracts to be enabled. Should one of these contracts have been manually disabled, the routine will revert.
Post Settlement Surplus Auction House
See PostSettlmentSurplusAuctionHouse.sol for more details.
1. Introduction
The Post Settlement Surplus Auction House is responsible for auctioning off the surplus coins the system has after the global settlement is triggered. The auctions resemble the Surplus Auction House auctions, with the difference that all of the protocol tokens are burned.
2. Contract Details
Key Methods:
Public
increaseBidSize
: Allows users to bid on the auctions, protocol tokens are transferred in this call.restartAuction
: Restarts an auction that expired with no bids.settleAuction
: Settles an auction, sending the system coins to the winning bidder.
Authorized
startAuction
: Starts a new surplus auction.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
Settlement Surplus Actioneer
See SettlementSurplusActioneer.sol for more details.
1. Introduction
The Settlement Surplus Auction Module facilitates the auctioning of surplus coins held by the system following the activation of a global settlement. The module's purpose is grounded in the idea that without conducting an auction, the total circulating coins might fall short of the overall system debt. This imbalance could lead to an increased redemption price for collateral. By orchestrating surplus auctions, the system guarantees an equitable redemption price, while also deterring ill-intentioned actors from exploiting a global settlement to acquire collaterals at a discounted rate.
2. Contract Details
Key Methods:
Public
auctionSurplus
: Triggers a surplus auction and starts the cooldown period.
Contract Parameters:
- Accounting Engine: Used to fetch the surplus auction parameters.
- Surplus Auction House: The Post Settlement Surplus Auction House contract.
Notice: The contract reads the parameters from the Accounting Engine to define the surplus auction cooldown period and the size of the auctions.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
❱ Tokens & Utils
This section introduces the ERC20 tokens, and token adaptor contracts, such as CoinJoin and CollateralJoin. These contracts serve as vital bridges between tokens and the smart contract operations, enhancing interoperability and functionality.
System Coin
See SystemCoin.sol for more details.
Protocol Token
See ProtocolToken.sol for more details.
Join Adapters
See CoinJoin.sol, CollateralJoin.sol for more details.
1. Introduction
The Join Adapter contracts assume responsibility for facilitating the seamless movement of collateral and system coin ERC20s into and out of the system. Their functions encompass:
- Safeguarding collateral ERC20 tokens through locking them within the contract, leading to an augmentation of the user's collateral type balance.
- Liberating collateral ERC20 tokens back to the user, thereby diminishing the user's collateral type balance.
- Generating system coin ERC20 tokens through the locking of internal coins within the contract.
- Eradicating system coin ERC20 tokens from the user's holdings, resulting in the release of internal coins to the user.
These contracts engage directly with the SAFE Engine, necessitating occasional user approval to permit the contract to access funds from their account. In the system, a collateral balance is denoted by a specific collateral type string (for example, 'ETH-A', 'OP').
2. Contract Details
2.1 Collateral Join
Key Methods:
join
: This operation secures collateral ERC20 tokens within the contract and augments the collateral type balance of the designated account.exit
: This function liberates collateral ERC20 tokens to the specified account, resulting in a reduction of the user's collateral type balance.
2.2 Coin Join
Key Methods:
exit
: This action involves locking internal coins within the contract and generating system coin ERC20 tokens for the designated account.join
: This function entails releasing internal coins to the specified account while extinguishing system coin ERC20 tokens from the user's holdings.
3. Key Mechanisms & Concepts
System Coin vs Collateral Modes
The system coin ERC20 represents a transferable unit of internal COINs that were initially generated via SAFEs. The ultimate purpose of the system coin ERC20 is to integrate into the system and contribute to the reduction of DEBT. This purpose leads to a reversal in logic between the Coin and Collateral Join contracts concerning the join
and exit
methods.
In the Collateral Join contract, users lock collateral to create an internal balance of a specific collateral type, and they can subsequently burn this internal balance to retrieve their ERC20 tokens. Conversely, in the Coin Join contract, users perform the opposite actions: they burn or mint the system coin ERC20 to respectively release or lock internal coins.
ERC20 Decimal Conversion
To accommodate a diverse array of collaterals and price references, the system employs a standardized unit for establishing balances and quotes, utilizing WAD precision (18 decimals). To ensure this consistency, the Collateral Join contract integrates a conversion factor during the execution of its join and exit methods. This strategy guarantees that users consistently interact with the contract using wei
measurements, which align with the token's inherent precision.
Notice: The CollateralJoin contract supports tokens with less than 18 decimals, but not more.
4. Gotchas
Precision Dust
Due to the potential variance between the precision of the system and that of the ERC20 tokens, users might encounter a situation where their collateral balance is lower than the system's minimum withdrawal threshold. This discrepancy can arise when the amount of collateral falls short of even 1 wei
, which is the smallest unit the system can process for withdrawal purposes.
5. Failure Modes
Global Settlement Mode
When the Coin Join functionality is deactivated, the contract permits the use of the join
method while restricting access to the exit
method. This implies that users retain the ability to convert their system coin ERC20 into internal coins, but they are prevented from generating additional system coin ERC20 tokens.
Conversely, in the event of Collateral Join being disabled, the contract enables the exit
method while prohibiting the use of the join
method. This signifies that users maintain the capability to redeem their collateral ERC20 by burning their corresponding collateral type balance, but they are unable to add more collateral ERC20 tokens to the contract.
On Authorizations
- For Coin Join to mint system coin ERC20, authorization within the System Coin contract is mandatory.
- Prior to interaction, users are required to grant approval within the SAFE Engine for the Coin Join contracts to access and withdraw funds from their account.
- Collateral Join necessitates authorization within the SAFE Engine contract for the purpose of modifying the collateral balance.
- With an active ERC20 balance and SAFE Engine authorization, the Collateral Join contract is capable of withdrawing funds from the user's account.
- The Coin Join contract can effectively burn system coin ERC20 tokens to provide funds to the user's account, provided the user has granted approval within the SAFE Engine and the Coin Join retains an internal coin balance.
Replaceability
Both the Coin and Collateral Join contracts could potentially be superseded by a single new contract through a multi-step process carried out by a single user. This process involves repeating the following sequence:
- Deploy and configure the new Join contract.
- Deactivate the current Join contract.
- For the Collateral Join:
- Execute
exit
on the old (deactivated) contract (reducing the internal balance). - Execute
join
on the new contract (increasing the internal balance). - Execute
exit
on the old contract. - Repeat this sequence until all collateral is successfully transferred.
- Execute
- For the Coin Join:
- Remove authorization for the system coin ERC20 from the old contract.
- Execute
join
on the old (deactivated) contract (increasing the internal balance). - Execute
exit
on the new contract (reducing the internal balance). - Repeat this sequence until all system coin ERC20 tokens are moved.
The primary objective of this procedure is to ensure that both contracts conclude with no funds remaining locked within them. This approach guarantees that the new join contract attains an internal balance equivalent to the amount of ERC20 tokens locked. Subsequently, it's essential to revoke the relevant authorizations from these contracts to complete their deprecation.
❱ Contract Utils
This section provides an in-depth exploration of inheritable utility contracts meticulously crafted to enhance and amplify the capabilities of the protocol. These adaptable utility contracts, when inherited by other protocol contracts, introduce fresh and extended functionalities that enhance the overall development process and consistency of the system. Through a detailed examination of these utilities, readers will gain a deeper understanding of how they contribute to a more robust and harmonized protocol ecosystem.
Authorizable
See Authorizable.sol for more details.
1. Introduction
This abstract contract introduces a fundamental authorization mechanism designed for contracts. It enables a contract to manage authorization for multiple accounts, granting them specific permissions. This is achieved through the use of modifiers, which serve to control and restrict access to designated methods as required.
2. Contract Details
Key Methods:
Authorized
addAuthorization
: Grants authorization to an account.removeAuthorization
: Removes authorization from an account.
Notice: Both methods will revert in the case of a no-operation (i.e. the account is already authorized or unauthorized).
3. Key Mechanisms & Concepts
In the contracts that inherit this functionality, all authorized accounts possess equal access privileges, without any hierarchy of authorization. This implies that any authorized account is capable of both adding and removing authorization for any other account.
4. Gotchas
5. Failure Modes
Modifiable
See Modifiable.sol for more details.
1. Introduction
This abstract contract establishes a standardized mechanism by which contracts can modify their registry and parameters. The available methods are confined to authorized accounts, ensuring that only designated entities have the authority to make these adjustments.
2. Contract Details
Key Methods:
modifyParameters
: Modifies a parameter of the contract._validateParameters
: Hook to validate the parameters after modifying them.
3. Key Mechanisms & Concepts
Standarized Method
The modifyParameters
method is standarized to be shared across contracts that may require different types of parameters. The parameter values are passed as a bytes array, and the inheriting contract is responsible for parsing them (see Encoding).
There are 2 methods that can be used to modify the parameters:
modifyParameters(bytes32 _param, bytes memory _data)
: Modifies a global contract parameter.modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data)
: Modifies a contract per-collateral parameter.
Parameters Structs
To explicitly define the parameters that can be modified, the contracts should define a parameters struct. Contract parameters that can be modified should be accessed through this struct, and will be read either as params.__param__
or cParams[_cType].__param__
.
Parameters Validation
The _validateParameters
hook is called after modifying the parameters, and can be used to validate the new parameters according to the contract's logic. All contract parameters should be validated, despite they having been modified or not. Common validations may use some of the methods defined in the Assertions library.
As with the modifyParameters
method, there are 2 methods that can be used to validate the parameters:
_validateParameters
: Validates all global contract parameter._validateCParameters
: Validates all contract per-collateral parameter.
Notice: The validation hooks should avoid a parameter that would cause the contract to be set in an undesired way. For example, the OracleRelayer contract implements a check on the liquidation ratio to be always above 100%, else the system would allow for overleveraged positions.
4. Gotchas
Constructors
Contracts that incorporate this functionality must guarantee that their constructors enforce initial parameter validation. This approach serves to prevent the deployment of contracts with invalid parameters. As a result, all validated parameters must be provided as arguments during the contract's construction, ensuring that only valid configurations are utilized upon deployment.
Testing
To thoroughly test the complete implementation of the modifyParameters
method, the testing process should involve fuzzing a parameters struct with all potential values. Subsequently, the method should be called, and the outcome must be validated to confirm that all parameters within the struct have been altered as intended.
To achieve this testing goal, the approach involves comparing the hash of the modified parameters struct with the struct's state obtained from the contract after the modifications have been executed. This rigorous comparison ensures that the method successfully and accurately modifies each parameter as specified.
5. Failure Modes
Disableable
See Disableable.sol for more details.
1. Introduction
This abstract contract introduces a fundamental disable mechanism for contracts. It grants the ability for a contract to be effectively deactivated, and utilizes modifiers to control access to specific methods based on the contract's current state.
2. Contract Details
Key Methods:
Authorized
disableContract
: Disables the contract.
Internal
_onContractDisable
: Hook to be called when the contract is disabled._isEnabled
: Checks if the contract is enabled.
Modifiers
whenEnabled
: Restricts access to the method to when the contract is enabled.whenDisabled
: Restricts access to the method to when the contract is disabled.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
❱ Factories
This section introduces a collection of essential contracts designed to streamline the creation and operation of various factory-related components. These contracts, alongside their accompanying utility modules, are specifically engineered to be inherited within the context of factory contracts. By leveraging these building blocks, developers can expedite the process of constructing, managing, and optimizing factory contracts with enhanced efficiency and reliability.
FactoryChild
See FactoryChild.sol for more details.
1. Introduction
This abstract contract is inherited by all contracts that are deployed through a factory. It provides a reference to the parent factory.
2. Contract Details
Key Methods:
factory
: Returns the parent factory.
3. Key Mechanisms & Concepts
The rationale behind this contract is to provide a way of extending contracts that are standalone deployable, to be deployed through a factory. Contracts that are factory deployed can also implement other factory related utils, such as AuthorizableChild or DisableableChild.
4. Gotchas
Constructors
Contracts which only change from the standalone version is the constructor routine should not create a new instance of the contract, but be considered as another child implementation of the same contract. This is the case of the CollateralJoinDelegatableChild, which is a child implementation of the CollateralJoin contract, that calls the ERC20Votes.delegate
method on constructor.
5. Failure Modes
AuthorizableChild
See AuthorizableChild.sol for more details.
1. Introduction
This abstract contract extends the Authorizable contract for factory deployed instances, to allow for a contract to be authorized in the parent factory, and still be able to access restricted methods.
2. Contract Details
Overrides
_isAuthorized
: internal method to check if the sender is authorized in the contract or the parent factory.
3. Key Mechanisms & Concepts
The contract will check if the sender is authorized in the contract or the parent factory.
4. Gotchas
5. Failure Modes
DisableableChild
See DisableableChild.sol for more details.
1. Introduction
This abstract contract extends the Disableable contract for factory deployed instances, to allow for the parent factory to be disabled, and extend the disabled state to all the child contracts.
2. Contract Details
Overrides
_isEnabled
: internal method to check if the contract AND the parent factory are enabled._onContractDisable
: can only be called by the parent factory.
3. Key Mechanisms & Concepts
The contract will check if the contract AND the parent factory are enabled. If either is disabled, the contract is considered disabled.
4. Gotchas
Contracts that inherit this contract can only be disabled by the parent factory. In that way, the factory can keep track of all the enabled contracts that have been deployed through it.
5. Failure Modes
❱ Proxy Utils
One of the core components of the HAI ecosystem is the HAI Safe Manager and Proxy Contracts. These smart contracts are designed to provide a secure and efficient way to interact with the HAI protocol, enabling users to manage their SAFEs and assets, and execute transactions in a streamlined manner.
HAI Proxy
See HaiProxy.sol for more details.
1. Introduction
The HAI Proxy contract is a powerful and flexible smart contract commonly used within the decentralized finance (DeFi) ecosystem. Its primary function is to act as an extensible, personal proxy contract that allows users to bundle multiple actions into single, atomic transactions. With HAI Proxy, users can interact with multiple smart contracts or execute complex contract calls in a secure, efficient, and modular manner.
2. Contract Details
Key Methods:
Owner
execute
: Allows owner to call a specific contract (usually a library or helper contract containing business logic) and pass in encoded function arguments to execute a certain operation.
3. Key Mechanisms & Concepts
Delegate Calls
In the Ethereum smart contract ecosystem, a delegate call is a special type of contract invocation that allows one contract to "borrow" code from another contract, executing it as if it were part of the calling contract's own code. Unlike a regular function call, a delegate call operates within the context of the calling contract, meaning it can read and modify the calling contract's state variables.
4. Gotchas
Dealing with Delegate Calls and ERC20 Transfers
When using proxy contracts that rely on delegate calls, certain common actions like ERC20 token transfers require special handling. In a typical setup, if a user attempts to execute ERC20.transfer
directly, aiming to transfer a balance that is attributed to the proxy, the operation will fail and the call will revert. This is because delegate calls operate in the context of the calling contract, not the called contract. In this case, the calling contract is the proxy, which doesn't hold the tokens, leading to a failed transaction.
To work around this issue, an intermediary contract can be introduced. This intermediary contract is responsible for parsing the intended action and then executing the transfer
operation using a regular call, rather than a delegate call.
5. Failure Modes
Proxy Factory
See HaiProxyFactory.sol and HaiProxyRegistry.sol for more details.
1. Introduction
The Proxy Factory Contract serves as a smart contract template for generating multiple proxy contracts in an automated, scalable manner. The Proxy Registry is a registry that keeps track of all the proxy contracts generated by the Proxy Factory Contract.
2. Contract Details
Key Methods:
Public
build
: Creates a new proxy contract and registers it in the Proxy Registry.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
SAFE Manager
See HaiSafeManager.sol and SAFEHandler.sol for more details.
1. Introduction
The SAFE Manager Contract serves as an interface for interacting with the SAFE Engine, which is the core contract responsible for managing SAFEs in the HAI ecosystem. While the SAFE Engine handles the intricate logic and state changes for SAFEs, the SAFE Manager simplifies and streamlines user interactions with their SAFEs. Essentially, it provides an abstraction layer that facilitates operations such as depositing collateral, withdrawing, and managing debt positions in a user-friendly manner.
2. Contract Details
Key Methods:
openSAFE
: Deploys a new SAFE Handler contract and registers it in the SAFE Manager.transferSAFEOwnership
: Initiates the ownership transfer of a SAFE to another address (doesn't reset SAFE protection).acceptSAFEOwnership
: Commits to the ownership transfer of a SAFE to another address (needs to be called by the new SAFE owner).modifySAFECollateralization
: Modifies the collateralization ratio of a SAFE (lock/free collateral and/or generate/repay debt).transferCollateral
: Transfers collateral from one account to another.transferInternalCoins
: Transfers internal coins from one account to another.quitSystem
: Closes a SAFE and transfers all remaining collateral and debt to the user's address.enterSystem
: Migrates collateral and debt from a source SAFE Handler to a destination SAFE.moveSAFE
: Migrates a SAFE from one SAFE to another.protectSAFE
: Protects a SAFE from being liquidated, using a SafeSaviour position to improve the SAFE health when it falls below the liquidation ratio.
3. Key Mechanisms & Concepts
SAFE IDs
The SAFE Engine identifies each SAFE by its unique contract address and the type of collateral it holds. In contrast, the SAFE Manager simplifies this by assigning each SAFE an auto-incremental ID when it is created. This ID serves as an easy-to-use reference point for users and external contracts, streamlining interactions and management. The auto-incremental ID is particularly useful for human readability and ease of interaction, while the address and collateral type identification in the SAFE Engine provides more granularity and is essential for the underlying mechanics.
Understanding the SAFE Handler
The SAFE Handler is a specialized contract that acts as an intermediary between the SAFE Engine and the SAFE Manager in the HAI system. Spawned when a new SAFE is created from the SAFE Manager, this contract communicates directly with the SAFE Engine from its unique address, to grant the SAFE Manager authorization to manage its corresponding SAFE, allowing for simplified user interactions and enhanced security. Essentially, each SAFE Handler represents a single-collateral SAFE and is managed by the SAFE Manager, which also controls any further authorizations for it.
User Authorization
The SAFE Manager Contract allows users to specify which addresses are authorized to interact with their SAFEs. This is crucial for advanced users who may want to deploy automated strategies via external smart contracts or trusted third parties.
SAFE Ownership Transfer
One unique feature is the ability to transfer ownership of a SAFE to another address. This facilitates a range of possibilities, including the sale of debt positions or the use of SAFEs in more complex financial products.
By providing a more accessible interface to the underlying SAFE Engine, the SAFE Manager Contract is an essential tool for anyone looking to interact with SAFEs in the HAI ecosystem.
SAFE Protection
SAFE owners can choose to connect a SafeSaviour position in order to improve the SAFE health and protect it from liquidation. When the SAFE is on the process of being liquidated, the SafeSaviour contract will unwind the user's position, in order to either reduce the SAFE debt, or increase its collateral, to improve the SAFE health and try to prevent liquidation.
SAFE owners need to account that the SafeSaviour position is connected to the SAFE id, so when transferring ownership to another account, it is responsibility of the previous owner to disconnect any liquidity deposited in the SafeSaviour contract.
4. Gotchas
5. Failure Modes
❱ Actions
The Actions Contract streamlines this process by offering a collection of pre-defined "actions" or methods that can be called through a proxy contract. These actions can then be combined into a single, atomic transaction, saving both time and cost.
Basic Actions
See BasicActions.sol for more details.
1. Introduction
These actions encapsulate all functionalities needed for the comprehensive management of Single-Collateral SAFEs within the SAFE Engine. Whether you're aiming to open, modify, or close SAFEs, Basic Actions provide the modular and gas-efficient methods to achieve your goals.
The scope of these Actions is to provide the user with a set of methods to interact with the SAFE Manager Contract. These methods are used by the HAI Proxy contract to execute the corresponding operations on the SAFE Engine.
2. Contract Details
Key Methods:
openSAFE
: Creates a new SAFEHandler (associated with a collateral type) and registers it in the SAFE Manager.generateDebt
: Generates debt within a SAFE and transfers the generated coins to the user's address.lockTokenCollateral
: Locks a certain amount of tokens as collateral within a SAFE.freeTokenCollateral
: Frees a certain amount of tokens from a SAFE's collateral, and transfers them to the user's address.repayAllDebt
: Repays all debt within a SAFE (the amount of debt to repay is automatically calculated).
3. Key Mechanisms & Concepts
Key Concepts for SAFE Management
Managing Single-Collateral SAFEs involves a series of actions to effectively handle your collateral and debt. In this context, four core concepts—Lock, Free, Collect, and Exit—play a pivotal role. These actions are integrated into the Basic Actions module, simplifying the interaction with the SAFE Manager Contract and the SAFE Engine. Here's a closer look at each:
- LOCK: Deposit collateral into a specified SAFE. This effectively "locks" your assets within the SAFE, providing the foundation upon which you can draw debt. It's the starting point for leveraging your assets within the SAFE ecosystem.
- FREE: The inverse of "Lock." It lets you withdraw or "release" collateral from a SAFE back to your designated address, given that you meet the SAFE's conditions (e.g., maintaining a specific collateral ratio).
- COLLECT: The "Collect" action is used to transfer collateral from an external address into the proxy contract. This is generally a preparatory step for other actions, such as "Lock," where the collateral will be moved from the proxy to the SAFE.
- EXIT: The "Exit" action allows you to burn the internal representation of collateral in exchange for ERC20 tokens, which are transferred to your own address. This action is often used when you wish to exit the SAFE ecosystem and convert your assets back to a fungible, transferable form.
4. Gotchas
Internal Balances of the User
In proxy-based systems designed for asset management, the internal balances within the proxy contract are often automatically reset to zero after each transaction. This is because actions are configured to "exit" or transfer any remaining coins or tokens back to the user's own wallet. The design serves dual purposes: it enhances security by not leaving residual assets exposed in the proxy contract, and it simplifies user experience by allowing users to see their complete asset balances directly in their own accounts. Thus, if you observe that the internal balances of your proxy contract are consistently zero, it's because the system is purposefully designed to "exit" any remaining assets, ensuring that no residual value is left lingering within the proxy.
5. Failure Modes
Rewarded Actions
See RewardedActions.sol for more details.
1. Introduction
Maintaining the protocol's overall health often involves executing key maintenance methods. To incentivize these interactions, the Rewarded Actions Contract exists as a specialized layer that batches transactions for interacting with Jobs contracts. These Jobs contracts offer rewards to users for successfully calling specific maintenance methods critical to the protocol. By consolidating these calls into batch transactions via the Rewarded Actions Contract, users can more efficiently earn rewards while aiding in the protocol's upkeep.
2. Contract Details
Key Methods:
startDebtAuction
: Starts a debt auction.startSurplusAction
: Starts a surplus auction.popDebtFromQueue
: Pops a debt block from the Accounting Engine's queue.transferExtraSurplus
: Transfers surplus (instead of auctioning it).liquidateSAFE
: Liquidates a SAFE.updateCollateralPrice
: Fether the latest price for a collateral type to update the system.updateRedemptionRate
: Triggers the redemption rate to be updated.
3. Key Mechanisms & Concepts
Payment Flow
In the HAI ecosystem, when users interact with Jobs contracts for performing key maintenance tasks, the rewards for these actions come from the Stability Fee Treasury. Upon successful execution of a job, the treasury transfers these rewards internally to the user's account within the protocol. Following this, a proxy action is triggered, designed specifically to "burn" these internal coins. This burning process essentially converts the internal balance into ERC20 HAI tokens, which are then withdrawn to the user's external wallet. Thus, the process seamlessly ensures that users are rewarded in a liquid form of HAI tokens that can be freely used or traded.
4. Gotchas
5. Failure Modes
Bidding Actions
See CollateralBidActions.sol, DebtBidActions.sol, SurplusBidActions.sol and PostSettlementSurplusBidActions.sol for more details.
1. Introduction
These contracts serve as the interaction layer between users and the auction houses responsible for handling collateral liquidations, debt auctions, and surplus auctions respectively.
2. Contract Details
Key Methods:
buyCollateral
: Allows users to bid on collateral auctions.decreaseSoldAmount
: Allows users to bid on debt auctions.increaseBidSize
: Allows users to bid on surplus auctions.settleAuction
: Settles an auction and withraws the corresponding funds to the user's account.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
Settlement Actions
See GlobalSettlementActions.sol for more details.
1. Introduction
Following a Global Settlement, the Settlement Actions Contract plays a critical role by batching essential transactions needed to interact with the protocol. This contract simplifies user interactions and boosts efficiency by consolidating multiple calls into one, easing the transition to the system's final state. Whether claiming collateral or finalizing debts, the Settlement Actions Contract is the go-to mechanism for all post-settlement activities.
2. Contract Details
Key Methods:
freeCollateral
: Allows users to claim their remaining collateral after a SAFE was processed.prepareCoinsForRedeeming
: Deposits system coins for them to be later redeemed.redeemCollateral
: Claims the corresponding collateral for a given amount of system coins deposited.
3. Key Mechanisms & Concepts
4. Gotchas
5. Failure Modes
Contents
- factories
- for-test
- governance
- jobs
- oracles
- proxies
- settlement
- tokens
- utils
- AccountingEngine
- CollateralAuctionHouse
- DebtAuctionHouse
- LiquidationEngine
- OracleRelayer
- PIDController
- PIDRateSetter
- SAFEEngine
- StabilityFeeTreasury
- SurplusAuctionHouse
- TaxCollector
Contents
- AuthorizableChild
- BeefyVeloVaultRelayerChild
- BeefyVeloVaultRelayerFactory
- ChainlinkRelayerChild
- ChainlinkRelayerFactory
- CollateralAuctionHouseChild
- CollateralAuctionHouseFactory
- CollateralJoinChild
- CollateralJoinDelegatableChild
- CollateralJoinFactory
- DelayedOracleChild
- DelayedOracleFactory
- DenominatedOracleChild
- DenominatedOracleFactory
- DisableableChild
- FactoryChild
- UniV3RelayerChild
- UniV3RelayerFactory
AuthorizableChild
Inherits: Authorizable, FactoryChild, IAuthorizableChild
This abstract contract is used to handle Authorizable children contracts through a parent factory
To give permissions to all children contracts, add authorization on the parent factory
To give permissions to a specific child contract, add authorization on the child contract
Functions
_isAuthorized
Method override to check for authorization also in the parent factory
function _isAuthorized(address _account) internal view virtual override returns (bool _authorized);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to check authorization for |
Returns
Name | Type | Description |
---|---|---|
_authorized | bool | Whether the account is authorized either in contract or in factory |
BeefyVeloVaultRelayerChild
Inherits: BeefyVeloVaultRelayer, FactoryChild, IBeefyVeloVaultRelayerChild
This contract inherits all the functionality of BeefyVeloVaultRelayer to be factory deployed
Functions
constructor
constructor(
IBaseOracle _token0priceSource,
IBaseOracle _token1priceSource,
IBeefyVaultV7 _beefyVault,
IVeloPool _veloPool
) BeefyVeloVaultRelayer(_token0priceSource, _token1priceSource, _beefyVault, _veloPool);
Parameters
Name | Type | Description |
---|---|---|
_token0priceSource | IBaseOracle | Address of the price source for the first token in the velo pool |
_token1priceSource | IBaseOracle | Address of the price source for the second token in the velo pool |
_beefyVault | IBeefyVaultV7 | The address of the beefy vault contract |
_veloPool | IVeloPool | The address of the velo pool underlying the beefy vault |
BeefyVeloVaultRelayerFactory
Inherits: Authorizable, IBeefyVeloVaultRelayerFactory
This contract is used to deploy BeefyVeloVaultRelayer contracts
The deployed contracts are BeefyVeloVaultRelayerChild instances
State Variables
_beefyVeloVaultRelayers
The enumerable set of deployed BeefyVeloVaultRelayer contracts
EnumerableSet.AddressSet internal _beefyVeloVaultRelayers;
Functions
constructor
constructor() Authorizable(msg.sender);
deployBeefyVeloVaultRelayer
Deploys a new BeefyVeloVaultRelayer contract
function deployBeefyVeloVaultRelayer(
IBaseOracle _token0priceSource,
IBaseOracle _token1priceSource,
IBeefyVaultV7 _beefyVault,
IVeloPool _veloPool
) external isAuthorized returns (IBaseOracle _beefyVeloVaultRelayer);
Parameters
Name | Type | Description |
---|---|---|
_token0priceSource | IBaseOracle | Address of the price source for the first token in the velo pool |
_token1priceSource | IBaseOracle | Address of the price source for the second token in the velo pool |
_beefyVault | IBeefyVaultV7 | The address of the beefy vault contract |
_veloPool | IVeloPool | The address of the velo pool underlying the beefy vault |
Returns
Name | Type | Description |
---|---|---|
_beefyVeloVaultRelayer | IBaseOracle | Address of the deployed BeefyVeloVaultRelayer contract |
beefyVeloVaultRelayersList
Getter for the list of BeefyVeloVaultRelayer contracts
function beefyVeloVaultRelayersList() external view returns (address[] memory _beefyVeloVaultRelayersList);
Returns
Name | Type | Description |
---|---|---|
_beefyVeloVaultRelayersList | address[] | List of BeefyVeloVaultRelayer contracts |
ChainlinkRelayerChild
Inherits: ChainlinkRelayer, FactoryChild, IChainlinkRelayerChild
This contract inherits all the functionality of ChainlinkRelayer to be factory deployed
Functions
constructor
constructor(
address _priceFeed,
address __sequencerUptimeFeed,
uint256 _staleThreshold
) ChainlinkRelayer(_priceFeed, __sequencerUptimeFeed, _staleThreshold);
Parameters
Name | Type | Description |
---|---|---|
_priceFeed | address | The address of the price feed to relay |
__sequencerUptimeFeed | address | The address of the sequencer uptime feed to relay |
_staleThreshold | uint256 | The threshold in seconds to consider the aggregator stale |
sequencerUptimeFeed
function sequencerUptimeFeed()
public
view
override(ChainlinkRelayer, IChainlinkRelayer)
returns (IChainlinkOracle __sequencerUptimeFeed);
_setSequencerUptimeFeed
Sets the Chainlink sequencer uptime feed contract address
Modifying sequencerUptimeFeed's address results in a no-operation (is read from factory)
function _setSequencerUptimeFeed(address __sequencerUptimeFeed) internal override;
Parameters
Name | Type | Description |
---|---|---|
__sequencerUptimeFeed | address | Ignored parameter (read from factory) |
ChainlinkRelayerFactory
Inherits: Authorizable, IChainlinkRelayerFactory
This contract is used to deploy ChainlinkRelayer contracts
The deployed contracts are ChainlinkRelayerChild instances
State Variables
sequencerUptimeFeed
Address of the Chainlink sequencer uptime feed used to consult the sequencer status
IChainlinkOracle public sequencerUptimeFeed;
_chainlinkRelayers
The enumerable set of deployed ChainlinkRelayer contracts
EnumerableSet.AddressSet internal _chainlinkRelayers;
Functions
constructor
constructor(address _sequencerUptimeFeed) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_sequencerUptimeFeed | address | The address of the Chainlink sequencer uptime feed |
deployChainlinkRelayer
Deploys a new ChainlinkRelayer contract
function deployChainlinkRelayer(
address _priceFeed,
uint256 _staleThreshold
) external isAuthorized returns (IBaseOracle _chainlinkRelayer);
Parameters
Name | Type | Description |
---|---|---|
_priceFeed | address | Address of the price feed to be used by the ChainlinkRelayer contract |
_staleThreshold | uint256 | Stale threshold to be used by the ChainlinkRelayer contract |
Returns
Name | Type | Description |
---|---|---|
_chainlinkRelayer | IBaseOracle | Address of the deployed ChainlinkRelayer contract |
chainlinkRelayersList
Getter for the list of ChainlinkRelayer contracts
function chainlinkRelayersList() external view returns (address[] memory _chainlinkRelayersList);
Returns
Name | Type | Description |
---|---|---|
_chainlinkRelayersList | address[] | List of ChainlinkRelayer contracts |
setSequencerUptimeFeed
Sets the Chainlink sequencer uptime feed contract address
function setSequencerUptimeFeed(address _sequencerUptimeFeed) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_sequencerUptimeFeed | address | The address of the Chainlink sequencer uptime feed |
_setSequencerUptimeFeed
function _setSequencerUptimeFeed(address _sequencerUptimeFeed) internal;
CollateralAuctionHouseChild
Inherits: DisableableChild, AuthorizableChild, CollateralAuctionHouse, ICollateralAuctionHouseChild
This contract inherits all the functionality of CollateralAuctionHouse to be factory deployed
Functions
constructor
constructor(
address _safeEngine,
address _liquidationEngine,
address _oracleRelayer,
bytes32 _cType,
CollateralAuctionHouseParams memory _cahParams
) CollateralAuctionHouse(_safeEngine, _liquidationEngine, _oracleRelayer, _cType, _cahParams);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_liquidationEngine | address | Ignored parameter (read from factory) |
_oracleRelayer | address | Ignored parameter (read from factory) |
_cType | bytes32 | Bytes32 representation of the collateral type |
_cahParams | CollateralAuctionHouseParams | Initial valid CollateralAuctionHouse parameters struct |
liquidationEngine
Address of the LiquidationEngine contract
Overriding method reads liquidationEngine from factory
function liquidationEngine()
public
view
override(CollateralAuctionHouse, ICollateralAuctionHouse)
returns (ILiquidationEngine _liquidationEngine);
oracleRelayer
Address of the OracleRelayer contract
Overriding method reads oracleRelayer from factory
function oracleRelayer()
public
view
override(CollateralAuctionHouse, ICollateralAuctionHouse)
returns (IOracleRelayer _oracleRelayer);
_setLiquidationEngine
Modifying liquidationEngine's address results in a no-operation (is read from factory)
function _setLiquidationEngine(address _newLiquidationEngine) internal override;
Parameters
Name | Type | Description |
---|---|---|
_newLiquidationEngine | address | Ignored parameter (read from factory) |
_setOracleRelayer
Modifying oracleRelayer's address results in a no-operation (is read from factory)
function _setOracleRelayer(address _newOracleRelayer) internal override;
Parameters
Name | Type | Description |
---|---|---|
_newOracleRelayer | address | Ignored parameter (read from factory) |
_isAuthorized
Method override to check for authorization also in the parent factory
function _isAuthorized(address _account)
internal
view
override(AuthorizableChild, Authorizable)
returns (bool _authorized);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to check authorization for |
Returns
Name | Type | Description |
---|---|---|
_authorized | bool | Whether the account is authorized either in contract or in factory |
_isEnabled
Method override to check for contract enablement also in the parent factory
function _isEnabled() internal view override(DisableableChild, Disableable) returns (bool _enabled);
Returns
Name | Type | Description |
---|---|---|
_enabled | bool | Whether the contract and the factory are enabled or not |
_onContractDisable
Method override to allow disabling contract only through the parent factory
function _onContractDisable() internal override(DisableableChild, Disableable);
CollateralAuctionHouseFactory
Inherits: Authorizable, Modifiable, ModifiablePerCollateral, Disableable, ICollateralAuctionHouseFactory
This contract is used to deploy CollateralAuctionHouse contracts
The deployed contracts are CollateralAuctionHouseChild instances
State Variables
safeEngine
Address of the SAFEEngine contract
address public safeEngine;
liquidationEngine
Address of the LiquidationEngine contract
address public liquidationEngine;
oracleRelayer
Address of the OracleRelayer contract
address public oracleRelayer;
collateralAuctionHouses
Getter for the address of the CollateralAuctionHouse contract associated with a collateral type
mapping(bytes32 _cType => address) public collateralAuctionHouses;
Functions
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType)
external
view
returns (ICollateralAuctionHouse.CollateralAuctionHouseParams memory _cahParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_cahParams | ICollateralAuctionHouse.CollateralAuctionHouseParams | CollateralAuctionHouse parameters struct |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType)
external
view
returns (uint256 _minimumBid, uint256 _minDiscount, uint256 _maxDiscount, uint256 _perSecondDiscountUpdateRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_minimumBid | uint256 | Minimum bid for the collateral auctions [wad] |
_minDiscount | uint256 | Minimum discount for the collateral auctions [wad %] |
_maxDiscount | uint256 | Maximum discount for the collateral auctions [wad %] |
_perSecondDiscountUpdateRate | uint256 | Per second rate at which the discount is updated [ray] |
constructor
Adds authorization to the LiquidationEngine (extended to all child contracts)
constructor(
address _safeEngine,
address _liquidationEngine,
address _oracleRelayer
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_liquidationEngine | address | Address of the LiquidationEngine contract |
_oracleRelayer | address | Address of the OracleRelayer contract |
collateralAuctionHousesList
Getter for the list of CollateralAuctionHouse contracts
function collateralAuctionHousesList() external view returns (address[] memory _collateralAuctionHousesList);
Returns
Name | Type | Description |
---|---|---|
_collateralAuctionHousesList | address[] | _collateralAuctionHouses List of CollateralAuctionHouse contracts |
_initializeCollateralType
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal override whenEnabled;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_setLiquidationEngine
Sets the LiquidationEngine contract address, revoking the previous, and granting the new one authorization
function _setLiquidationEngine(address _newLiquidationEngine) internal;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
CollateralJoinChild
Inherits: CollateralJoin, DisableableChild, ICollateralJoinChild
This contract inherits all the functionality of CollateralJoin to be factory deployed
Functions
constructor
constructor(address _safeEngine, bytes32 _cType, address _collateral) CollateralJoin(_safeEngine, _cType, _collateral);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SafeEngine contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20 collateral token |
_isEnabled
Method override to check for contract enablement also in the parent factory
function _isEnabled() internal view override(DisableableChild, Disableable) returns (bool _enabled);
Returns
Name | Type | Description |
---|---|---|
_enabled | bool | Whether the contract and the factory are enabled or not |
_onContractDisable
Method override to allow disabling contract only through the parent factory
function _onContractDisable() internal override(DisableableChild, Disableable);
CollateralJoinDelegatableChild
Inherits: CollateralJoinChild, ICollateralJoinDelegatableChild
This contract inherits all the functionality of CollateralJoin to be factory deployed and adds a ERC20Votes delegation
For well behaved ERC20Votes tokens with less than 18 decimals
State Variables
delegatee
Address to whom the voting power is delegated
address public delegatee;
Functions
constructor
constructor(
address _safeEngine,
bytes32 _cType,
address _collateral,
address _delegatee
) CollateralJoinChild(_safeEngine, _cType, _collateral);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SafeEngine contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20Votes collateral token |
_delegatee | address | Address to whom the voting power is delegated |
CollateralJoinFactory
Inherits: Authorizable, Disableable, ICollateralJoinFactory
This contract is used to deploy CollateralJoin contracts
The deployed contracts are CollateralJoinChild or CollateralJoinDelegatableChild instances
State Variables
safeEngine
Address of the SAFEEngine contract
address public safeEngine;
_collateralTypes
The enumerable set of deployed CollateralJoin contracts
EnumerableSet.Bytes32Set internal _collateralTypes;
collateralJoins
Getter for the address of the CollateralJoin contract associated with a collateral type
mapping(bytes32 _cType => address _collateralJoin) public collateralJoins;
Functions
constructor
constructor(address _safeEngine) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
deployCollateralJoin
Deploys a CollateralJoinChild contract
function deployCollateralJoin(
bytes32 _cType,
address _collateral
) external isAuthorized whenEnabled returns (ICollateralJoin _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20 collateral token |
Returns
Name | Type | Description |
---|---|---|
_collateralJoin | ICollateralJoin | Address of the deployed CollateralJoinChild contract |
deployDelegatableCollateralJoin
Deploys a CollateralJoinDelegatableChild contract
function deployDelegatableCollateralJoin(
bytes32 _cType,
address _collateral,
address _delegatee
) external isAuthorized whenEnabled returns (ICollateralJoin _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20Votes collateral token |
_delegatee | address | Address to whom the deployed child will delegate the voting power to |
Returns
Name | Type | Description |
---|---|---|
_collateralJoin | ICollateralJoin | Address of the deployed CollateralJoinDelegatableChild contract |
disableCollateralJoin
Disables a CollateralJoin contract and removes it from the collateral types list
Allows the deployment of other CollateralJoin contract for the same collateral type
function disableCollateralJoin(bytes32 _cType) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
collateralTypesList
Getter for the list of collateral types
function collateralTypesList() external view returns (bytes32[] memory _collateralTypesList);
Returns
Name | Type | Description |
---|---|---|
_collateralTypesList | bytes32[] | List of collateral types |
collateralJoinsList
Getter for the list of CollateralJoin contracts
function collateralJoinsList() external view returns (address[] memory _collateralJoinsList);
Returns
Name | Type | Description |
---|---|---|
_collateralJoinsList | address[] | List of CollateralJoin contracts |
DelayedOracleChild
Inherits: DelayedOracle, FactoryChild, IDelayedOracleChild
This contract inherits all the functionality of DelayedOracle to be factory deployed
Functions
constructor
constructor(IBaseOracle _priceSource, uint256 _updateDelay) DelayedOracle(_priceSource, _updateDelay);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source |
_updateDelay | uint256 | Amount of seconds to be applied between the price source and the delayed oracle feeds |
DelayedOracleFactory
Inherits: Authorizable, IDelayedOracleFactory
This contract is used to deploy DelayedOracle contracts
The deployed contracts are DelayedOracleChild instances
State Variables
_delayedOracles
The enumerable set of deployed DelayedOracle contracts
EnumerableSet.AddressSet internal _delayedOracles;
Functions
constructor
constructor() Authorizable(msg.sender);
deployDelayedOracle
Deploys a new DelayedOracle contract
function deployDelayedOracle(
IBaseOracle _priceSource,
uint256 _updateDelay
) external isAuthorized returns (IDelayedOracle _delayedOracle);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source for the DelayedOracle contract |
_updateDelay | uint256 | Delay in seconds to be applied between the price source and the delayed oracle feeds |
Returns
Name | Type | Description |
---|---|---|
_delayedOracle | IDelayedOracle | Address of the deployed DelayedOracle contract |
delayedOraclesList
Getter for the list of DelayedOracle contracts
function delayedOraclesList() external view returns (address[] memory _delayedOraclesList);
Returns
Name | Type | Description |
---|---|---|
_delayedOraclesList | address[] | List of DelayedOracle contracts |
DenominatedOracleChild
Inherits: DenominatedOracle, FactoryChild, IDenominatedOracleChild
This contract inherits all the functionality of DenominatedOracle to be factory deployed
Functions
constructor
constructor(
IBaseOracle _priceSource,
IBaseOracle _denominationPriceSource,
bool _inverted
) DenominatedOracle(_priceSource, _denominationPriceSource, _inverted);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source |
_denominationPriceSource | IBaseOracle | Address of the denomination price source |
_inverted | bool | Boolean indicating if the denomination quote should be inverted |
DenominatedOracleFactory
Inherits: Authorizable, IDenominatedOracleFactory
This contract is used to deploy DenominatedOracle contracts
The deployed contracts are DenominatedOracleChild instances
State Variables
_denominatedOracles
The enumerable set of deployed DenominatedOracle contracts
EnumerableSet.AddressSet internal _denominatedOracles;
Functions
constructor
constructor() Authorizable(msg.sender);
deployDenominatedOracle
Deploys a new DenominatedOracle contract
The denomination quote should follow the format: (A / B) * (B / C) = A / C
function deployDenominatedOracle(
IBaseOracle _priceSource,
IBaseOracle _denominationPriceSource,
bool _inverted
) external isAuthorized returns (IBaseOracle _denominatedOracle);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source for the DenominatedOracle contract |
_denominationPriceSource | IBaseOracle | Address of the denomination price source for the DenominatedOracle contract |
_inverted | bool | Boolean indicating if the denomination calculation quote should be inverted |
Returns
Name | Type | Description |
---|---|---|
_denominatedOracle | IBaseOracle | Address of the deployed DenominatedOracle contract |
denominatedOraclesList
Getter for the list of DenominatedOracle contracts
function denominatedOraclesList() external view returns (address[] memory _denominatedOraclesList);
Returns
Name | Type | Description |
---|---|---|
_denominatedOraclesList | address[] | List of DenominatedOracle contracts |
DisableableChild
Inherits: Disableable, FactoryChild, IDisableableChild
This abstract contract is used to disable Disableable children contracts through a parent factory
Functions
_isEnabled
Internal virtual view to check if the contract is enabled
Method override to check for contract enablement also in the parent factory
function _isEnabled() internal view virtual override returns (bool _enabled);
Returns
Name | Type | Description |
---|---|---|
_enabled | bool | Whether the contract and the factory are enabled or not |
_onContractDisable
Internal virtual method to be called when the contract is disabled
Method override to allow disabling contract only through the parent factory
function _onContractDisable() internal virtual override onlyFactory;
FactoryChild
Inherits: IFactoryChild
This abstract contract adds a factory address and modifier to the inheriting contract
State Variables
factory
Getter for the address of the factory that deployed the inheriting contract
address public factory;
Functions
constructor
Verifies that the contract is being deployed by a contract address
constructor();
onlyFactory
Verifies that the caller is the factory
modifier onlyFactory();
UniV3RelayerChild
Inherits: UniV3Relayer, FactoryChild, IUniV3RelayerChild
This contract inherits all the functionality of UniV3Relayer to be factory deployed
Functions
constructor
constructor(
address _uniV3Factory,
address _baseToken,
address _quoteToken,
uint24 _feeTier,
uint32 _quotePeriod
) UniV3Relayer(_uniV3Factory, _baseToken, _quoteToken, _feeTier, _quotePeriod);
Parameters
Name | Type | Description |
---|---|---|
_uniV3Factory | address | |
_baseToken | address | Address of the base token to be quoted |
_quoteToken | address | Address of the quote reference token |
_feeTier | uint24 | Fee tier used to identify the UniV3 pool |
_quotePeriod | uint32 | Length of the period used to calculate the TWAP quote |
UniV3RelayerFactory
Inherits: Authorizable, IUniV3RelayerFactory
This contract is used to deploy UniV3Relayer contracts
The deployed contracts are UniV3RelayerChild instances
State Variables
_UNI_V3_FACTORY
Address of the UniswapV3Factory used to fetch the pool address
address internal immutable _UNI_V3_FACTORY;
_uniV3Relayers
The enumerable set of deployed UniV3Relayer contracts
EnumerableSet.AddressSet internal _uniV3Relayers;
Functions
constructor
constructor(address _uniV3Factory) Authorizable(msg.sender);
deployUniV3Relayer
Deploys a new UniV3Relayer contract
function deployUniV3Relayer(
address _baseToken,
address _quoteToken,
uint24 _feeTier,
uint32 _quotePeriod
) external isAuthorized returns (IBaseOracle _uniV3Relayer);
Parameters
Name | Type | Description |
---|---|---|
_baseToken | address | Address of the base token to be quoted |
_quoteToken | address | Address of the quote reference token |
_feeTier | uint24 | Fee tier used to identify the UniV3 pool |
_quotePeriod | uint32 | Length of the period used to calculate the TWAP quote |
Returns
Name | Type | Description |
---|---|---|
_uniV3Relayer | IBaseOracle | Address of the deployed UniV3Relayer contract |
uniV3RelayersList
Getter for the list of UniV3Relayer contracts
function uniV3RelayersList() external view returns (address[] memory _uniV3RelayersList);
Returns
Name | Type | Description |
---|---|---|
_uniV3RelayersList | address[] | List of UniV3Relayer contracts |
Contents
DeviatedOracle
Inherits: IBaseOracle
This oracle is used to simulate a price source that returns a price deviated from the redemption price
State Variables
deviation
The proportional deviation from the redemption price [wad %]
uint256 public deviation;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
oracleRelayer
The oracle relayer contract
IOracleRelayer public oracleRelayer;
Functions
constructor
constructor(string memory _symbol, address _oracleRelayer, uint256 _deviation);
Parameters
Name | Type | Description |
---|---|---|
_symbol | string | The symbol of the oracle |
_oracleRelayer | address | The address of the oracle relayer contract |
_deviation | uint256 | The proportional deviation from the redemption price [wad %] |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _price, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _price);
HardcodedOracle
Inherits: IBaseOracle
This oracle is used to simulate a price source that returns a hardcoded price
State Variables
price
The hardcoded price the oracle returns [wad]
uint256 public price;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
Functions
constructor
constructor(string memory _symbol, uint256 _price);
Parameters
Name | Type | Description |
---|---|---|
_symbol | string | The symbol of the oracle |
_price | uint256 | The hardcoded price the oracle returns [wad] |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _price, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _value);
MintableERC20
Inherits: IERC20Metadata, ERC20
This ERC20 contract is used for testing purposes, to allow users to mint tokens
State Variables
_decimals
The number of decimals the token uses
uint8 internal _decimals;
Functions
constructor
constructor(string memory _name, string memory _symbol, uint8 __decimals) ERC20(_name, _symbol);
Parameters
Name | Type | Description |
---|---|---|
_name | string | The name of the ERC20 token |
_symbol | string | The symbol of the ERC20 token |
__decimals | uint8 | The number of decimals the token uses |
decimals
function decimals() public view virtual override(ERC20, IERC20Metadata) returns (uint8 __decimals);
mint
Mint tokens to the caller
The minting amount is capped to uint192 to avoid overflowing supply
function mint(uint256 _wei) external;
Parameters
Name | Type | Description |
---|---|---|
_wei | uint256 | The amount of tokens to mint (in wei representation) |
mint
Mint tokens to the specified user
The minting amount is capped to uint192 to avoid overflowing supply
function mint(address _usr, uint256 _wei) external;
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user to mint tokens to |
_wei | uint256 | The amount of tokens to mint (in wei representation) |
Contents
HaiDelegatee
Inherits: IHaiDelegatee, Ownable
This contract is used to proxy the voting power delegated to it to a delegatee
Compatible with OpenZeppelin's Governor contract
State Variables
delegatee
Get the address of the delegatee of the contract
address public delegatee;
Functions
constructor
constructor(address _owner) Ownable(_owner);
setDelegatee
Set the delegatee of the contract
function setDelegatee(address _delegatee) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_delegatee | address | The address of the new delegatee |
castVote
Cast a vote using the voting power delegated to this contract
function castVote(
IGovernor _governor,
uint256 _proposalId,
uint8 _support
) public onlyDelegatee returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
Returns
Name | Type | Description |
---|---|---|
_weight | uint256 | The weight of the vote |
castVoteWithReason
Cast a vote with reason using the voting power delegated to this contract
function castVoteWithReason(
IGovernor _governor,
uint256 _proposalId,
uint8 _support,
string memory _reason
) public onlyDelegatee returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
_reason | string | The reason for the vote |
Returns
Name | Type | Description |
---|---|---|
_weight | uint256 | The weight of the vote |
castVoteWithReasonAndParams
Cast a vote with reason and params using the voting power delegated to this contract
function castVoteWithReasonAndParams(
IGovernor _governor,
uint256 _proposalId,
uint8 _support,
string memory _reason,
bytes memory _params
) public onlyDelegatee returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
_reason | string | The reason for the vote |
_params | bytes | The params for the vote |
onlyDelegatee
modifier onlyDelegatee();
HaiGovernor
Inherits: Governor, GovernorSettings, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorPreventLateQuorum, GovernorTimelockControl
This contract implements OpenZeppelin's Governor contract overriding the clock to use block.timestamp
Functions
constructor
constructor(
IVotes _token,
string memory _governorName,
IHaiGovernor.HaiGovernorParams memory _params
)
Governor(_governorName)
GovernorSettings(_params.votingDelay, _params.votingPeriod, _params.proposalThreshold)
GovernorVotes(_token)
GovernorVotesQuorumFraction(_params.quorumNumeratorValue)
GovernorPreventLateQuorum(_params.quorumVoteExtension)
GovernorTimelockControl(
new TimelockController(_params.timelockMinDelay, new address[](0), new address[](0), address(this))
);
clock
Set the clock to block timestamp, as opposed to the default block number
function clock() public view override(Governor, GovernorVotes) returns (uint48 _timestamp);
CLOCK_MODE
function CLOCK_MODE() public view virtual override(Governor, GovernorVotes) returns (string memory _mode);
_cancel
The following functions are overrides required by Solidity
function _cancel(
address[] memory _targets,
uint256[] memory _values,
bytes[] memory _calldatas,
bytes32 _descriptionHash
) internal override(Governor, GovernorTimelockControl) returns (uint256 _proposalId);
_executeOperations
function _executeOperations(
uint256 _proposalId,
address[] memory _targets,
uint256[] memory _values,
bytes[] memory _calldatas,
bytes32 _descriptionHash
) internal override(Governor, GovernorTimelockControl);
_executor
function _executor() internal view override(Governor, GovernorTimelockControl) returns (address _addy);
_queueOperations
function _queueOperations(
uint256 _proposalId,
address[] memory _targets,
uint256[] memory _values,
bytes[] memory _calldatas,
bytes32 _descriptionHash
) internal override(Governor, GovernorTimelockControl) returns (uint48 _scheduledTime);
proposalNeedsQueuing
function proposalNeedsQueuing(uint256 _proposalId)
public
view
override(Governor, GovernorTimelockControl)
returns (bool _needsQueuing);
proposalThreshold
function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256 _threshold);
state
function state(uint256 _proposalId)
public
view
override(Governor, GovernorTimelockControl)
returns (ProposalState _state);
_castVote
function _castVote(
uint256 _proposalId,
address _account,
uint8 _support,
string memory _reason,
bytes memory _params
) internal override(Governor, GovernorPreventLateQuorum) returns (uint256 _voteId);
proposalDeadline
function proposalDeadline(uint256 _proposalId)
public
view
override(Governor, GovernorPreventLateQuorum)
returns (uint256 _deadline);
Contents
AccountingJob
Inherits: Authorizable, Modifiable, Job, IAccountingJob
This contract contains rewarded methods to handle the accounting engine debt and surplus
State Variables
shouldWorkPopDebtFromQueue
Whether the pop debt from queue job should be worked
bool public shouldWorkPopDebtFromQueue;
shouldWorkAuctionDebt
Whether the auction debt job should be worked
bool public shouldWorkAuctionDebt;
shouldWorkAuctionSurplus
Whether the auction surplus job should be worked
bool public shouldWorkAuctionSurplus;
shouldWorkTransferExtraSurplus
Whether the transfer extra surplus job should be worked
bool public shouldWorkTransferExtraSurplus;
accountingEngine
Address of the AccountingEngine contract
IAccountingEngine public accountingEngine;
Functions
constructor
constructor(
address _accountingEngine,
address _stabilityFeeTreasury,
uint256 _rewardAmount
) Job(_stabilityFeeTreasury, _rewardAmount) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_accountingEngine | address | Address of the AccountingEngine contract |
_stabilityFeeTreasury | address | Address of the StabilityFeeTreasury contract |
_rewardAmount | uint256 | Amount of tokens to reward per job transaction [wad] |
workPopDebtFromQueue
Rewarded method to pop debt from the AccountingEngine's queue
function workPopDebtFromQueue(uint256 _debtBlockTimestamp) external reward;
Parameters
Name | Type | Description |
---|---|---|
_debtBlockTimestamp | uint256 | Timestamp of the debt block to pop |
workAuctionDebt
Rewarded method to auction debt from the AccountingEngine
function workAuctionDebt() external reward;
workAuctionSurplus
Rewarded method to auction surplus from the AccountingEngine
function workAuctionSurplus() external reward;
workTransferExtraSurplus
Rewarded method to transfer surplus from the AccountingEngine
function workTransferExtraSurplus() external reward;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override(Modifiable, Job);
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override(Modifiable, Job);
Job
Inherits: Authorizable, Modifiable, IJob
This abstract contract is inherited by all jobs to add a reward modifier
State Variables
rewardAmount
Amount of tokens to reward per job transaction [wad]
uint256 public rewardAmount;
stabilityFeeTreasury
Address of the StabilityFeeTreasury contract
IStabilityFeeTreasury public stabilityFeeTreasury;
Functions
constructor
constructor(address _stabilityFeeTreasury, uint256 _rewardAmount);
Parameters
Name | Type | Description |
---|---|---|
_stabilityFeeTreasury | address | Address of the StabilityFeeTreasury contract |
_rewardAmount | uint256 | Amount of tokens to reward per job transaction [wad] |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal virtual override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view virtual override;
reward
Modifier to reward the caller for calling the function
modifier reward();
LiquidationJob
Inherits: Authorizable, Modifiable, Job, ILiquidationJob
This contract contains rewarded methods to handle the SAFE liquidations
State Variables
shouldWork
Whether the liquidation job should be worked
bool public shouldWork;
liquidationEngine
Address of the LiquidationEngine contract
ILiquidationEngine public liquidationEngine;
Functions
constructor
constructor(
address _liquidationEngine,
address _stabilityFeeTreasury,
uint256 _rewardAmount
) Job(_stabilityFeeTreasury, _rewardAmount) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_liquidationEngine | address | Address of the LiquidationEngine contract |
_stabilityFeeTreasury | address | Address of the StabilityFeeTreasury contract |
_rewardAmount | uint256 | Amount of tokens to reward per job transaction [wad] |
workLiquidation
Rewarded method to liquidate a SAFE
function workLiquidation(bytes32 _cType, address _safe) external reward;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE to liquidate |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override(Job, Modifiable);
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override(Job, Modifiable);
OracleJob
Inherits: Authorizable, Modifiable, Job, IOracleJob
This contract contains rewarded methods to handle the oracle relayer and the PID rate setter updates
State Variables
shouldWorkUpdateCollateralPrice
Whether the update collateral price job should be worked
bool public shouldWorkUpdateCollateralPrice;
shouldWorkUpdateRate
Whether the update rate job should be worked
bool public shouldWorkUpdateRate;
oracleRelayer
Address of the OracleRelayer contract
IOracleRelayer public oracleRelayer;
pidRateSetter
Address of the PIDRateSetter contract
IPIDRateSetter public pidRateSetter;
Functions
constructor
constructor(
address _oracleRelayer,
address _pidRateSetter,
address _stabilityFeeTreasury,
uint256 _rewardAmount
) Job(_stabilityFeeTreasury, _rewardAmount) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_oracleRelayer | address | Address of the OracleRelayer contract |
_pidRateSetter | address | Address of the PIDRateSetter contract |
_stabilityFeeTreasury | address | Address of the StabilityFeeTreasury contract |
_rewardAmount | uint256 | Amount of tokens to reward per job transaction [wad] |
workUpdateCollateralPrice
Rewarded method to update a collateral price
function workUpdateCollateralPrice(bytes32 _cType) external reward;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
workUpdateRate
Rewarded method to update the redemption rate
function workUpdateRate() external reward;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override(Job, Modifiable);
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override(Job, Modifiable);
Contents
BeefyVeloVaultRelayer
Inherits: IBaseOracle, IBeefyVeloVaultRelayer
Deconstructs a Beefy Vault to it's Velodrome liquidity pool and that pool's constituent tokens to return a price feed
Requires an underlying Velodrome pool and price feeds for the pool's tokens
State Variables
token0priceSource
Address of the token0 price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
IBaseOracle public token0priceSource;
token1priceSource
Address of the token1 price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
IBaseOracle public token1priceSource;
beefyVault
Address of the beefy vault
Assumes that the beefy vault is a valid IBeefyVaultV7
IBeefyVaultV7 public beefyVault;
veloPool
Address of the velo pool underlying the beefy vault
Assumes that the price source is a valid IVeloPool
IVeloPool public veloPool;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
Functions
constructor
constructor(
IBaseOracle _token0priceSource,
IBaseOracle _token1priceSource,
IBeefyVaultV7 _beefyVault,
IVeloPool _veloPool
);
Parameters
Name | Type | Description |
---|---|---|
_token0priceSource | IBaseOracle | Address of the price source for the first token in the velo pool |
_token1priceSource | IBaseOracle | Address of the price source for the second token in the velo pool |
_beefyVault | IBeefyVaultV7 | The address of the beefy vault contract |
_veloPool | IVeloPool | The address of the velo pool underlying the beefy vault |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _result);
_getCombinedPriceValue
Returns the combined price of the two tokens in the velo pool
function _getCombinedPriceValue(
uint256 _token0priceSourceValue,
uint256 _token1priceSourceValue
) internal view returns (uint256 _combinedPriceValue);
ChainlinkRelayer
Inherits: IBaseOracle, IChainlinkRelayer
This contracts transforms a Chainlink price feed into a standard IBaseOracle feed It also verifies that the reading is new enough, compared to a staleThreshold
State Variables
priceFeed
Address of the Chainlink price feed used to consult the price
IChainlinkOracle public priceFeed;
_sequencerUptimeFeed
Internal storage variable to allow overrides in child implementation contract
IChainlinkOracle internal _sequencerUptimeFeed;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
multiplier
The multiplier used to convert the quote into an 18 decimals format
uint256 public multiplier;
staleThreshold
The time threshold after which a Chainlink response is considered stale
uint256 public staleThreshold;
Functions
constructor
constructor(address _priceFeed, address __sequencerUptimeFeed, uint256 _staleThreshold);
Parameters
Name | Type | Description |
---|---|---|
_priceFeed | address | The address of the Chainlink price feed |
__sequencerUptimeFeed | address | The address of the Chainlink sequencer uptime feed |
_staleThreshold | uint256 | The threshold after which the price is considered stale |
sequencerUptimeFeed
Address of the Chainlink sequencer uptime feed used to consult the sequencer status
function sequencerUptimeFeed() public view virtual returns (IChainlinkOracle __sequencerUptimeFeed);
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _result);
_parseResult
Parses the result from the price feed into 18 decimals format
function _parseResult(int256 _feedResult) internal view returns (uint256 _result);
_isValidFeed
Checks if the feed is valid, considering the sequencer status, the staleThreshold and the feed timestamp
function _isValidFeed(uint256 _feedTimestamp) internal view returns (bool _valid);
_setSequencerUptimeFeed
Sets the Chainlink sequencer uptime feed contract address
function _setSequencerUptimeFeed(address __sequencerUptimeFeed) internal virtual;
DelayedOracle
Inherits: IBaseOracle, IDelayedOracle
Transforms a price feed into a delayed price feed with a step function
Requires an external mechanism to call updateResult every updateDelay
seconds
State Variables
priceSource
Address of the non-delayed price source
Assumes that the price source is a valid IBaseOracle
IBaseOracle public priceSource;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
updateDelay
The delay in seconds that should elapse between updates
uint256 public updateDelay;
lastUpdateTime
The timestamp of the last update
uint256 public lastUpdateTime;
_currentFeed
The current valid price feed storage struct
Feed internal _currentFeed;
_nextFeed
The next valid price feed storage struct
Feed internal _nextFeed;
Functions
constructor
constructor(IBaseOracle _priceSource, uint256 _updateDelay);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | The address of the non-delayed price source |
_updateDelay | uint256 | The delay in seconds that should elapse between updates |
updateResult
Updates the current price with the last next price, and reads the next price feed
Will revert if the delay since last update has not elapsed
function updateResult() external returns (bool _success);
Returns
Name | Type | Description |
---|---|---|
_success | bool | Whether the update was successful or not |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _result);
shouldUpdate
Indicates if a delay has passed since the last update
function shouldUpdate() external view returns (bool _ok);
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether the oracle should be updated or not |
getNextResultWithValidity
The next valid price feed, taking effect at the next updateResult call
function getNextResultWithValidity() external view returns (uint256 _result, bool _validity);
Returns
Name | Type | Description |
---|---|---|
_result | uint256 | The value in 18 decimals format of the next price feed |
_validity | bool | Whether the next price feed is valid or not |
_getPriceSourceResult
Internal view function that queries the standard price source
function _getPriceSourceResult() internal view returns (uint256 _priceFeedValue, bool _hasValidValue);
_delayHasElapsed
Internal view function that returns whether the delay between calls has been passed
function _delayHasElapsed() internal view returns (bool _ok);
DenominatedOracle
Inherits: IBaseOracle, IDenominatedOracle
Transforms two price feeds with a shared token into a new denominated price feed between the other two tokens of the feeds
Requires an external base price feed with a shared token between the price source and the denomination price source
State Variables
priceSource
Address of the base price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
IBaseOracle public priceSource;
denominationPriceSource
Address of the base price source that is used to calculate the denominated price
Assumes that the price source is a valid IBaseOracle
IBaseOracle public denominationPriceSource;
symbol
Concatenated symbols of the two price sources used for quoting (e.g. '(WBTC / ETH) * (ETH / USD)')
The order of the symbols must follow a continuous chain of tokens
string public symbol;
inverted
Whether the price source quote should be inverted or not
Used to fix an inverted path of token quotes into a continuous chain of tokens (e.g. '(ETH / WBTC)^-1 * (ETH / USD)')
bool public inverted;
Functions
constructor
constructor(IBaseOracle _priceSource, IBaseOracle _denominationPriceSource, bool _inverted);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the base price source that is used to calculate the price |
_denominationPriceSource | IBaseOracle | Address of the denomination price source that is used to calculate price |
_inverted | bool | Flag that indicates whether the price source quote should be inverted or not |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _result);
UniV3Relayer
Inherits: IBaseOracle, IUniV3Relayer
This contracts consults a UniswapV3Pool TWAP and transforms the result into a standard IBaseOracle feed
The quote obtained from the pool query is transformed into an 18 decimals format
State Variables
uniV3Pool
Address of the UniswapV3Pool used to consult the TWAP
address public uniV3Pool;
baseToken
Address of the base token used to consult the quote from
address public baseToken;
quoteToken
Address of the token used as a quote reference
address public quoteToken;
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
string public symbol;
baseAmount
The amount in wei of the base token used to consult the pool for a quote
uint128 public baseAmount;
multiplier
The multiplier used to convert the quote into an 18 decimals format
uint256 public multiplier;
quotePeriod
The length of the TWAP used to consult the pool
uint32 public quotePeriod;
Functions
constructor
constructor(address _uniV3Factory, address _baseToken, address _quoteToken, uint24 _feeTier, uint32 _quotePeriod);
Parameters
Name | Type | Description |
---|---|---|
_uniV3Factory | address | |
_baseToken | address | Address of the base token used to consult the quote |
_quoteToken | address | Address of the token used as a quote reference |
_feeTier | uint24 | Fee tier of the pool used to consult the quote |
_quotePeriod | uint32 | Length in seconds of the TWAP used to consult the pool |
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
Method will return invalid if the pool doesn't have enough history
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
This method may revert with 'OLD!' if the pool doesn't have enough cardinality or initialized history
function read() external view returns (uint256 _result);
_parseResult
Parses the result from the aggregator into 18 decimals format
function _parseResult(uint256 _quoteResult) internal view returns (uint256 _result);
Contents
Contents
- BasicActions
- CollateralBidActions
- CommonActions
- DebtBidActions
- GlobalSettlementActions
- PostSettlementSurplusBidActions
- RewardedActions
- SurplusBidActions
BasicActions
Inherits: CommonActions, IBasicActions
This contract defines the actions that can be executed to manage a SAFE
Functions
_getGeneratedDeltaDebt
Gets delta debt generated for delta wad (always positive)
Total SAFE debt minus available safeHandler COIN balance
function _getGeneratedDeltaDebt(
address _safeEngine,
bytes32 _cType,
address _safeHandler,
uint256 _deltaWad
) internal view returns (int256 _deltaDebt);
_getRepaidDeltaDebt
Gets repaid delta debt generated
The rate adjusted debt of the SAFE
function _getRepaidDeltaDebt(
address _safeEngine,
bytes32 _cType,
address _safeHandler
) internal view returns (int256 _deltaDebt);
_getRepaidDebt
Gets repaid debt
The rate adjusted SAFE's debt minus COIN balance available in usr's address
function _getRepaidDebt(
address _safeEngine,
address _usr,
bytes32 _cType,
address _safeHandler
) internal view returns (uint256 _deltaWad);
_generateDebt
Generates debt
Modifies the SAFE collateralization ratio, increasing the debt and sends the COIN amount to the user's address
function _generateDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) internal;
_repayDebt
Repays debt
Joins COIN amount into the safeEngine and modifies the SAFE collateralization reducing the debt
function _repayDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) internal;
_openSAFE
Routes the openSAFE call to the HaiSafeManager contract
function _openSAFE(address _manager, bytes32 _cType, address _usr) internal returns (uint256 _safeId);
_transferCollateral
Routes the transferCollateral call to the HaiSafeManager contract
function _transferCollateral(address _manager, uint256 _safeId, address _dst, uint256 _deltaWad) internal;
_transferInternalCoins
Routes the transferInternalCoins call to the HaiSafeManager contract
function _transferInternalCoins(address _manager, uint256 _safeId, address _dst, uint256 _rad) internal;
_modifySAFECollateralization
Routes the modifySAFECollateralization call to the HaiSafeManager contract
function _modifySAFECollateralization(
address _manager,
uint256 _safeId,
int256 _deltaCollateral,
int256 _deltaDebt
) internal;
_lockTokenCollateralAndGenerateDebt
Joins collateral and exits an amount of COIN
function _lockTokenCollateralAndGenerateDebt(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safeId,
uint256 _collateralAmount,
uint256 _deltaWad
) internal;
_collectAndExitCoins
Transfers an amount of COIN to the proxy address and exits to the user's address
function _collectAndExitCoins(address _manager, address _coinJoin, uint256 _safeId, uint256 _deltaWad) internal;
_collectAndExitCollateral
Transfers an amount of collateral to the proxy address and exits collateral tokens to the user
function _collectAndExitCollateral(
address _manager,
address _collateralJoin,
uint256 _safeId,
uint256 _deltaWad
) internal;
openSAFE
Opens a brand new SAFE
function openSAFE(address _manager, bytes32 _cType, address _usr) external onlyDelegateCall returns (uint256 _safeId);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_cType | bytes32 | Bytes32 representing the collateral type |
_usr | address | Address of the SAFE owner |
Returns
Name | Type | Description |
---|---|---|
_safeId | uint256 | Id of the created SAFE |
generateDebt
Generates debt and sends COIN amount to msg.sender
function generateDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
repayDebt
Repays an amount of debt
function repayDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of COIN to repay [wad] |
lockTokenCollateral
Locks a collateral token amount in the SAFE
function lockTokenCollateral(
address _manager,
address _collateralJoin,
uint256 _safeId,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to collateralize [wad] |
freeTokenCollateral
Unlocks a collateral token amount from the SAFE, and transfers the ERC20 collateral to the user's address
function freeTokenCollateral(
address _manager,
address _collateralJoin,
uint256 _safeId,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to free [wad] |
repayAllDebt
Repays the total amount of debt of a SAFE
This method is used to close a SAFE's debt, when the amount of debt is increasing due to stability fees
function repayAllDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
lockTokenCollateralAndGenerateDebt
Locks a collateral token amount in the SAFE and generates debt
function lockTokenCollateralAndGenerateDebt(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safe,
uint256 _collateralAmount,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safe | uint256 | Id of the SAFE |
_collateralAmount | uint256 | Amount of collateral to collateralize [wad] |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
openLockTokenCollateralAndGenerateDebt
Creates a SAFE, locks a collateral token amount in it and generates debt
function openLockTokenCollateralAndGenerateDebt(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
bytes32 _cType,
uint256 _collateralAmount,
uint256 _deltaWad
) external onlyDelegateCall returns (uint256 _safe);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representing the collateral type |
_collateralAmount | uint256 | Amount of collateral to collateralize [wad] |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
Returns
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the created SAFE |
repayDebtAndFreeTokenCollateral
Repays debt and unlocks a collateral token amount from the SAFE
function repayDebtAndFreeTokenCollateral(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safeId,
uint256 _collateralWad,
uint256 _debtWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_collateralWad | uint256 | Amount of collateral to free [wad] |
_debtWad | uint256 | Amount of COIN to repay [wad] |
repayAllDebtAndFreeTokenCollateral
Repays all debt and unlocks collateral from the SAFE
function repayAllDebtAndFreeTokenCollateral(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safeId,
uint256 _collateralWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_collateralWad | uint256 | Amount of collateral to free [wad] |
collectTokenCollateral
Collects a collateral token amount from the SAFE handler, and transfers the ERC20 collateral to the user's address
function collectTokenCollateral(
address _manager,
address _collateralJoin,
uint256 _safeId,
uint256 _deltaWad
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to collect [wad] |
CollateralBidActions
Inherits: CommonActions, ICollateralBidActions
All methods here are executed as delegatecalls from the user's proxy
Functions
buyCollateral
Buys collateral tokens from a collateral auction
This method will fail if the purchased amount is lower than the minimum, or the bid higher than the specified amount
function buyCollateral(
address _coinJoin,
address _collateralJoin,
address _collateralAuctionHouse,
uint256 _auctionId,
uint256 _minCollateralAmount,
uint256 _bidAmount
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_collateralAuctionHouse | address | Address of the CollateralAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_minCollateralAmount | uint256 | Minimum amount of collateral tokens to buy [wad] |
_bidAmount | uint256 | Amount of system coins to bid [wad] |
CommonActions
Inherits: ICommonActions
This abstract contract defines common actions to be used by the proxy actions contracts
State Variables
_THIS
Address of the inheriting contract, used to check if the call is being made through a delegate call
address internal immutable _THIS = address(this);
Functions
joinSystemCoins
Joins system coins into the safeEngine
function joinSystemCoins(address _coinJoin, address _dst, uint256 _wad) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_dst | address | Address of the SAFE to join the coins into |
_wad | uint256 | Amount of coins to join [wad] |
exitSystemCoins
Exits system coins from the safeEngine
function exitSystemCoins(address _coinJoin, uint256 _coinsToExit) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_coinsToExit | uint256 | Amount of coins to exit [rad] |
exitAllSystemCoins
Exits all system coins from the safeEngine
function exitAllSystemCoins(address _coinJoin) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
exitCollateral
Exits collateral tokens from the safeEngine
function exitCollateral(address _collateralJoin, uint256 _wad) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_collateralJoin | address | Address of the CollateralJoin contract |
_wad | uint256 | Amount of collateral tokens to exit [wad] |
_joinSystemCoins
Joins system coins into the safeEngine
Transfers ERC20 coins from the user to the proxy, then joins them through the CoinJoin contract into the destination SAFE
function _joinSystemCoins(address _coinJoin, address _dst, uint256 _wad) internal;
_exitSystemCoins
Exits system coins from the safeEngine
Exits system coins through the CoinJoin contract, transferring the ERC20 coins to the user
function _exitSystemCoins(address _coinJoin, uint256 _coinsToExit) internal virtual;
_joinCollateral
Joins collateral tokens into the safeEngine
Transfers ERC20 tokens from the user to the proxy, then joins them through the CollateralJoin contract into the destination SAFE
function _joinCollateral(address _collateralJoin, address _safe, uint256 _wad) internal;
_exitCollateral
Exits collateral tokens from the safeEngine
Exits collateral tokens through the CollateralJoin contract, transferring the ERC20 tokens to the user
The exited tokens will be rounded down to collateral decimals precision
function _exitCollateral(address _collateralJoin, uint256 _wad) internal;
onlyDelegateCall
Checks if the call is being made through a delegate call
modifier onlyDelegateCall();
DebtBidActions
Inherits: CommonActions, IDebtBidActions
All methods here are executed as delegatecalls from the user's proxy
Functions
decreaseSoldAmount
Place a bid offering to receive a lesser amount of protocol tokens for covering the auctioned debt amount
function decreaseSoldAmount(
address _coinJoin,
address _debtAuctionHouse,
uint256 _auctionId,
uint256 _soldAmount
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_debtAuctionHouse | address | Address of the DebtAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_soldAmount | uint256 | Amount of protocol tokens to receive [wad] |
settleAuction
Settles an auction, collecting the protocol tokens if the user is the highest bidder
This method will fail if the auction is not finished
function settleAuction(address _coinJoin, address _debtAuctionHouse, uint256 _auctionId) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_debtAuctionHouse | address | Address of the DebtAuctionHouse contract |
_auctionId | uint256 | Id of the auction to settle |
collectProtocolTokens
Collects the protocol tokens that the proxy has
This method is used to collect protocol tokens from an auction that was settled by another user
function collectProtocolTokens(address _protocolToken) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_protocolToken | address | Address of the protocol token |
GlobalSettlementActions
Inherits: CommonActions, IGlobalSettlementActions
All methods here are executed as delegatecalls from the user's proxy
Functions
freeCollateral
Free remaining collateral from a SAFE after being processed by the global settlement
function freeCollateral(
address _manager,
address _globalSettlement,
address _collateralJoin,
uint256 _safeId
) external onlyDelegateCall returns (uint256 _collateralAmount);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_globalSettlement | address | Address of the GlobalSettlement contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE to free collateral from |
Returns
Name | Type | Description |
---|---|---|
_collateralAmount | uint256 | Amount of collateral freed [wad] |
prepareCoinsForRedeeming
Prepare coins for redeeming
function prepareCoinsForRedeeming(
address _globalSettlement,
address _coinJoin,
uint256 _coinAmount
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_globalSettlement | address | Address of the GlobalSettlement contract |
_coinJoin | address | Address of the CoinJoin contract |
_coinAmount | uint256 | Amount of coins to prepare for redeeming [wad] |
redeemCollateral
Redeem collateral tokens from the global settlement
function redeemCollateral(
address _globalSettlement,
address _collateralJoin
) external onlyDelegateCall returns (uint256 _collateralAmount);
Parameters
Name | Type | Description |
---|---|---|
_globalSettlement | address | Address of the GlobalSettlement contract |
_collateralJoin | address | Address of the CollateralJoin contract |
Returns
Name | Type | Description |
---|---|---|
_collateralAmount | uint256 | Amount of collateral redeemed [wad] |
PostSettlementSurplusBidActions
Inherits: SurplusBidActions
All methods here are executed as delegatecalls from the user's proxy
Functions
_exitSystemCoins
Exits system coins from the safeEngine
Post settlement it is not possible to exit system coins
function _exitSystemCoins(address, uint256) internal override;
RewardedActions
Inherits: CommonActions, IRewardedActions
All methods here are executed as delegatecalls from the user's proxy
Functions
startDebtAuction
Starts a debt auction and transfers the reward to the user
function startDebtAuction(address _accountingJob, address _coinJoin) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
startSurplusAuction
Starts a surplus auction and transfers the reward to the user
function startSurplusAuction(address _accountingJob, address _coinJoin) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
popDebtFromQueue
Pops debt from accounting engine's queue and transfers the reward to the user
function popDebtFromQueue(address _accountingJob, address _coinJoin, uint256 _debtTimestamp) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_debtTimestamp | uint256 | Timestamp of the debt to pop from the queue |
transferExtraSurplus
Transfers surplus from accounting engine and transfers the reward to the user
function transferExtraSurplus(address _accountingJob, address _coinJoin) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
liquidateSAFE
Starts a liquidation and transfers the reward to the user
function liquidateSAFE(
address _liquidationJob,
address _coinJoin,
bytes32 _cType,
address _safe
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_liquidationJob | address | Address of the LiquidationJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE to liquidate |
updateCollateralPrice
Updates the price of a collateral type and transfers the reward to the user
function updateCollateralPrice(address _oracleJob, address _coinJoin, bytes32 _cType) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_oracleJob | address | Address of the OracleJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
updateRedemptionRate
Updates the redemption rate and transfers the reward to the user
function updateRedemptionRate(address _oracleJob, address _coinJoin) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_oracleJob | address | Address of the OracleJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_exitReward
Exits the reward from the job and transfers it to the user
function _exitReward(address _job, address _coinJoin) internal;
Parameters
Name | Type | Description |
---|---|---|
_job | address | Address of the job contract |
_coinJoin | address | Address of the CoinJoin contract |
SurplusBidActions
Inherits: ISurplusBidActions, CommonActions
All methods here are executed as delegatecalls from the user's proxy
Functions
increaseBidSize
Place a bid offering to provide a higher amount of coins for receiving the auctioned protocol tokens
function increaseBidSize(
address _surplusAuctionHouse,
uint256 _auctionId,
uint256 _bidAmount
) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_bidAmount | uint256 | Amount of system coins to bid [wad] |
settleAuction
Settles an auction, collecting the system coins if the user is the highest bidder
This method will fail if the auction is not finished
function settleAuction(address _coinJoin, address _surplusAuctionHouse, uint256 _auctionId) external onlyDelegateCall;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse contract |
_auctionId | uint256 | Id of the auction to settle |
HaiProxy
Inherits: HaiOwnable2Step, IHaiProxy
This contract is an ownable proxy to execute batched transactions in the protocol contracts
The proxy executes a delegate call to an Actions contract, which have the logic to execute the batched transactions
Functions
constructor
constructor(address _owner) Ownable(_owner);
Parameters
Name | Type | Description |
---|---|---|
_owner | address | The owner of the proxy contract |
execute
Executes a call to the target contract through a delegate call
The proxy will call the target through a delegate call (the target must not be a direct protocol contract)
function execute(address _target, bytes memory _data) external payable onlyOwner returns (bytes memory _response);
Parameters
Name | Type | Description |
---|---|---|
_target | address | Address of the target Actions contract |
_data | bytes | Encoded data of the transaction to execute |
Returns
Name | Type | Description |
---|---|---|
_response | bytes | The raw response of the target call |
owner
Emitted when an ownership transfer is initiated
function owner() public view override(HaiOwnable2Step, IHaiOwnable2Step) returns (address _owner);
pendingOwner
The address of the pending owner
function pendingOwner() public view override(HaiOwnable2Step, IHaiOwnable2Step) returns (address _pendingOwner);
renounceOwnership
Leaves the contract without an owner, thereby disabling any functionality that is only available to the owner
It will not be possible to call onlyOwner
functions
function renounceOwnership() public override(HaiOwnable2Step, IHaiOwnable2Step) onlyOwner;
transferOwnership
Starts the ownership transfer of the contract to a new account
Replaces the pending transfer if there is one
function transferOwnership(address _newOwner) public override(HaiOwnable2Step, IHaiOwnable2Step) onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_newOwner | address | The address of the new owner |
acceptOwnership
Accepts the ownership transfer
Can only be called by the current pending owner
function acceptOwnership() public override(HaiOwnable2Step, IHaiOwnable2Step);
HaiProxyFactory
Inherits: IHaiProxyFactory
This contract is used to deploy new HaiProxy instances
State Variables
isProxy
Mapping of proxy addresses to boolean state
mapping(address _proxyAddress => bool _exists) public isProxy;
proxies
Mapping of user addresses to proxy instances
mapping(address _owner => IHaiProxy) public proxies;
nonces
Mapping of the next nonce to be used for the specified owner
mapping(address _owner => uint256 nonce) public nonces;
Functions
build
Deploys a new proxy instance, setting the caller as the owner
function build() external returns (address payable _proxy);
Returns
Name | Type | Description |
---|---|---|
_proxy | address payable | Address of the new proxy |
build
Deploys a new proxy instance, setting the caller as the owner
function build(address _owner) external returns (address payable _proxy);
Returns
Name | Type | Description |
---|---|---|
_proxy | address payable | Address of the new proxy |
_build
Internal method used to deploy a new proxy instance
function _build(address _owner) internal returns (address payable _proxy);
HaiSafeManager
Inherits: IHaiSafeManager
This contract acts as interface to the SAFEEngine, facilitating the management of SAFEs
This contract is meant to be used by users that interact with the protocol through a proxy contract
State Variables
safeEngine
Address of the SAFEEngine
address public safeEngine;
_safeId
Nonce used to generate safe ids (autoincremental)
uint256 internal _safeId;
_usrSafes
Mapping of user addresses to their enumerable set of safes
mapping(address _safeOwner => EnumerableSet.UintSet) internal _usrSafes;
_usrSafesPerCollat
Mapping of user addresses to their enumerable set of safes per collateral type
mapping(address _safeOwner => mapping(bytes32 _cType => EnumerableSet.UintSet)) internal _usrSafesPerCollat;
_safeData
Mapping of safe ids to their data
mapping(uint256 _safeId => SAFEData) internal _safeData;
safeCan
Mapping of owner and safe permissions to a caller permissions
mapping(address _owner => mapping(uint256 _safeId => mapping(address _caller => bool _ok))) public safeCan;
handlerCan
Mapping of handler to a caller permissions
mapping(address _safeHandler => mapping(address _caller => bool _ok)) public handlerCan;
Functions
safeAllowed
Checks if the sender is the owner of the safe or the safe has permissions to call the function
modifier safeAllowed(uint256 _safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the safe to check if msg.sender has permissions for |
handlerAllowed
Checks if the sender is the safe handler has permissions to call the function
modifier handlerAllowed(address _handler);
Parameters
Name | Type | Description |
---|---|---|
_handler | address | Address of the handler to check if msg.sender has permissions for |
constructor
constructor(address _safeEngine);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine |
getSafes
Getter for the list of safes owned by a user
function getSafes(address _usr) external view returns (uint256[] memory _safes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user |
getSafes
Getter for the list of safes owned by a user
function getSafes(address _usr, bytes32 _cType) external view returns (uint256[] memory _safes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
_cType | bytes32 |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user |
getSafesData
Getter for the details of the safes owned by a user
function getSafesData(address _usr)
external
view
returns (uint256[] memory _safes, address[] memory _safeHandlers, bytes32[] memory _cTypes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user |
_safeHandlers | address[] | List of safe handlers addresses owned by the user |
_cTypes | bytes32[] | List of collateral types of the safes owned by the user |
safeData
Getter for the details of a SAFE
function safeData(uint256 _safe) external view returns (SAFEData memory _sData);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
Returns
Name | Type | Description |
---|---|---|
_sData | SAFEData | Struct with the safe data |
allowSAFE
Allow/disallow a user address to manage the safe
function allowSAFE(uint256 _safe, address _usr, bool _ok) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_usr | address | Address of the user to allow/disallow |
_ok | bool | Boolean state to allow/disallow |
allowHandler
Allow/disallow a handler address to manage the safe
function allowHandler(address _usr, bool _ok) external;
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user to allow/disallow |
_ok | bool | Boolean state to allow/disallow |
openSAFE
Open a new safe for a user address
function openSAFE(bytes32 _cType, address _usr) external returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_usr | address | Address of the user to open the safe for |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the new SAFE |
transferSAFEOwnership
Initiate the transfer of the ownership of a safe to a dst address
function transferSAFEOwnership(uint256 _safe, address _dst) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
acceptSAFEOwnership
Accept the transfer of the ownership of a safe
function acceptSAFEOwnership(uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
modifySAFECollateralization
Modify a SAFE's collateralization ratio while keeping the generated COIN or collateral freed in the safe handler address
function modifySAFECollateralization(
uint256 _safe,
int256 _deltaCollateral,
int256 _deltaDebt
) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_deltaCollateral | int256 | Delta of collateral to add/remove [wad] |
_deltaDebt | int256 | Delta of debt to add/remove [wad] |
transferCollateral
Transfer wad amount of safe collateral from the safe address to a dst address
function transferCollateral(uint256 _safe, address _dst, uint256 _wad) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_wad | uint256 | Amount of collateral to transfer [wad] |
transferCollateral
Transfer wad amount of safe collateral from the safe address to a dst address
function transferCollateral(bytes32 _cType, uint256 _safe, address _dst, uint256 _wad) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | |
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_wad | uint256 | Amount of collateral to transfer [wad] |
transferInternalCoins
Transfer an amount of COIN from the safe address to a dst address [rad]
function transferInternalCoins(uint256 _safe, address _dst, uint256 _rad) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_rad | uint256 | Amount of COIN to transfer [rad] |
quitSystem
Quit the system, migrating the safe (lockedCollateral, generatedDebt) to a different dst handler
function quitSystem(uint256 _safe, address _dst) external safeAllowed(_safe) handlerAllowed(_dst);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst handler |
enterSystem
Enter the system, migrating the safe (lockedCollateral, generatedDebt) from a src handler to the safe handler
function enterSystem(address _src, uint256 _safe) external handlerAllowed(_src) safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_src | address | Address of the src handler |
_safe | uint256 | Id of the SAFE |
moveSAFE
Move a position from safeSrc handler to the safeDst handler
function moveSAFE(uint256 _safeSrc, uint256 _safeDst) external safeAllowed(_safeSrc) safeAllowed(_safeDst);
Parameters
Name | Type | Description |
---|---|---|
_safeSrc | uint256 | Id of the source SAFE |
_safeDst | uint256 | Id of the destination SAFE |
addSAFE
Add a safe to the user's list of safes (doesn't set safe ownership)
This function is meant to allow the user to add a safe to their list (if it was previously removed)
function addSAFE(uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
removeSAFE
Remove a safe from the user's list of safes (doesn't erase safe ownership)
This function is meant to allow the user to remove a safe from their list (if it was added against their will)
function removeSAFE(uint256 _safe) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
protectSAFE
Choose a safe saviour inside LiquidationEngine for the SAFE
function protectSAFE(uint256 _safe, address _liquidationEngine, address _saviour) external safeAllowed(_safe);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_liquidationEngine | address | Address of the LiquidationEngine |
_saviour | address | Address of the saviour |
SAFEHandler
This contract is spawned to provide a unique safe handler address for each user's SAFE
When a new SAFE is created inside HaiSafeManager, this contract is deployed and calls the SAFEEngine to add permissions to the SAFE manager
Functions
constructor
Grants permissions to the SAFE manager to modify the SAFE of this contract's address
constructor(address _safeEngine);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
Contents
GlobalSettlement
Inherits: Authorizable, Modifiable, Disableable, IGlobalSettlement
This contract is responsible for processing the system settlement, a stateful process that takes place over nine steps.
System shutdown:
We must freeze the system and start the cooldown period before we can process any system state. In particular, oracle prices are frozen, and no more debt can be generated from the SAFEEngine.
shutdownSystem()
- freeze the system and start the cooldown period
freezeCollateralType(_cType)
- reads and store the final price for each collateral type
- initializes
collateralTotalDebt
to the total debt registered in safe engine
Cooldown period:
We must process some system state before it is possible to calculate the final coin / collateral price. In particular, we need to determine:
- (a)
collateralShortfall
(considers under-collateralized SAFEs)- (b)
outstandingCoinSupply
(after including system surplus / deficit)
- We determine (a) by processing all under-collateralized SAFEs.
- We determine (b) by processing ongoing coin generating processes, i.e. auctions. We need to ensure that auctions will not generate any further coin income.
processSAFE(_cType, _safe)
- confiscates SAFE debt and backing collateral (excess of collateral remains).
- Auctions at SAH and DAH can be terminated prematurely, while CAH auctions are handled by this contract
- 4.a.
SAH.terminateAuctionPrematurely(_id)
- settles the auction
- transfers the surplus to the highest bidder
- 4.b.
DAH.terminateAuctionPrematurely(_id)
- settles the auction
- returns the coins to the highest bidder
- registers the unbacked debt at the accounting engine
- 4.c.
this.fastTrackAuction(_cType, _id)
- settles the auction: returns collateral and debt to the SAFE
- registers returned debt in
collateralTotalDebt
When an overcollateralized SAFE has been processed and has no debt remaining, the remaining collateral can be withdrawn:
freeCollateral(_cType)
- remove collateral from the caller's SAFE (requires SAFE to have no debt)
After cooldown period:
We enable calculation of the final price for each collateral type. Requires accounting engine to have no surplus.
setOutstandingCoinSupply()
- fixes the total outstanding supply of coin
calculateCashPrice(_cType)
- calculate
collateralCashPrice
adjusted in the case of deficit / surplus
Redeeming:
At this point we have computed the final price for each collateral type and coin holders can now turn their coin into collateral.
prepareCoinsForRedeeming(_wad)
- deposit the amount of coins to redeem in caller's accountance
- Each unit of coin can claim a proportional amount of all of the system's collateral
- At any point a user can get and prepare more coins to redeem for more collateral
redeemCollateral(_cType, _wad)
- claim tokens from a specific collateral type given the amount of coins caller has deposited
- The amount of collateral to redeem depends exclusively in the state variables calculated in the previous steps
- The amount of collaterals left when all circulating coins are redeemed should be 0
State Variables
shutdownTime
The timestamp when settlement was triggered
uint256 public shutdownTime;
outstandingCoinSupply
The outstanding coin supply computed during the settlement process [rad]
uint256 public outstandingCoinSupply;
finalCoinPerCollateralPrice
The final coin per collateral price computed during the settlement process
mapping(bytes32 _cType => uint256 _ray) public finalCoinPerCollateralPrice;
collateralShortfall
The total amount of bad debt for a collateral type computed during the settlement process
mapping(bytes32 _cType => uint256 _wad) public collateralShortfall;
collateralTotalDebt
The total amount of debt for a collateral type computed during the settlement process
mapping(bytes32 _cType => uint256 _wad) public collateralTotalDebt;
collateralCashPrice
Final collateral cash price computed during the settlement process, accounting for surplus / shortfall
mapping(bytes32 _cType => uint256 _ray) public collateralCashPrice;
coinBag
Mapping containing the total amount of coins a user has prepared for redeeming
mapping(address _usr => uint256 _wad) public coinBag;
coinsUsedToRedeem
Mapping containing the total amount of coins a user has used to redeem collateral
mapping(bytes32 _cType => mapping(address _usr => uint256 _wad)) public coinsUsedToRedeem;
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
liquidationEngine
Address of the LiquidationEngine contract
ILiquidationEngine public liquidationEngine;
oracleRelayer
Address of the OracleRelayer contract
IOracleRelayer public oracleRelayer;
coinJoin
Address of the CoinJoin contract
IDisableable public coinJoin;
collateralJoinFactory
Address of the CollateralJoinFactory contract
IDisableable public collateralJoinFactory;
collateralAuctionHouseFactory
Address of the CollateralAuctionHouseFactory contract
IDisableable public collateralAuctionHouseFactory;
stabilityFeeTreasury
Address of the StabilityFeeTreasury contract
IDisableable public stabilityFeeTreasury;
accountingEngine
Address of the AccountingEngine contract
IDisableable public accountingEngine;
_params
Getter for the unpacked contract parameters struct
GlobalSettlementParams public _params;
Functions
params
Getter for the contract parameters struct
function params() external view returns (GlobalSettlementParams memory _globalSettlementParams);
Returns
Name | Type | Description |
---|---|---|
_globalSettlementParams | GlobalSettlementParams | GlobalSettlement parameters struct |
constructor
constructor(
address _safeEngine,
address _liquidationEngine,
address _oracleRelayer,
address _coinJoin,
address _collateralJoinFactory,
address _collateralAuctionHouseFactory,
address _stabilityFeeTreasury,
address _accountingEngine,
GlobalSettlementParams memory _gsParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_liquidationEngine | address | Address of the LiquidationEngine contract |
_oracleRelayer | address | Address of the OracleRelayer contract |
_coinJoin | address | Address of the CoinJoin contract |
_collateralJoinFactory | address | Address of the CollateralJoinFactory contract |
_collateralAuctionHouseFactory | address | Address of the CollateralAuctionHouseFactory contract |
_stabilityFeeTreasury | address | Address of the StabilityFeeTreasury contract |
_accountingEngine | address | Address of the AccountingEngine contract |
_gsParams | GlobalSettlementParams | Initial valid GlobalSettlement parameters struct |
_onContractDisable
Internal virtual method to be called when the contract is disabled
Method override avoids externally disabling this contract
function _onContractDisable() internal pure override;
shutdownSystem
Freeze the system and start the cooldown period
This function switches the whenEnabled
/whenDisabled
modifiers across the system contracts
function shutdownSystem() external isAuthorized whenEnabled;
freezeCollateralType
Calculate a collateral type's final price according to the latest system coin redemption price
function freezeCollateralType(bytes32 _cType) external whenDisabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to calculate the price for |
fastTrackAuction
Fast track an ongoing collateral auction
function fastTrackAuction(bytes32 _cType, uint256 _auctionId) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type associated with the auction contract |
_auctionId | uint256 | The ID of the auction to be fast tracked |
processSAFE
Cancel a SAFE's debt and leave any extra collateral in it
function processSAFE(bytes32 _cType, address _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type associated with the SAFE |
_safe | address | The SAFE to be processed |
freeCollateral
Remove collateral from the caller's SAFE (requires SAFE to have no debt)
function freeCollateral(bytes32 _cType) external whenDisabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to free |
setOutstandingCoinSupply
Set the final outstanding supply of system coins
There must be no remaining surplus in the accounting engine
function setOutstandingCoinSupply() external whenDisabled;
calculateCashPrice
Calculate a collateral's price taking into consideration system surplus/deficit and the finalCoinPerCollateralPrice
function calculateCashPrice(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral whose cash price will be calculated |
prepareCoinsForRedeeming
Add coins into a 'bag' so that you can use them to redeem collateral
function prepareCoinsForRedeeming(uint256 _coinAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_coinAmount | uint256 | The amount of internal system coins to add into the bag |
redeemCollateral
Redeem a specific collateral type using an amount of internal system coins from your bag
function redeemCollateral(bytes32 _cType, uint256 _coinsAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to redeem |
_coinsAmount | uint256 | The amount of internal coins to use from your bag |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override whenEnabled;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
PostSettlementSurplusAuctionHouse
Inherits: Authorizable, Modifiable, IPostSettlementSurplusAuctionHouse
This contract enables the sell of system coins in exchange for protocol tokens after Global Settlement is triggered
The reason to auction the post settlement surplus is to avoid incentives to trigger Global Settlement if the system has a surplus
State Variables
AUCTION_HOUSE_TYPE
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32('SURPLUS');
_auctions
Raw data of an auction
mapping(uint256 => Auction) public _auctions;
auctionsStarted
Total amount of surplus auctions created
uint256 public auctionsStarted;
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
protocolToken
Address of the ProtocolToken contract
IProtocolToken public protocolToken;
_params
Getter for the unpacked contract parameters struct
PostSettlementSAHParams public _params;
Functions
auctions
Data of an auction
function auctions(uint256 _id) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
params
Getter for the contract parameters struct
function params() external view returns (PostSettlementSAHParams memory _pssahParams);
Returns
Name | Type | Description |
---|---|---|
_pssahParams | PostSettlementSAHParams | The contract parameters struct |
constructor
constructor(
address _safeEngine,
address _protocolToken,
PostSettlementSAHParams memory _pssahParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_protocolToken | address | Address of the ProtocolToken contract |
_pssahParams | PostSettlementSAHParams | Initial valid PostSettlementSAH parameters struct |
startAuction
Start a new surplus auction
function startAuction(uint256 _amountToSell, uint256 _initialBid) external isAuthorized returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_amountToSell | uint256 | Total amount of system coins to sell [rad] |
_initialBid | uint256 | Initial protocol token bid [wad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the started auction |
restartAuction
Restart an auction if no bids were submitted for it
function restartAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to restart |
increaseBidSize
Submit a higher protocol token bid for the same amount of system coins
function increaseBidSize(uint256 _id, uint256 _bid) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction you want to submit the bid for |
_bid | uint256 | New bid submitted [wad] |
settleAuction
Settle/finish an auction
function settleAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to settle |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
SettlementSurplusAuctioneer
Inherits: Authorizable, Modifiable, ISettlementSurplusAuctioneer
This contract receives post-settlement surplus coins from the AccountingEngine and starts auctions for them
State Variables
lastSurplusTime
The last time when this contract triggered a surplus auction
uint256 public lastSurplusTime;
accountingEngine
The address of the AccountingEngine
IAccountingEngine public accountingEngine;
surplusAuctionHouse
The address of the SurplusAuctionHouse
ISurplusAuctionHouse public surplusAuctionHouse;
safeEngine
The address of the SAFEEngine
ISAFEEngine public safeEngine;
Functions
constructor
constructor(address _accountingEngine, address _surplusAuctionHouse) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_accountingEngine | address | Address of the AccountingEngine |
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse |
auctionSurplus
Starts a new surplus auction
The contract reads surplus auction parameters from the AccountingEngine
function auctionSurplus() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | The id of the started auction |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_setSurplusAuctionHouse
Sets the SurplusAuctionHouse, revoking the previous one permissions and approving the new one
function _setSurplusAuctionHouse(address _address) internal;
Contents
ProtocolToken
Inherits: ERC20, ERC20Permit, ERC20Votes, ERC20Pausable, Authorizable, IProtocolToken
This contract represents the protocol ERC20Votes token to be used for governance purposes
Functions
constructor
constructor(
string memory _name,
string memory _symbol
) ERC20(_name, _symbol) ERC20Permit(_name) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_name | string | String with the name of the token |
_symbol | string | String with the symbol of the token |
mint
Mint an amount of tokens to an account
Only authorized addresses can mint tokens
function mint(address _dst, uint256 _wad) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_dst | address | |
_wad | uint256 |
burn
Burn an amount of tokens from the sender
function burn(uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_wad | uint256 |
unpause
Unpause the token transfers, minting and burning
Only authorized addresses can unpause the token
function unpause() external isAuthorized;
_update
function _update(address _from, address _to, uint256 _value) internal override(ERC20, ERC20Votes, ERC20Pausable);
nonces
function nonces(address _owner) public view override(ERC20Permit, IERC20Permit, Nonces) returns (uint256 _nonce);
clock
Set the clock to block timestamp, as opposed to the default block number.
function clock() public view override returns (uint48 _timestamp);
CLOCK_MODE
function CLOCK_MODE() public view virtual override returns (string memory _mode);
SystemCoin
Inherits: ERC20, ERC20Permit, Authorizable, ISystemCoin
This contract represents the system coin ERC20 token to be used outside the system
Functions
constructor
constructor(
string memory _name,
string memory _symbol
) ERC20(_name, _symbol) ERC20Permit(_name) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_name | string | String with the name of the token |
_symbol | string | String with the symbol of the token |
mint
Mint an amount of tokens to an account
Only authorized addresses can mint tokens
function mint(address _dst, uint256 _wad) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_dst | address | |
_wad | uint256 |
burn
Burn an amount of tokens from the sender
function burn(uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_wad | uint256 |
TokenDistributor
Inherits: Authorizable, ITokenDistributor
This contract allows users to claim tokens from a merkle tree proof
State Variables
token
Address of the ERC20 token to be distributed
IProtocolToken public token;
root
The merkle root of the token distribution
bytes32 public root;
totalClaimable
Total amount of tokens to be distributed
uint256 public totalClaimable;
claimPeriodStart
Timestamp when the claim period starts
uint256 public claimPeriodStart;
claimPeriodEnd
Timestamp when the claim period ends
uint256 public claimPeriodEnd;
claimed
Mapping containing the users that have already claimed
mapping(address _user => bool _hasClaimed) public claimed;
Functions
constructor
constructor(address _token, TokenDistributorParams memory _tokenDistributorParams) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_token | address | Address of the ERC20 token to be distributed |
_tokenDistributorParams | TokenDistributorParams | TokenDistributor valid parameters struct |
canClaim
Checks if a user can claim tokens
function canClaim(bytes32[] calldata _proof, address _user, uint256 _amount) external view returns (bool _claimable);
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_user | address | Address of the user to check |
_amount | uint256 | Amount of tokens to check |
Returns
Name | Type | Description |
---|---|---|
_claimable | bool | Whether the user can claim the amount with the proof provided |
claim
Claims tokens from the distributor
function claim(bytes32[] calldata _proof, uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_amount | uint256 | Amount of tokens to claim |
claimAndDelegate
Claims tokens from the distributor and delegates them using a signature
function claimAndDelegate(
bytes32[] calldata _proof,
uint256 _amount,
address _delegatee,
uint256 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_amount | uint256 | Amount of tokens to claim |
_delegatee | address | Address to delegate the token votes to |
_expiry | uint256 | Expiration timestamp of the signature |
_v | uint8 | Recovery byte of the signature |
_r | bytes32 | ECDSA signature r value |
_s | bytes32 | ECDSA signature s value |
sweep
Withdraws tokens from the distributor to a given address after the claim period has ended
function sweep(address _sweepReceiver) external override isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_sweepReceiver | address | Address to send the tokens to |
_canClaim
function _canClaim(bytes32[] calldata _proof, address _user, uint256 _amount) internal view returns (bool _claimable);
_claim
function _claim(bytes32[] calldata _proof, uint256 _amount) internal;
Contents
Authorizable
Inherits: IAuthorizable
Implements authorization control for contracts
Authorization control is boolean and handled by isAuthorized
modifier
State Variables
_authorizedAccounts
EnumerableSet of authorized accounts
EnumerableSet.AddressSet internal _authorizedAccounts;
Functions
constructor
constructor(address _account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Initial account to add authorization to |
authorizedAccounts
Checks whether an account is authorized
function authorizedAccounts(address _account) external view returns (bool _authorized);
Returns
Name | Type | Description |
---|---|---|
_authorized | bool | Whether the account is authorized or not |
authorizedAccounts
Getter for the authorized accounts
function authorizedAccounts() external view returns (address[] memory _accounts);
Returns
Name | Type | Description |
---|---|---|
_accounts | address[] | Array of authorized accounts |
addAuthorization
Add auth to an account
function addAuthorization(address _account) external virtual isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to add auth to |
removeAuthorization
Remove auth from an account
function removeAuthorization(address _account) external virtual isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to remove auth from |
_addAuthorization
function _addAuthorization(address _account) internal;
_removeAuthorization
function _removeAuthorization(address _account) internal;
_isAuthorized
function _isAuthorized(address _account) internal view virtual returns (bool _authorized);
isAuthorized
Checks whether msg.sender can call an authed function
Will revert with Unauthorized
if the sender is not authorized
modifier isAuthorized();
CoinJoin
Inherits: Authorizable, Disableable, ICoinJoin
This contract allows to connect the SAFEEngine with the system coin
This contract needs to be authorized in Coin and SAFEEngine
State Variables
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
systemCoin
Address of the SystemCoin contract
ISystemCoin public systemCoin;
decimals
Number of decimals the coin has
uint256 public decimals;
Functions
constructor
constructor(address _safeEngine, address _systemCoin) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_systemCoin | address | Address of the SystemCoin contract |
join
Join system coins in the system
Exited coins have 18 decimals but inside the system they have 45 [rad] decimals. When we join, the amount [wad] is multiplied by 10**27 [ray]
function join(address _account, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that will receive the joined coins |
_wad | uint256 | Amount of external coins to join [wad] |
exit
Exit system coins from the system
New coins cannot be minted after the system is disabled
function exit(address _account, uint256 _wad) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that will receive the exited coins |
_wad | uint256 | Amount of internal coins to join (18 decimal number) |
CollateralJoin
Inherits: Disableable, ICollateralJoin
This contract allows to connect the SAFEEngine to arbitrary external token implementations
For well behaved ERC20 tokens with less than 18 decimals.
All Join adapters need to implement two basic methods: join
and exit
State Variables
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
collateral
Address of the ERC20 collateral token contract
IERC20Metadata public collateral;
collateralType
The collateral type that this contract handles
bytes32 public collateralType;
decimals
Number of decimals of the collateral token
uint256 public decimals;
multiplier
Multiplier used to transform collateral into 18 decimals within the system
uint256 public multiplier;
Functions
constructor
constructor(address _safeEngine, bytes32 _cType, address _collateral) Authorizable(msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20 collateral token |
join
Join collateral in the system
This function locks collateral in the adapter and creates a representation of the locked collateral inside the system. The representation uses 18 decimals.
function join(address _account, uint256 _wei) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to which we add collateral into the system |
_wei | uint256 | Amount of collateral to transfer in the system (represented as a number with token decimals) |
exit
Exit collateral from the system
This function destroys the collateral representation from inside the system and exits the collateral from this adapter. The transferred collateral uses the same decimals as the original collateral token.
function exit(address _account, uint256 _wei) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to which we transfer the collateral out of the system |
_wei | uint256 | Amount of collateral to transfer to account (represented as a number with token decimals) |
Disableable
Inherits: IDisableable, Authorizable
This abstract contract provides the ability to disable the inheriting contract, triggering (if implemented) an on-disable routine hook.
This contract also implements whenEnabled
and whenDisabled
modifiers to restrict
the methods that can be called on each state.
State Variables
contractEnabled
Check if the contract is enabled
bool public contractEnabled = true;
Functions
disableContract
External method to trigger the contract disablement
Triggers an internal call to _onContractDisable
virtual method
function disableContract() external isAuthorized whenEnabled;
_onContractDisable
Internal virtual method to be called when the contract is disabled
This method is virtual and should be overriden to implement
function _onContractDisable() internal virtual;
_isEnabled
Internal virtual view to check if the contract is enabled
This method is virtual and could be overriden for non-standard implementations
function _isEnabled() internal view virtual returns (bool _enabled);
whenEnabled
Allows method calls only when the contract is enabled
modifier whenEnabled();
whenDisabled
Allows method calls only when the contract is disabled
modifier whenDisabled();
HaiOwnable2Step
Inherits: Ownable2Step, IHaiOwnable2Step
This abstract contract inherits Ownable2Step
Functions
owner
Emitted when an ownership transfer is initiated
function owner() public view virtual override(Ownable, IHaiOwnable2Step) returns (address _owner);
pendingOwner
The address of the pending owner
function pendingOwner() public view virtual override(Ownable2Step, IHaiOwnable2Step) returns (address _pendingOwner);
renounceOwnership
Leaves the contract without an owner, thereby disabling any functionality that is only available to the owner
It will not be possible to call onlyOwner
functions
function renounceOwnership() public virtual override(Ownable, IHaiOwnable2Step) onlyOwner;
transferOwnership
Starts the ownership transfer of the contract to a new account
Replaces the pending transfer if there is one
function transferOwnership(address _newOwner) public virtual override(Ownable2Step, IHaiOwnable2Step) onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
_newOwner | address | The address of the new owner |
acceptOwnership
Accepts the ownership transfer
Can only be called by the current pending owner
function acceptOwnership() public virtual override(Ownable2Step, IHaiOwnable2Step);
Modifiable
Inherits: Authorizable, IModifiable
Allows inheriting contracts to modify parameters values
Requires inheriting contracts to override _modifyParameters
virtual methods
State Variables
_GLOBAL_PARAM
Used to emit a global parameter modification event
bytes32 internal constant _GLOBAL_PARAM = bytes32(0);
Functions
modifyParameters
Set a new value for a global specific parameter
function modifyParameters(bytes32 _param, bytes memory _data) external isAuthorized validParams;
Parameters
Name | Type | Description |
---|---|---|
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal virtual;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view virtual;
validParams
Triggers a routine to validate parameters after a modification
modifier validParams();
ModifiablePerCollateral
Inherits: Authorizable, IModifiablePerCollateral
Allows inheriting contracts to modify parameters values and initialize collateral types
Requires inheriting contracts to override _modifyParameters
virtual methods and implement _initializeCollateralType
State Variables
_collateralList
EnumerableSet.Bytes32Set internal _collateralList;
Functions
collateralList
List of all the collateral types registered in the OracleRelayer
function collateralList() external view returns (bytes32[] memory __collateralList);
Returns
Name | Type | Description |
---|---|---|
__collateralList | bytes32[] | Array of all the collateral types registered |
initializeCollateralType
Register a new collateral type in the SAFEEngine
function initializeCollateralType(
bytes32 _cType,
bytes memory _collateralParams
) public virtual isAuthorized validCParams(_cType);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
modifyParameters
Set a new value for a collateral specific parameter
function modifyParameters(
bytes32 _cType,
bytes32 _param,
bytes memory _data
) external isAuthorized validCParams(_cType);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal virtual;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_initializeCollateralType
Register a new collateral type in the SAFEEngine
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal virtual;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
_validateCParameters
Internal function to be overriden with custom logic to validate collateral parameters
function _validateCParameters(bytes32 _cType) internal view virtual;
validCParams
Triggers a routine to validate collateral parameters after a modification
modifier validCParams(bytes32 _cType);
AccountingEngine
Inherits: Authorizable, Modifiable, Disableable, IAccountingEngine
This contract is responsible for handling protocol surplus and debt
It allows the system to auction surplus and debt, as well as transfer surplus
This is a system contract, therefore it is not meant to be used by users directly
State Variables
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
surplusAuctionHouse
Address of the SurplusAuctionHouse contract
ISurplusAuctionHouse public surplusAuctionHouse;
debtAuctionHouse
Address of the DebtAuctionHouse contract
IDebtAuctionHouse public debtAuctionHouse;
postSettlementSurplusDrain
The post settlement surplus drain is used to transfer remaining surplus after settlement is triggered
Usually the SettlementSurplusAuctioneer
contract
address public postSettlementSurplusDrain;
extraSurplusReceiver
The extra surplus receiver is used to transfer surplus if is not being auctioned
address public extraSurplusReceiver;
_params
Getter for the unpacked contract parameters struct
AccountingEngineParams public _params;
debtQueue
A mapping storing debtBlocks that need to be covered by auctions
A debtBlock can be popped from the queue (to be auctioned) if more than popDebtDelay
has elapsed since creation
mapping(uint256 _timestamp => uint256 _rad) public debtQueue;
totalOnAuctionDebt
The total amount of debt that is currently on auction in the DebtAuctionHouse
uint256 public totalOnAuctionDebt;
totalQueuedDebt
The total amount of debt that is currently in the debtQueue to be auctioned
uint256 public totalQueuedDebt;
lastSurplusTime
The timestamp of the last time surplus was transferred or auctioned
uint256 public lastSurplusTime;
disableTimestamp
When the contract is disabled (usually by GlobalSettlement
) it has to wait disableCooldown
before any remaining surplus can be transferred to postSettlementSurplusDrain
uint256 public disableTimestamp;
Functions
addAuthorization
Overriding method allows new authorizations only if the contract is enabled
Method will revert if the account is already authorized
function addAuthorization(address _account) external override(Authorizable, IAuthorizable) isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to authorize |
params
Getter for the contract parameters struct
function params() external view returns (AccountingEngineParams memory _accEngineParams);
Returns
Name | Type | Description |
---|---|---|
_accEngineParams | AccountingEngineParams | _params AccountingEngine parameters struct |
constructor
constructor(
address _safeEngine,
address _surplusAuctionHouse,
address _debtAuctionHouse,
AccountingEngineParams memory _accEngineParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine |
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse |
_debtAuctionHouse | address | Address of the DebtAuctionHouse |
_accEngineParams | AccountingEngineParams | Initial valid AccountingEngine parameters struct |
unqueuedUnauctionedDebt
Returns the amount of bad debt that is not in the debtQueue and is not currently handled by debt auctions
The difference between the debt in the SAFEEngine and the debt in the debtQueue and on auction
function unqueuedUnauctionedDebt() external view returns (uint256 __unqueuedUnauctionedDebt);
Returns
Name | Type | Description |
---|---|---|
__unqueuedUnauctionedDebt | uint256 | _unqueuedUnauctionedDebt Amount of debt in RAD that is currently not in the debtQueue and not on auction [rad] |
_unqueuedUnauctionedDebt
function _unqueuedUnauctionedDebt(uint256 _debtBalance) internal view returns (uint256 __unqueuedUnauctionedDebt);
pushDebtToQueue
Push a block of debt to the debt queue
Usually called by the LiquidationEngine
when a SAFE is liquidated
function pushDebtToQueue(uint256 _debtBlock) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_debtBlock | uint256 | Amount of debt to push [rad] |
popDebtFromQueue
Pop a block of debt from the debt queue
A debtBlock can be popped from the queue after popDebtDelay
seconds have passed since creation
function popDebtFromQueue(uint256 _debtBlockTimestamp) external;
Parameters
Name | Type | Description |
---|---|---|
_debtBlockTimestamp | uint256 | Timestamp of the block of debt that should be popped out |
settleDebt
Destroy an equal amount of coins and debt
It can only destroy debt that is not locked in the queue and also not in a debt auction (unqueuedUnauctionedDebt
)
function settleDebt(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt to destroy [rad] |
_settleDebt
function _settleDebt(
uint256 _coinBalance,
uint256 _debtBalance,
uint256 _rad
) internal returns (uint256 _newCoinBalance, uint256 _newDebtBalance);
cancelAuctionedDebtWithSurplus
Use surplus coins to destroy debt that was in a debt auction
Usually called by the DebtAuctionHouse
after a debt bid is made
function cancelAuctionedDebtWithSurplus(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt to destroy with surplus [rad] |
auctionDebt
Start a debt auction (print protocol tokens in exchange for coins so that the system can be recapitalized)
It can only auction debt that has been popped from the debt queue and is not already being auctioned
function auctionDebt() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the debt auction that was started |
auctionSurplus
Start a surplus auction (sell surplus stability fees for protocol tokens)
It can only auction surplus if surplusIsTransferred
is set to false
function auctionSurplus() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the surplus auction that was started |
transferExtraSurplus
Transfer surplus to an address as an alternative to surplus auctions
It can only transfer surplus if surplusIsTransferred
is set to true
function transferExtraSurplus() external;
_onContractDisable
Runtime to be run when the contract is disabled (normally triggered by GlobalSettlement)
When it's being disabled, the contract will record the current timestamp. Afterwards, the contract tries to settle as much debt as possible (if there's any) with any surplus that's left in the AccountingEngine
function _onContractDisable() internal override;
transferPostSettlementSurplus
Transfer any remaining surplus after the disable cooldown has passed. Meant to be a backup in case GlobalSettlement.processSAFE has a bug, governance doesn't have power over the system and there's still surplus left in the AccountingEngine which then blocks GlobalSettlement.setOutstandingCoinSupply.
Transfer any remaining surplus after disableCooldown
seconds have passed since disabling the contract
function transferPostSettlementSurplus() external whenDisabled;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_setSurplusAuctionHouse
Set the surplus auction house, deny permissions on the old one and approve on the new one
function _setSurplusAuctionHouse(address _surplusAuctionHouse) internal;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
CollateralAuctionHouse
Inherits: Authorizable, Modifiable, Disableable, ICollateralAuctionHouse
This contract enables the sell of a confiscated collateral in exchange for system coins to cover a SAFE's debt
State Variables
AUCTION_HOUSE_TYPE
Type of the auction house
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32('COLLATERAL');
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
_liquidationEngine
Internal storage variable to allow overrides in child implementation contract
ILiquidationEngine internal _liquidationEngine;
_oracleRelayer
Internal storage variable to allow overrides in child implementation contract
IOracleRelayer internal _oracleRelayer;
collateralType
The collateral type of the auctions created by this contract
bytes32 public collateralType;
auctionsStarted
Total amount of collateral auctions created
uint256 public auctionsStarted;
_auctions
Unpacked data of an auction
mapping(uint256 _auctionId => Auction) public _auctions;
_params
Getter for the unpacked contract parameters struct
CollateralAuctionHouseParams public _params;
Functions
liquidationEngine
Address of the LiquidationEngine contract
function liquidationEngine() public view virtual returns (ILiquidationEngine __liquidationEngine);
oracleRelayer
Address of the OracleRelayer contract
function oracleRelayer() public view virtual returns (IOracleRelayer __oracleRelayer);
auctions
Data of an auction
function auctions(uint256 _auctionId) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_auctionId | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
params
Getter for the contract parameters struct
function params() external view returns (CollateralAuctionHouseParams memory _cahParams);
Returns
Name | Type | Description |
---|---|---|
_cahParams | CollateralAuctionHouseParams | Auction house parameters struct |
constructor
constructor(
address _safeEngine,
address __liquidationEngine,
address __oracleRelayer,
bytes32 _cType,
CollateralAuctionHouseParams memory _cahParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
__liquidationEngine | address | Address of the LiquidationEngine contract |
__oracleRelayer | address | Address of the OracleRelayer contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_cahParams | CollateralAuctionHouseParams | Initial valid CollateralAuctionHouse parameters struct |
_getBoughtCollateral
Get the amount of bought collateral from a specific auction using collateral and system coin prices, with a custom discount
The inputted bid is capped to the amount of system coins needed to buy all collateral
function _getBoughtCollateral(
uint256 _collateralPrice,
uint256 _systemCoinPrice,
uint256 _amountToSell,
uint256 _adjustedBid,
uint256 _customDiscount
) internal pure returns (uint256 _boughtCollateral, uint256 _readjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_collateralPrice | uint256 | The collateral price fetched from the Oracle |
_systemCoinPrice | uint256 | The system coin redemption price fetched from the OracleRelayer |
_amountToSell | uint256 | The amount of collateral being auctioned |
_adjustedBid | uint256 | The limited system coin bid |
_customDiscount | uint256 | The discount offered |
Returns
Name | Type | Description |
---|---|---|
_boughtCollateral | uint256 | Amount of collateral bought for given parameters |
_readjustedBid | uint256 | Amount of system coins actually used to buy the collateral |
_getCollateralPrice
Get the collateral price from the oracle
function _getCollateralPrice() internal view returns (uint256 _collateralPrice);
Returns
Name | Type | Description |
---|---|---|
_collateralPrice | uint256 | The collateral price if valid [wad] |
_getAuctionDiscount
Get the upcoming discount that will be used in a specific auction
function _getAuctionDiscount(uint256 _id) internal view returns (uint256 _auctionDiscount);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | The ID of the auction to calculate the upcoming discount for |
Returns
Name | Type | Description |
---|---|---|
_auctionDiscount | uint256 | The upcoming discount that will be used in the targeted auction |
_getAdjustedBid
Get the actual bid that will be used in an auction (taking into account the bidder input)
The inputted bid is capped to the amount of system coins the auction needs to raise
function _getAdjustedBid(uint256 _id, uint256 _wad) internal view returns (uint256 _adjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | The id of the auction to calculate the adjusted bid for |
_wad | uint256 | The initial bid submitted |
Returns
Name | Type | Description |
---|---|---|
_adjustedBid | uint256 | The adjusted bid |
startAuction
Starts a new collateral auction
function startAuction(
address _forgoneCollateralReceiver,
address _auctionIncomeRecipient,
uint256 _amountToRaise,
uint256 _amountToSell
) external isAuthorized whenEnabled returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_forgoneCollateralReceiver | address | Who receives leftover collateral that is not sold in the auction (usually the liquidated SAFE) |
_auctionIncomeRecipient | address | Who receives the coins raised by the auction (usually the AccountingEngine) |
_amountToRaise | uint256 | Total/max amount of coins to raise [rad] |
_amountToSell | uint256 |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the started auction |
getAuctionDiscount
Calculates the current discount of an auction
function getAuctionDiscount(uint256 _id) external view returns (uint256 _auctionDiscount);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auctionDiscount | uint256 | Current discount of the auction [wad %] |
getCollateralBought
Calculates the amount of collateral that will be bought with a given bid
function getCollateralBought(
uint256 _id,
uint256 _wad
) external view returns (uint256 _boughtCollateral, uint256 _adjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_wad | uint256 | Bid amount [wad] |
Returns
Name | Type | Description |
---|---|---|
_boughtCollateral | uint256 | _collateralBought Amount of collateral that will be bought [wad] |
_adjustedBid | uint256 | Adjusted bid amount [wad] |
buyCollateral
Buys collateral from an auction
function buyCollateral(
uint256 _id,
uint256 _wad
) external whenEnabled returns (uint256 _boughtCollateral, uint256 _adjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_wad | uint256 | Bid amount [wad] |
Returns
Name | Type | Description |
---|---|---|
_boughtCollateral | uint256 | Amount of collateral that was bought [wad] |
_adjustedBid | uint256 | Adjusted bid amount [wad] |
terminateAuctionPrematurely
Terminates an auction prematurely
Transfers collateral and coins to the authorized caller address
function terminateAuctionPrematurely(uint256 _id) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal virtual override;
_setLiquidationEngine
Sets the LiquidationEngine contract address, revoking the previous, and granting the new one authorization
function _setLiquidationEngine(address _newLiquidationEngine) internal virtual;
_setOracleRelayer
Sets the OracleRelayer contract address
function _setOracleRelayer(address _newOracleRelayer) internal virtual;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
DebtAuctionHouse
Inherits: Authorizable, Modifiable, Disableable, IDebtAuctionHouse
This contract enables the sell of newly minted protocol tokens in exchange for system coins to cover a protocol debt
State Variables
AUCTION_HOUSE_TYPE
Type of the auction house
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32('DEBT');
_auctions
Unpacked data of an auction
mapping(uint256 _auctionId => Auction) public _auctions;
auctionsStarted
Total amount of debt auctions created
uint256 public auctionsStarted;
activeDebtAuctions
Total amount of simultaneous active debt auctions
uint256 public activeDebtAuctions;
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
protocolToken
Address of the ProtocolToken contract
IProtocolToken public protocolToken;
accountingEngine
Address of the AccountingEngine contract
address public accountingEngine;
_params
Getter for the unpacked contract parameters struct
DebtAuctionHouseParams public _params;
Functions
auctions
Data of an auction
function auctions(uint256 _id) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
params
Getter for the contract parameters struct
function params() external view returns (DebtAuctionHouseParams memory _dahParams);
Returns
Name | Type | Description |
---|---|---|
_dahParams | DebtAuctionHouseParams | Auction house parameters struct |
constructor
constructor(
address _safeEngine,
address _protocolToken,
DebtAuctionHouseParams memory _dahParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_protocolToken | address | Address of the protocol governance token |
_dahParams | DebtAuctionHouseParams | Initial valid DebtAuctionHouse parameters struct |
_onContractDisable
Internal virtual method to be called when the contract is disabled
Sets the accountingEngine state var to the caller's address
function _onContractDisable() internal override;
startAuction
Start a new debt auction
function startAuction(
address _incomeReceiver,
uint256 _amountToSell,
uint256 _initialBid
) external isAuthorized whenEnabled returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_incomeReceiver | address | Who receives the auction proceeds |
_amountToSell | uint256 | Initial amount of protocol tokens to be minted [wad] |
_initialBid | uint256 | Amount of debt to be sold [rad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
restartAuction
Restart an auction if no bids were placed
An auction can be restarted if the auction expired with no bids
function restartAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
decreaseSoldAmount
Decrease the protocol token amount you're willing to receive in exchange for providing the same amount of system coins being raised by the auction
function decreaseSoldAmount(uint256 _id, uint256 _amountToBuy) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction for which you want to submit a new bid |
_amountToBuy | uint256 | Amount of protocol tokens to buy (must be smaller than the previous proposed amount) [wad] |
settleAuction
Settle an auction
Can only be called after the auction expired with a winning bid
function settleAuction(uint256 _id) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
terminateAuctionPrematurely
Terminate an auction prematurely
Can only be called after the contract is disabled
function terminateAuctionPrematurely(uint256 _id) external whenDisabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
LiquidationEngine
Inherits: Authorizable, Disableable, Modifiable, ModifiablePerCollateral, ReentrancyGuard, ILiquidationEngine
Handles the liquidations of SAFEs if the accumulated debt is higher than the collateral liquidation value
State Variables
safeSaviours
Allowed contracts that can be chosen to save SAFEs from liquidation
mapping(address _saviour => bool _allowed) public safeSaviours;
chosenSAFESaviour
Saviour contract chosen for each SAFE by its owner
mapping(bytes32 _cType => mapping(address _safe => address _saviour)) public chosenSAFESaviour;
currentOnAuctionSystemCoins
Total amount of system coins currently being auctioned
uint256 public currentOnAuctionSystemCoins;
safeEngine
The SAFEEngine is used to query the state of the SAFEs, confiscate the collateral and transfer the debt
ISAFEEngine public safeEngine;
accountingEngine
The AccountingEngine is used to push the debt into the system, and set as the first bidder on the collateral auctions
IAccountingEngine public accountingEngine;
_params
Getter for the unpacked contract parameters struct
LiquidationEngineParams public _params;
_cParams
Getter for the unpacked collateral parameters struct
mapping(bytes32 _cType => LiquidationEngineCollateralParams) public _cParams;
Functions
params
Getter for the contract parameters struct
function params() external view returns (LiquidationEngineParams memory _liqEngineParams);
Returns
Name | Type | Description |
---|---|---|
_liqEngineParams | LiquidationEngineParams | LiquidationEngine parameters struct |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (LiquidationEngineCollateralParams memory _liqEngineCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_liqEngineCParams | LiquidationEngineCollateralParams | LiquidationEngine collateral parameters struct |
constructor
constructor(
address _safeEngine,
address _accountingEngine,
LiquidationEngineParams memory _liqEngineParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_accountingEngine | address | Address of the AccountingEngine contract |
_liqEngineParams | LiquidationEngineParams | Initial valid LiquidationEngine parameters struct |
connectSAFESaviour
Authed function to add contracts that can save SAFEs from liquidation
function connectSAFESaviour(address _saviour) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract to be whitelisted |
disconnectSAFESaviour
Authed function to remove contracts that can save SAFEs from liquidation
function disconnectSAFESaviour(address _saviour) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract to be removed |
protectSAFE
Choose a saviour contract for your SAFE
function protectSAFE(bytes32 _cType, address _safe, address _saviour) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
_saviour | address | The chosen saviour |
liquidateSAFE
Liquidate a SAFE
A SAFE can be liquidated if the accumulated debt plus the liquidation penalty is higher than the collateral value
function liquidateSAFE(bytes32 _cType, address _safe) external whenEnabled nonReentrant returns (uint256 _auctionId);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
Returns
Name | Type | Description |
---|---|---|
_auctionId | uint256 | The auction id of the collateral auction |
attemptSave
function attemptSave(
bytes32 _cType,
address _safe,
address _liquidator,
ISAFEEngine.SAFE calldata _safeData
) external returns (ISAFEEngine.SAFE memory _newSafeData);
removeCoinsFromAuction
Remove debt that was being auctioned
Usually called by CollateralAuctionHouse when an auction is settled
function removeCoinsFromAuction(uint256 _rad) public isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | The amount of debt in RAD to withdraw from currentOnAuctionSystemCoins |
getLimitAdjustedDebtToCover
The limit adjusted debt to cover
function getLimitAdjustedDebtToCover(
bytes32 _cType,
address _safe
) external view returns (uint256 _limitAdjustedDebtToCover);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
Returns
Name | Type | Description |
---|---|---|
_limitAdjustedDebtToCover | uint256 | _wad The limit adjusted debt to cover |
_getLimitAdjustedDebt
function _getLimitAdjustedDebt(
uint256 _generatedDebt,
uint256 _accumulatedRate,
uint256 _liquidationQuantity,
uint256 _liquidationPenalty,
uint256 _debtFloor
) internal pure returns (uint256 _limitAdjustedDebt);
_initializeCollateralType
Register a new collateral type in the SAFEEngine
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal override whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
_validateCParameters
Internal function to be overriden with custom logic to validate collateral parameters
function _validateCParameters(bytes32 _cType) internal view override;
_setCollateralAuctionHouse
Set the collateral auction house, deny permissions on the old one and approve on the new one
function _setCollateralAuctionHouse(bytes32 _cType, address _newCollateralAuctionHouse) internal;
OracleRelayer
Inherits: Authorizable, Disableable, Modifiable, ModifiablePerCollateral, IOracleRelayer
Handles the collateral prices inside the system (SAFEEngine) and calculates the redemption price using the rate
State Variables
safeEngine
The SAFEEngine is called to update the price of the collateral in the system
ISAFEEngine public safeEngine;
systemCoinOracle
The oracle used to fetch the system coin market price
IBaseOracle public systemCoinOracle;
_params
Getter for the unpacked contract parameters struct
OracleRelayerParams public _params;
_cParams
Getter for the unpacked collateral parameters struct
mapping(bytes32 _cType => OracleRelayerCollateralParams) public _cParams;
_redemptionPrice
Virtual redemption price (not the most updated value) [ray]
uint256 internal _redemptionPrice;
redemptionRate
The redemption rate is the rate at which the redemption price changes over time
By changing the redemption rate, it changes the incentives of the system users
uint256 public redemptionRate;
redemptionPriceUpdateTime
Last time when the redemption price was changed
Used to calculate the current redemption price
uint256 public redemptionPriceUpdateTime;
Functions
params
Getter for the contract parameters struct
function params() external view override returns (OracleRelayerParams memory _oracleRelayerParams);
Returns
Name | Type | Description |
---|---|---|
_oracleRelayerParams | OracleRelayerParams | An OracleRelayerParams struct |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (OracleRelayerCollateralParams memory _oracleRelayerCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_oracleRelayerCParams | OracleRelayerCollateralParams | An OracleRelayerCollateralParams struct |
constructor
constructor(
address _safeEngine,
IBaseOracle _systemCoinOracle,
OracleRelayerParams memory _oracleRelayerParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine |
_systemCoinOracle | IBaseOracle | Address of the system coin oracle |
_oracleRelayerParams | OracleRelayerParams | Initial OracleRelayer valid parameters struct |
marketPrice
The current system coin market price
function marketPrice() external view returns (uint256 _marketPrice);
Returns
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The current system coin market price [ray] |
calcRedemptionPrice
View method to fetch the current redemption price
To be used within view functions, not to be used in transactions, use redemptionPrice
instead
function calcRedemptionPrice() external view returns (uint256 _virtualRedemptionPrice);
Returns
Name | Type | Description |
---|---|---|
_virtualRedemptionPrice | uint256 | _redemptionPrice The current calculated redemption price [ray] |
_updateRedemptionPrice
Calculates and updates the redemption price using the current redemption rate
function _updateRedemptionPrice() internal virtual returns (uint256 _updatedPrice);
redemptionPrice
Fetch the latest redemption price by first updating it
function redemptionPrice() external returns (uint256 _updatedPrice);
Returns
Name | Type | Description |
---|---|---|
_updatedPrice | uint256 | The newly updated redemption price [ray] |
_getRedemptionPrice
Avoids reupdating the redemptionPrice if no seconds have passed since last update
function _getRedemptionPrice() internal virtual returns (uint256 _updatedPrice);
updateCollateralPrice
Update the collateral price inside the system (inside SAFEEngine)
Usually called by a keeper, incentivized by the system to keep the prices up to date
function updateCollateralPrice(bytes32 _cType) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
updateRedemptionRate
Update the system redemption rate, the rate at which the redemption price changes over time
Usually called by the PIDRateSetter
function updateRedemptionRate(uint256 _redemptionRate) external isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The newly calculated redemption rate [ray] |
_onContractDisable
Internal virtual method to be called when the contract is disabled
Sets the redemption rate to 1 (no change in the redemption price)
function _onContractDisable() internal override;
_initializeCollateralType
Register a new collateral type in the SAFEEngine
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override whenEnabled;
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal override whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
_validateCParameters
Internal function to be overriden with custom logic to validate collateral parameters
function _validateCParameters(bytes32 _cType) internal view override;
PIDController
Inherits: Authorizable, Modifiable, IPIDController
Redemption Rate Feedback Mechanism (RRFM) controller that implements a PI controller
State Variables
_NEGATIVE_RATE_LIMIT
The lower (when negative) bound for the redemption rate
Represents a rate of -99.999% per second (as -100% is not allowed) in RAY precision
uint256 internal constant _NEGATIVE_RATE_LIMIT = RAY - 1;
_POSITIVE_RATE_LIMIT
The upper bound for the redemption rate
Maximum possible value that can be safely casted to int256
uint256 internal constant _POSITIVE_RATE_LIMIT = uint256(type(int256).max);
seedProposer
Returns the address allowed to call computeRate method
address public seedProposer;
_params
Getter for the unpacked contract parameters struct
PIDControllerParams public _params;
_deviationObservation
Raw data about the last deviation observation
The last deviation observation, containing latest timestamp, proportional and integral terms
DeviationObservation public _deviationObservation;
_controllerGains
Raw data about the Kp and Ki values used in this calculator
ControllerGains public _controllerGains;
Functions
params
Getter for the contract parameters struct
function params() external view returns (PIDControllerParams memory _pidParams);
Returns
Name | Type | Description |
---|---|---|
_pidParams | PIDControllerParams | The PID controller parameters struct |
deviationObservation
Returns the last deviation observation, containing latest timestamp, proportional and integral terms
function deviationObservation() external view returns (DeviationObservation memory __deviationObservation);
Returns
Name | Type | Description |
---|---|---|
__deviationObservation | DeviationObservation | The last deviation observation struct |
controllerGains
Returns the Kp and Ki values used in this calculator
The values are expressed in WAD, Kp stands for proportional and Ki for integral terms
function controllerGains() external view returns (ControllerGains memory _cGains);
constructor
constructor(
ControllerGains memory _cGains,
PIDControllerParams memory _pidParams,
DeviationObservation memory _importedState
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_cGains | ControllerGains | Initial valid controller gains settings struct |
_pidParams | PIDControllerParams | Initial valid PID controller parameters struct |
_importedState | DeviationObservation | Imported initial state of the controller (optional) |
getBoundedRedemptionRate
Return a redemption rate bounded by feedbackOutputLowerBound and feedbackOutputUpperBound as well as the timeline over which that rate will take effect
function getBoundedRedemptionRate(int256 _piOutput) external view returns (uint256 _newRedemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_piOutput | int256 | The raw redemption rate computed from the proportional and integral terms |
Returns
Name | Type | Description |
---|---|---|
_newRedemptionRate | uint256 | _redemptionRate The bounded redemption rate |
_getBoundedRedemptionRate
Computes the new redemption rate by taking into account the feedbackOutputUpperBound and feedbackOutputLowerBound
function _getBoundedRedemptionRate(int256 _piOutput) internal view virtual returns (uint256 _newRedemptionRate);
_getBoundedPIOutput
Computes the pi output by taking into account the feedbackOutputUpperBound and feedbackOutputLowerBound
function _getBoundedPIOutput(int256 _piOutput) internal view virtual returns (int256 _boundedPIOutput);
computeRate
Compute a new redemption rate
function computeRate(uint256 _marketPrice, uint256 _redemptionPrice) external returns (uint256 _newRedemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The system coin market price |
_redemptionPrice | uint256 | The system coin redemption price |
Returns
Name | Type | Description |
---|---|---|
_newRedemptionRate | uint256 | _redemptionRate The computed redemption rate |
_getProportionalTerm
Computes the proportional term using the scaled difference between market price and redemption price
function _getProportionalTerm(
uint256 _marketPrice,
uint256 _redemptionPrice
) internal view virtual returns (int256 _proportionalTerm);
breaksNoiseBarrier
Returns whether the P + I sum exceeds the noise barrier
function breaksNoiseBarrier(uint256 _piSum, uint256 _redemptionPrice) external view virtual returns (bool _breaksNb);
Parameters
Name | Type | Description |
---|---|---|
_piSum | uint256 | Represents a sum between P + I |
_redemptionPrice | uint256 | The system coin redemption price |
Returns
Name | Type | Description |
---|---|---|
_breaksNb | bool | Whether the P + I sum exceeds the noise barrier |
_breaksNoiseBarrier
Returns whether the P + I sum exceeds the noise barrier
function _breaksNoiseBarrier(uint256 _piSum, uint256 _redemptionPrice) internal view virtual returns (bool _breaksNb);
getGainAdjustedPIOutput
Apply Kp to the proportional term and Ki to the integral term (by multiplication) and then sum P and I
function getGainAdjustedPIOutput(
int256 _proportionalTerm,
int256 _integralTerm
) external view returns (int256 _gainAdjustedPIOutput);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term |
_integralTerm | int256 | The integral term |
Returns
Name | Type | Description |
---|---|---|
_gainAdjustedPIOutput | int256 | _piOutput The sum of P and I |
_getGainAdjustedPIOutput
Computes the gain adjusted PI output by multiplying P by Kp and I by Ki and then sum P & I
function _getGainAdjustedPIOutput(
int256 _proportionalTerm,
int256 _integralTerm
) internal view virtual returns (int256 _adjustedPIOutput);
_getGainAdjustedTerms
Computes the gain adjusted terms by multiplying P by Kp and I by Ki
function _getGainAdjustedTerms(
int256 _proportionalTerm,
int256 _integralTerm
) internal view virtual returns (int256 _ajustedProportionalTerm, int256 _adjustedIntegralTerm);
getGainAdjustedTerms
Independently return and calculate P * Kp and I * Ki
function getGainAdjustedTerms(
int256 _proportionalTerm,
int256 _integralTerm
) external view returns (int256 _ajustedProportionalTerm, int256 _adjustedIntegralTerm);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term |
_integralTerm | int256 | The integral term |
Returns
Name | Type | Description |
---|---|---|
_ajustedProportionalTerm | int256 | _proportionalGain The proportional gain |
_adjustedIntegralTerm | int256 | _integralGain The integral gain |
_updateDeviation
Push new observations in deviationObservations while also updating priceDeviationCumulative
function _updateDeviation(
int256 _proportionalTerm,
uint256 _accumulatedLeak
) internal virtual returns (int256 _integralTerm);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportionalTerm |
_accumulatedLeak | uint256 | The total leak (similar to a negative interest rate) applied to priceDeviationCumulative before proportionalTerm is added to it |
getNextDeviationCumulative
Compute a new priceDeviationCumulative (integral term)
function getNextDeviationCumulative(
int256 _proportionalTerm,
uint256 _accumulatedLeak
) external view returns (int256 _nextDeviationCumulative, int256 _appliedDeviation);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term (redemptionPrice - marketPrice) |
_accumulatedLeak | uint256 | The total leak applied to priceDeviationCumulative before it is summed with the new time adjusted deviation |
Returns
Name | Type | Description |
---|---|---|
_nextDeviationCumulative | int256 | _priceDeviationCumulative The new priceDeviationCumulative |
_appliedDeviation | int256 | _timeAdjustedDeviation The new time adjusted deviation |
_getNextDeviationCumulative
Computes the new priceDeviationCumulative (integral term)
function _getNextDeviationCumulative(
int256 _proportionalTerm,
uint256 _accumulatedLeak
) internal view virtual returns (int256 _nextDeviationCumulative, int256 _appliedDeviation);
getNextRedemptionRate
Compute and return the upcoming redemption rate
This method is used to provide a view of the next redemption rate without updating the state of the controller
function getNextRedemptionRate(
uint256 _marketPrice,
uint256 _redemptionPrice,
uint256 _accumulatedLeak
) external view returns (uint256 _redemptionRate, int256 _proportionalTerm, int256 _integralTerm);
Parameters
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The system coin market price |
_redemptionPrice | uint256 | The system coin redemption price |
_accumulatedLeak | uint256 | The total leak applied to priceDeviationCumulative before it is summed with the proportionalTerm |
Returns
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The upcoming redemption rate |
_proportionalTerm | int256 | The upcoming proportional term |
_integralTerm | int256 | The upcoming integral term |
timeSinceLastUpdate
Returns the time elapsed since the last computeRate call
function timeSinceLastUpdate() external view returns (uint256 _elapsed);
_timeSinceLastUpdate
function _timeSinceLastUpdate() internal view returns (uint256 _elapsed);
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
PIDRateSetter
Inherits: Authorizable, Modifiable, IPIDRateSetter
This contract is used to trigger the update of the redemption rate using the PID controller
State Variables
oracleRelayer
The oracle relayer where the redemption price and rate are stored
IOracleRelayer public oracleRelayer;
pidCalculator
The PID calculator used to compute the redemption rate
IPIDController public pidCalculator;
_params
Getter for the unpacked contract parameters struct
PIDRateSetterParams public _params;
lastUpdateTime
The timestamp of the last update
uint256 public lastUpdateTime;
Functions
params
Getter for the contract parameters struct
function params() external view returns (PIDRateSetterParams memory _pidRateSetterParams);
Returns
Name | Type | Description |
---|---|---|
_pidRateSetterParams | PIDRateSetterParams | PIDRateSetter parameters struct |
constructor
constructor(
address _oracleRelayer,
address _pidCalculator,
PIDRateSetterParams memory _pidRateSetterParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_oracleRelayer | address | Address of the oracle relayer |
_pidCalculator | address | Address of the PID calculator |
_pidRateSetterParams | PIDRateSetterParams | Initial valid PID rate setter parameters struct |
updateRate
Compute and set a new redemption rate
function updateRate() external;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
SAFEEngine
Inherits: Authorizable, Disableable, Modifiable, ModifiablePerCollateral, ISAFEEngine
Core contract that manages the state of the SAFE system
State Variables
_params
Getter for the unpacked contract parameters struct
SAFEEngineParams public _params;
_cParams
Getter for the unpacked collateral parameters struct
mapping(bytes32 _cType => SAFEEngineCollateralParams) public _cParams;
_cData
Getter for the unpacked collateral data struct
mapping(bytes32 _cType => SAFEEngineCollateralData) public _cData;
_safes
Unpacked data about each SAFE
mapping(bytes32 _cType => mapping(address _safe => SAFE)) public _safes;
safeRights
Who can transfer collateral & debt in/out of a SAFE
mapping(address _caller => mapping(address _account => bool _isAllowed)) public safeRights;
tokenCollateral
Balance of each collateral type
mapping(bytes32 _cType => mapping(address _safe => uint256 _wad)) public tokenCollateral;
coinBalance
Internal balance of system coins held by an account
mapping(address _safe => uint256 _rad) public coinBalance;
debtBalance
Amount of debt held by an account
mapping(address _safe => uint256 _rad) public debtBalance;
globalDebt
Total amount of debt (coins) currently issued
uint256 public globalDebt;
globalUnbackedDebt
'Bad' debt that's not covered by collateral
uint256 public globalUnbackedDebt;
Functions
params
Getter for the contract parameters struct
function params() external view returns (SAFEEngineParams memory _safeEngineParams);
Returns
Name | Type | Description |
---|---|---|
_safeEngineParams | SAFEEngineParams | The active SAFEEngineParams |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (SAFEEngineCollateralParams memory _safeEngineCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_safeEngineCParams | SAFEEngineCollateralParams | SAFEEngineCollateralParams for the collateral type |
cData
Getter for the collateral data struct
function cData(bytes32 _cType) external view returns (SAFEEngineCollateralData memory _safeEngineCData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_safeEngineCData | SAFEEngineCollateralData | SAFEEngineCollateralData for the collateral type |
safes
Data about each SAFE
function safes(bytes32 _cType, address _safe) external view returns (SAFE memory _safeData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address |
Returns
Name | Type | Description |
---|---|---|
_safeData | SAFE | SAFE data for the specified collateral type of the specified safe. |
constructor
constructor(SAFEEngineParams memory _safeEngineParams) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngineParams | SAFEEngineParams | Initial SAFEEngine valid parameters struct |
transferCollateral
Transfer collateral between accounts
function transferCollateral(
bytes32 _cType,
address _source,
address _destination,
uint256 _wad
) external isSAFEAllowed(_source, msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type transferred |
_source | address | Collateral source |
_destination | address | Collateral destination |
_wad | uint256 | Amount of collateral transferred |
transferInternalCoins
Transfer internal coins (does not affect external balances from Coin.sol)
function transferInternalCoins(
address _source,
address _destination,
uint256 _rad
) external isSAFEAllowed(_source, msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_source | address | Coins source |
_destination | address | Coins destination |
_rad | uint256 | Amount of coins transferred |
modifyCollateralBalance
Join/exit collateral into and and out of the system
function modifyCollateralBalance(bytes32 _cType, address _account, int256 _wad) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to join/exit |
_account | address | Account that gets credited/debited |
_wad | int256 | Amount of collateral |
modifySAFECollateralization
Add/remove collateral or put back/generate more debt in a SAFE
function modifySAFECollateralization(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Type of collateral to withdraw/deposit in and from the SAFE |
_safe | address | Target SAFE |
_collateralSource | address | Account we take collateral from/put collateral into |
_debtDestination | address | Account from which we credit/debit coins and debt |
_deltaCollateral | int256 | Amount of collateral added/extracted from the SAFE [wad] |
_deltaDebt | int256 | Amount of debt to generate/repay [wad] |
transferSAFECollateralAndDebt
Transfer collateral and/or debt between SAFEs
function transferSAFECollateralAndDebt(
bytes32 _cType,
address _src,
address _dst,
int256 _deltaCollateral,
int256 _deltaDebt
) external isSAFEAllowed(_src, msg.sender) isSAFEAllowed(_dst, msg.sender);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type transferred between SAFEs |
_src | address | Source SAFE |
_dst | address | Destination SAFE |
_deltaCollateral | int256 | Amount of collateral to take/add into src and give/take from dst [wad] |
_deltaDebt | int256 | Amount of debt to take/add into src and give/take from dst [wad] |
confiscateSAFECollateralAndDebt
Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else
function confiscateSAFECollateralAndDebt(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type the SAFE has locked inside |
_safe | address | Target SAFE |
_collateralSource | address | Who we take/give collateral to |
_debtDestination | address | Who we take/give debt to |
_deltaCollateral | int256 | Amount of collateral taken/added into the SAFE [wad] |
_deltaDebt | int256 | Amount of debt taken/added into the SAFE [wad] |
settleDebt
Nullify an amount of coins with an equal amount of debt
Coins & debt are like matter and antimatter, they nullify each other
function settleDebt(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of debt & coins to destroy |
createUnbackedDebt
Allows an authorized contract to create debt without collateral
Usually called by DebtAuctionHouse in order to terminate auctions prematurely post settlement
function createUnbackedDebt(address _debtDestination, address _coinDestination, uint256 _rad) external isAuthorized;
Parameters
Name | Type | Description |
---|---|---|
_debtDestination | address | The account that will receive the newly created debt |
_coinDestination | address | The account that will receive the newly created coins |
_rad | uint256 | Amount of debt to create |
updateAccumulatedRate
Allows an authorized contract to accrue interest on a specific collateral type
The rateMultiplier is usually calculated by the TaxCollector contract
function updateAccumulatedRate(
bytes32 _cType,
address _surplusDst,
int256 _rateMultiplier
) external isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type we accrue interest for |
_surplusDst | address | Destination for the newly created surplus |
_rateMultiplier | int256 | Multiplier applied to the debtAmount in order to calculate the surplus [ray] |
updateCollateralPrice
Allows an authorized contract to update the safety price and liquidation price of a collateral type
function updateCollateralPrice(
bytes32 _cType,
uint256 _safetyPrice,
uint256 _liquidationPrice
) external isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type we update the prices for |
_safetyPrice | uint256 | New safety price [ray] |
_liquidationPrice | uint256 | New liquidation price [ray] |
addAuthorization
Add auth to an account
This overriden method avoids adding new authorizations after the contract has been disabled
function addAuthorization(address _account) external override(Authorizable, IAuthorizable) isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to add auth to |
removeAuthorization
Remove auth from an account
function removeAuthorization(address _account) external override(Authorizable, IAuthorizable) isAuthorized whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to remove auth from |
approveSAFEModification
Allow an address to modify your SAFE
function approveSAFEModification(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to give SAFE permissions to |
denySAFEModification
Deny an address the rights to modify your SAFE
function denySAFEModification(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that is denied SAFE permissions |
canModifySAFE
Checks whether an account has the right to modify a SAFE
function canModifySAFE(address _safe, address _account) public view returns (bool _canModifySafe);
Parameters
Name | Type | Description |
---|---|---|
_safe | address | The safe to check |
_account | address | The account to check |
Returns
Name | Type | Description |
---|---|---|
_canModifySafe | bool | _allowed Whether the account can modify the safe |
_modifyCollateralBalance
function _modifyCollateralBalance(bytes32 _cType, address _account, int256 _wad) internal;
_modifyInternalCoins
function _modifyInternalCoins(address _dst, int256 _rad) internal;
_modifySAFECollateralization
function _modifySAFECollateralization(
bytes32 _cType,
address _safe,
int256 _deltaCollateral,
int256 _deltaDebt
) internal;
_emitTransferCollateral
function _emitTransferCollateral(bytes32 _cType, address _src, address _dst, int256 _deltaCollateral) internal;
_initializeCollateralType
Register a new collateral type in the SAFEEngine
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal override whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
isSAFEAllowed
modifier isSAFEAllowed(address _safe, address _account);
StabilityFeeTreasury
Inherits: Authorizable, Modifiable, Disableable, IStabilityFeeTreasury
This contract is in charge of distributing the accrued stability fees to allowed addresses
State Variables
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
systemCoin
Address of the SystemCoin contract
ISystemCoin public systemCoin;
coinJoin
Address of the CoinJoin contract
ICoinJoin public coinJoin;
extraSurplusReceiver
Address that receives surplus funds when treasury exceeds capacity (or is disabled)
address public extraSurplusReceiver;
_params
Getter for the unpacked contract parameters struct
StabilityFeeTreasuryParams public _params;
_allowance
Getter for the unpacked allowance struct of a given account
A null per hour allowance means that the account has no per hour limit
mapping(address _account => Allowance) public _allowance;
pulledPerHour
Amount of internal coins a given account has pulled from the treasury in a given block hour
mapping(address _account => mapping(uint256 _blockHour => uint256 _rad)) public pulledPerHour;
latestSurplusTransferTime
Timestamp of the last time that surplus funds were transferred
uint256 public latestSurplusTransferTime;
Functions
params
Getter for the contract parameters struct
function params() external view returns (StabilityFeeTreasuryParams memory _sfTreasuryParams);
Returns
Name | Type | Description |
---|---|---|
_sfTreasuryParams | StabilityFeeTreasuryParams | StabilityFee parameters struct |
allowance
Getter for the allowance struct of a given account
function allowance(address _account) external view returns (Allowance memory __allowance);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to query |
Returns
Name | Type | Description |
---|---|---|
__allowance | Allowance | Data structure containing total and per hour allowance for the given account |
accountNotTreasury
Modifier to check if an account is not the treasury (this contract)
This modifier is used to prevent the treasury from giving funds to itself
modifier accountNotTreasury(address _account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to check whether it's the treasury or not |
constructor
constructor(
address _safeEngine,
address _extraSurplusReceiver,
address _coinJoin,
StabilityFeeTreasuryParams memory _sfTreasuryParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_extraSurplusReceiver | address | Address that receives surplus funds when treasury exceeds capacity |
_coinJoin | address | Address of the CoinJoin contract |
_sfTreasuryParams | StabilityFeeTreasuryParams | Initial valid StabilityFeeTreasury parameters struct |
_onContractDisable
Disable this contract (normally called by GlobalSettlement)
This method is virtual and should be overriden to implement
function _onContractDisable() internal override;
_joinAllCoins
Join all ERC20 system coins that the treasury has inside the SAFEEngine
Converts all ERC20 system coins to internal system coins
function _joinAllCoins() internal;
settleDebt
Settle as much bad debt as possible (if this contract has any)
function settleDebt() external returns (uint256 _coinBalance, uint256 _debtBalance);
Returns
Name | Type | Description |
---|---|---|
_coinBalance | uint256 | Amount of internal system coins that this contract has after settling debt |
_debtBalance | uint256 | Amount of bad debt that this contract has after settling debt |
_settleDebt
Settle as much bad debt as possible (if this contract has any)
function _settleDebt() internal returns (uint256 _coinBalance, uint256 _debtBalance);
Returns
Name | Type | Description |
---|---|---|
_coinBalance | uint256 | Amount of internal system coins that this contract has after settling debt |
_debtBalance | uint256 | Amount of bad debt that this contract has after settling debt |
setTotalAllowance
Modify an address' total allowance in order to withdraw SF from the treasury
function setTotalAllowance(address _account, uint256 _rad) external isAuthorized accountNotTreasury(_account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The approved address |
_rad | uint256 | The total approved amount of SF to withdraw [rad] |
setPerHourAllowance
Modify an address' per hour allowance in order to withdraw SF from the treasury
function setPerHourAllowance(address _account, uint256 _rad) external isAuthorized accountNotTreasury(_account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The approved address |
_rad | uint256 | The per hour approved amount of SF to withdraw [rad] |
giveFunds
Governance transfers SF to an address
function giveFunds(address _account, uint256 _rad) external isAuthorized accountNotTreasury(_account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address to transfer SF to |
_rad | uint256 | Amount of internal system coins to transfer [rad] |
takeFunds
Governance takes funds from an address
function takeFunds(address _account, uint256 _rad) external isAuthorized accountNotTreasury(_account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address to take system coins from |
_rad | uint256 | Amount of internal system coins to take from the account [rad] |
pullFunds
Pull stability fees from the treasury
The caller of this method needs to have enough allowance in order to pull funds
function pullFunds(address _dstAccount, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_dstAccount | address | Address to transfer funds to |
_wad | uint256 | Amount of system coins (SF) to transfer [wad] |
transferSurplusFunds
Transfer surplus stability fees to the extraSurplusReceiver. This is here to make sure that the treasury doesn't accumulate fees that it doesn't even need in order to pay for allowances. It ensures that there are enough funds left in the treasury to account for posterior expenses
function transferSurplusFunds() external;
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
SurplusAuctionHouse
Inherits: Authorizable, Modifiable, Disableable, ISurplusAuctionHouse
This contract enables the sell of system coins in exchange for protocol tokens
A percentage of the protocol tokens raised in the auction are sent to a receiver, the rest is burnt
State Variables
AUCTION_HOUSE_TYPE
Type of the auction house
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32('SURPLUS');
_auctions
Raw data of an auction
mapping(uint256 _auctionId => Auction) public _auctions;
auctionsStarted
Total amount of surplus auctions created
uint256 public auctionsStarted;
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
protocolToken
Address of the ProtocolToken contract
IProtocolToken public protocolToken;
_params
Getter for the unpacked contract parameters struct
SurplusAuctionHouseParams public _params;
Functions
auctions
Data of an auction
function auctions(uint256 _id) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
params
Getter for the contract parameters struct
function params() external view returns (SurplusAuctionHouseParams memory _sahParams);
Returns
Name | Type | Description |
---|---|---|
_sahParams | SurplusAuctionHouseParams | Auction house parameters struct |
constructor
constructor(
address _safeEngine,
address _protocolToken,
SurplusAuctionHouseParams memory _sahParams
) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_protocolToken | address | Address of the protocol governance token |
_sahParams | SurplusAuctionHouseParams | Initial valid SurplusAuctionHouse parameters struct |
_onContractDisable
Internal virtual method to be called when the contract is disabled
Transfer all system coins back to the caller's address (usually the AccountingEngine)
function _onContractDisable() internal override;
startAuction
Start a new surplus auction
function startAuction(
uint256 _amountToSell,
uint256 _initialBid
) external isAuthorized whenEnabled returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_amountToSell | uint256 | Total amount of system coins to sell [rad] |
_initialBid | uint256 | Initial protocol token bid [wad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the started auction |
restartAuction
Restart an auction if no bids were submitted for it
function restartAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to restart |
increaseBidSize
Submit a higher protocol token bid for the same amount of system coins
function increaseBidSize(uint256 _id, uint256 _bid) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction you want to submit the bid for |
_bid | uint256 | New bid submitted [wad] |
settleAuction
Settle/finish an auction
function settleAuction(uint256 _id) external whenEnabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to settle |
terminateAuctionPrematurely
Terminate an auction prematurely.
function terminateAuctionPrematurely(uint256 _id) external whenDisabled;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to settle/terminate |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
TaxCollector
Inherits: Authorizable, Modifiable, ModifiablePerCollateral, ITaxCollector
This contract calculates and collects the stability fee from all collateral types
State Variables
safeEngine
Address of the SAFEEngine contract
ISAFEEngine public safeEngine;
_params
Getter for the unpacked contract parameters struct
TaxCollectorParams public _params;
_cParams
Getter for the unpacked collateral parameters struct
mapping(bytes32 _cType => TaxCollectorCollateralParams) public _cParams;
_cData
Getter for the unpacked collateral data struct
mapping(bytes32 _cType => TaxCollectorCollateralData) public _cData;
_secondaryReceiverRevenueSources
List of collateral types that send SF to a specific tax receiver
mapping(address _taxReceiver => EnumerableSet.Bytes32Set) internal _secondaryReceiverRevenueSources;
_secondaryTaxReceivers
Getter for the unpacked data about a specific secondary tax receiver
mapping(bytes32 _cType => mapping(address _taxReceiver => TaxReceiver)) public _secondaryTaxReceivers;
_secondaryReceivers
Enumerable set with the active secondary tax receivers
EnumerableSet.AddressSet internal _secondaryReceivers;
Functions
params
Getter for the contract parameters struct
function params() external view returns (TaxCollectorParams memory _taxCollectorParams);
Returns
Name | Type | Description |
---|---|---|
_taxCollectorParams | TaxCollectorParams | Tax collector parameters struct |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (TaxCollectorCollateralParams memory _taxCollectorCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_taxCollectorCParams | TaxCollectorCollateralParams | Tax collector collateral parameters struct |
cData
Getter for the collateral data struct
function cData(bytes32 _cType) external view returns (TaxCollectorCollateralData memory _taxCollectorCData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_taxCollectorCData | TaxCollectorCollateralData | Tax collector collateral data struct |
secondaryTaxReceivers
Getter for the data about a specific secondary tax receiver
function secondaryTaxReceivers(
bytes32 _cType,
address _receiver
) external view returns (TaxReceiver memory _secondaryTaxReceiver);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_receiver | address | Tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_secondaryTaxReceiver | TaxReceiver | Tax receiver struct |
constructor
constructor(address _safeEngine, TaxCollectorParams memory _taxCollectorParams) Authorizable(msg.sender) validParams;
Parameters
Name | Type | Description |
---|---|---|
_safeEngine | address | Address of the SAFEEngine contract |
_taxCollectorParams | TaxCollectorParams | Initial valid TaxCollector parameters struct |
collectedManyTax
Check if multiple collateral types are up to date with taxation
function collectedManyTax(uint256 _start, uint256 _end) public view returns (bool _ok);
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index of the first collateral type to check |
_end | uint256 | Index of the last collateral type to check |
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether all collateral types are up to date |
taxManyOutcome
Check how much SF will be charged (to collateral types between indexes 'start' and 'end' in the collateralList) during the next taxation
function taxManyOutcome(uint256 _start, uint256 _end) public view returns (bool _ok, int256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index in collateralList from which to start looping and calculating the tax outcome |
_end | uint256 | Index in collateralList at which we stop looping and calculating the tax outcome |
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether the tax outcome can be computed |
_rad | int256 | The total amount of SF that will be charged during the next taxation |
taxSingleOutcome
Get how much SF will be distributed after taxing a specific collateral type
function taxSingleOutcome(bytes32 _cType) public view returns (uint256 _newlyAccumulatedRate, int256 _deltaRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to compute the taxation outcome for |
Returns
Name | Type | Description |
---|---|---|
_newlyAccumulatedRate | uint256 | The newly accumulated rate |
_deltaRate | int256 | The delta between the new and the last accumulated rates |
secondaryReceiversListLength
Get the secondary tax receiver list length
function secondaryReceiversListLength() public view returns (uint256 _secondaryReceiversListLength);
collateralListLength
Get the collateralList length
function collateralListLength() public view returns (uint256 _collateralListLength);
isSecondaryReceiver
Check if a tax receiver is at a certain position in the list
function isSecondaryReceiver(address _receiver) public view returns (bool _isSecondaryReceiver);
Parameters
Name | Type | Description |
---|---|---|
_receiver | address | Tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_isSecondaryReceiver | bool | Whether the tax receiver for at least one collateral type |
secondaryReceiversList
Get the list of all secondary tax receivers
function secondaryReceiversList() external view returns (address[] memory _secondaryReceiversList);
secondaryReceiverRevenueSourcesList
Get the list of all collateral types for which a specific address is a secondary tax receiver
function secondaryReceiverRevenueSourcesList(address _secondaryReceiver)
external
view
returns (bytes32[] memory _secondaryReceiverRevenueSourcesList);
Parameters
Name | Type | Description |
---|---|---|
_secondaryReceiver | address | Secondary tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_secondaryReceiverRevenueSourcesList | bytes32[] | List of collateral types for which the address is a secondary tax receiver |
taxMany
Collect tax from multiple collateral types at once
function taxMany(uint256 _start, uint256 _end) external;
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index in collateralList from which to start looping and calculating the tax outcome |
_end | uint256 | Index in collateralList at which we stop looping and calculating the tax outcome |
taxSingle
Collect tax from a single collateral type
function taxSingle(bytes32 _cType) public returns (uint256 _latestAccumulatedRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to tax |
Returns
Name | Type | Description |
---|---|---|
_latestAccumulatedRate | uint256 | The newly accumulated rate after taxation |
_getNextStabilityFee
Compute the next stability fee for a collateral type, bounded by the maxStabilityFeeRange
The stability fee calculation is bounded by the maxStabilityFeeRange
function _getNextStabilityFee(bytes32 _cType) internal view returns (uint256 _nextStabilityFee);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 identifier of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_nextStabilityFee | uint256 | The next stability fee to be applied for the collateral type |
_splitTaxIncome
Split SF between all tax receivers
function _splitTaxIncome(bytes32 _cType, uint256 _debtAmount, int256 _deltaRate) internal;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to distribute SF for |
_debtAmount | uint256 | Total debt currently issued for the collateral type |
_deltaRate | int256 | Difference between the last and the latest accumulate rates for the collateralType |
_distributeTax
Give/withdraw SF from a tax receiver
function _distributeTax(bytes32 _cType, address _receiver, uint256 _debtAmount, int256 _deltaRate) internal;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to distribute SF for |
_receiver | address | Tax receiver address |
_debtAmount | uint256 | Total debt currently issued |
_deltaRate | int256 | Difference between the latest and the last accumulated rates for the collateralType |
_initializeCollateralType
If SF is negative and a tax receiver doesn't have enough coins to absorb the loss, compute a new tax cut that can be absorbed If the tax receiver's tax cut is not null and if the receiver accepts negative SF offer/take SF to/from them
function _initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
_modifyParameters
Internal function to be overriden with custom logic to modify parameters
This function is set to revert if not overriden
function _modifyParameters(bytes32 _param, bytes memory _data) internal override;
_modifyParameters
Set a new value for a collateral specific parameter
function _modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) internal override;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
_validateParameters
Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view override;
_validateCParameters
Internal function to be overriden with custom logic to validate collateral parameters
function _validateCParameters(bytes32 _cType) internal view override;
_setPrimaryTaxReceiver
Sets the primary tax receiver, the address that receives the unallocated SF from all collateral types
function _setPrimaryTaxReceiver(address _primaryTaxReceiver) internal;
Parameters
Name | Type | Description |
---|---|---|
_primaryTaxReceiver | address | Address of the primary tax receiver |
_setSecondaryTaxReceiver
Add a new secondary tax receiver or update data (add a new SF source or modify % of SF taken from a collateral type)
function _setSecondaryTaxReceiver(bytes32 _cType, TaxReceiver memory _data) internal;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type that will give SF to the tax receiver |
_data | TaxReceiver | Encoded data containing the receiver, tax percentage, and whether it supports negative tax |
Contents
- external
- factories
- governance
- jobs
- oracles
- proxies
- settlement
- tokens
- utils
- IAccountingEngine
- ICollateralAuctionHouse
- ICommonSurplusAuctionHouse
- IDebtAuctionHouse
- ILiquidationEngine
- IOracleRelayer
- IPIDController
- IPIDRateSetter
- ISAFEEngine
- IStabilityFeeTreasury
- ISurplusAuctionHouse
- ITaxCollector
Contents
IBeefyVaultV7
Functions
getPricePerFullShare
function getPricePerFullShare() external view returns (uint256 _pricePerFullShare);
symbol
function symbol() external view returns (string memory _symbol);
ISAFESaviour
Functions
saveSAFE
function saveSAFE(
address _liquidator,
bytes32 _cType,
address _safe
) external returns (bool _ok, uint256 _collateralAdded, uint256 _liquidatorReward);
IVeloPool
Functions
totalSupply
Returns the value of tokens in existence.
function totalSupply() external view returns (uint256 _totalSupply);
reserve0
Amount of token0 in pool
function reserve0() external view returns (uint256 _reserve0);
reserve1
Amount of token1 in pool
function reserve1() external view returns (uint256 _reserve1);
symbol
function symbol() external view returns (string memory _symbol);
IWeth
Inherits: IERC20
Functions
deposit
function deposit() external payable;
withdraw
function withdraw(uint256 _amount) external;
Contents
- IAuthorizableChild
- IBeefyVeloVaultRelayerChild
- IBeefyVeloVaultRelayerFactory
- IChainlinkRelayerChild
- IChainlinkRelayerFactory
- ICollateralAuctionHouseChild
- ICollateralAuctionHouseFactory
- ICollateralJoinChild
- ICollateralJoinDelegatableChild
- ICollateralJoinFactory
- IDelayedOracleChild
- IDelayedOracleFactory
- IDenominatedOracleChild
- IDenominatedOracleFactory
- IDisableableChild
- IFactoryChild
- IUniV3RelayerChild
- IUniV3RelayerFactory
IAuthorizableChild
Inherits: IAuthorizable, IFactoryChild
IBeefyVeloVaultRelayerChild
Inherits: IBeefyVeloVaultRelayer, IFactoryChild
IBeefyVeloVaultRelayerFactory
Inherits: IAuthorizable
Functions
deployBeefyVeloVaultRelayer
Deploys a new BeefyVeloVaultRelayer contract
function deployBeefyVeloVaultRelayer(
IBaseOracle _token0priceSource,
IBaseOracle _token1priceSource,
IBeefyVaultV7 _beefyVault,
IVeloPool _veloPool
) external returns (IBaseOracle _beefyVeloVaultRelayer);
Parameters
Name | Type | Description |
---|---|---|
_token0priceSource | IBaseOracle | Address of the price source for the first token in the velo pool |
_token1priceSource | IBaseOracle | Address of the price source for the second token in the velo pool |
_beefyVault | IBeefyVaultV7 | The address of the beefy vault contract |
_veloPool | IVeloPool | The address of the velo pool underlying the beefy vault |
Returns
Name | Type | Description |
---|---|---|
_beefyVeloVaultRelayer | IBaseOracle | Address of the deployed BeefyVeloVaultRelayer contract |
beefyVeloVaultRelayersList
Getter for the list of BeefyVeloVaultRelayer contracts
function beefyVeloVaultRelayersList() external view returns (address[] memory _beefyVeloVaultRelayersList);
Returns
Name | Type | Description |
---|---|---|
_beefyVeloVaultRelayersList | address[] | List of BeefyVeloVaultRelayer contracts |
Events
NewBeefyVeloVaultRelayer
Emitted when a new BeefyVeloVaultRelayer contract is deployed
event NewBeefyVeloVaultRelayer(
address indexed _beefyVeloVaultRelayer,
address _token0priceSource,
address _token1priceSource,
address _beefyVault,
address _veloPool
);
Parameters
Name | Type | Description |
---|---|---|
_beefyVeloVaultRelayer | address | Address of the deployed DenominatedOracle contract |
_token0priceSource | address | Address of the price source for the first token in the velo pool |
_token1priceSource | address | Address of the price source for the second token in the velo pool |
_beefyVault | address | The address of the beefy vault contract |
_veloPool | address | The address of the velo pool underlying the beefy vault |
IChainlinkRelayerChild
Inherits: IChainlinkRelayer, IFactoryChild
IChainlinkRelayerFactory
Inherits: IAuthorizable
Functions
sequencerUptimeFeed
Address of the Chainlink sequencer uptime feed used to consult the sequencer status
function sequencerUptimeFeed() external view returns (IChainlinkOracle _sequencerUptimeFeed);
deployChainlinkRelayer
Deploys a new ChainlinkRelayer contract
function deployChainlinkRelayer(
address _priceFeed,
uint256 _staleThreshold
) external returns (IBaseOracle _chainlinkRelayer);
Parameters
Name | Type | Description |
---|---|---|
_priceFeed | address | Address of the price feed to be used by the ChainlinkRelayer contract |
_staleThreshold | uint256 | Stale threshold to be used by the ChainlinkRelayer contract |
Returns
Name | Type | Description |
---|---|---|
_chainlinkRelayer | IBaseOracle | Address of the deployed ChainlinkRelayer contract |
chainlinkRelayersList
Getter for the list of ChainlinkRelayer contracts
function chainlinkRelayersList() external view returns (address[] memory _chainlinkRelayersList);
Returns
Name | Type | Description |
---|---|---|
_chainlinkRelayersList | address[] | List of ChainlinkRelayer contracts |
setSequencerUptimeFeed
Sets the Chainlink sequencer uptime feed contract address
function setSequencerUptimeFeed(address _sequencerUptimeFeed) external;
Parameters
Name | Type | Description |
---|---|---|
_sequencerUptimeFeed | address | The address of the Chainlink sequencer uptime feed |
Events
NewChainlinkRelayer
Emitted when a new ChainlinkRelayer contract is deployed
event NewChainlinkRelayer(
address indexed _chainlinkRelayer, address _priceFeed, address _sequencerUptimeFeed, uint256 _staleThreshold
);
Parameters
Name | Type | Description |
---|---|---|
_chainlinkRelayer | address | Address of the deployed ChainlinkRelayer contract |
_priceFeed | address | Address of the price feed to be used by the ChainlinkRelayer contract |
_sequencerUptimeFeed | address | Address of the sequencer uptime feed to be used by the ChainlinkRelayer contract |
_staleThreshold | uint256 | Stale threshold to be used by the ChainlinkRelayer contract |
Errors
ChainlinkRelayerFactory_NullSequencerUptimeFeed
Throws if the provided sequencer uptime feed address is null
error ChainlinkRelayerFactory_NullSequencerUptimeFeed();
ICollateralAuctionHouseChild
Inherits: ICollateralAuctionHouse, IFactoryChild
ICollateralAuctionHouseFactory
Inherits: IAuthorizable, IModifiable, IModifiablePerCollateral
Functions
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType)
external
view
returns (ICollateralAuctionHouse.CollateralAuctionHouseParams memory _cahParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_cahParams | ICollateralAuctionHouse.CollateralAuctionHouseParams | CollateralAuctionHouse parameters struct |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType)
external
view
returns (uint256 _minimumBid, uint256 _minDiscount, uint256 _maxDiscount, uint256 _perSecondDiscountUpdateRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_minimumBid | uint256 | Minimum bid for the collateral auctions [wad] |
_minDiscount | uint256 | Minimum discount for the collateral auctions [wad %] |
_maxDiscount | uint256 | Maximum discount for the collateral auctions [wad %] |
_perSecondDiscountUpdateRate | uint256 | Per second rate at which the discount is updated [ray] |
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (address _safeEngine);
liquidationEngine
Address of the LiquidationEngine contract
function liquidationEngine() external view returns (address _liquidationEngine);
oracleRelayer
Address of the OracleRelayer contract
function oracleRelayer() external view returns (address _oracleRelayer);
collateralAuctionHouses
Getter for the address of the CollateralAuctionHouse contract associated with a collateral type
function collateralAuctionHouses(bytes32 _cType) external view returns (address _collateralAuctionHouse);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralAuctionHouse | address | Address of the CollateralAuctionHouse contract |
collateralAuctionHousesList
Getter for the list of CollateralAuctionHouse contracts
function collateralAuctionHousesList() external view returns (address[] memory _collateralAuctionHouses);
Returns
Name | Type | Description |
---|---|---|
_collateralAuctionHouses | address[] | List of CollateralAuctionHouse contracts |
Events
DeployCollateralAuctionHouse
Emitted when a new CollateralAuctionHouse contract is deployed
event DeployCollateralAuctionHouse(bytes32 indexed _cType, address indexed _collateralAuctionHouse);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateralAuctionHouse | address | Address of the deployed CollateralAuctionHouse contract |
ICollateralJoinChild
Inherits: ICollateralJoin, IFactoryChild
ICollateralJoinDelegatableChild
Inherits: ICollateralJoinChild
Functions
delegatee
Address to whom the votes are delegated
function delegatee() external view returns (address _delegatee);
ICollateralJoinFactory
Inherits: IAuthorizable, IDisableable
Functions
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (address _safeEngine);
collateralJoins
Getter for the address of the CollateralJoin contract associated with a collateral type
function collateralJoins(bytes32 _cType) external view returns (address _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralJoin | address | Address of the CollateralJoin contract |
collateralTypesList
Getter for the list of collateral types
function collateralTypesList() external view returns (bytes32[] memory _collateralTypesList);
Returns
Name | Type | Description |
---|---|---|
_collateralTypesList | bytes32[] | List of collateral types |
collateralJoinsList
Getter for the list of CollateralJoin contracts
function collateralJoinsList() external view returns (address[] memory _collateralJoinsList);
Returns
Name | Type | Description |
---|---|---|
_collateralJoinsList | address[] | List of CollateralJoin contracts |
deployCollateralJoin
Deploys a CollateralJoinChild contract
function deployCollateralJoin(bytes32 _cType, address _collateral) external returns (ICollateralJoin _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20 collateral token |
Returns
Name | Type | Description |
---|---|---|
_collateralJoin | ICollateralJoin | Address of the deployed CollateralJoinChild contract |
deployDelegatableCollateralJoin
Deploys a CollateralJoinDelegatableChild contract
function deployDelegatableCollateralJoin(
bytes32 _cType,
address _collateral,
address _delegatee
) external returns (ICollateralJoin _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20Votes collateral token |
_delegatee | address | Address to whom the deployed child will delegate the voting power to |
Returns
Name | Type | Description |
---|---|---|
_collateralJoin | ICollateralJoin | Address of the deployed CollateralJoinDelegatableChild contract |
disableCollateralJoin
Disables a CollateralJoin contract and removes it from the collateral types list
Allows the deployment of other CollateralJoin contract for the same collateral type
function disableCollateralJoin(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Events
DeployCollateralJoin
Emitted when a new CollateralJoin contract is deployed
event DeployCollateralJoin(bytes32 indexed _cType, address indexed _collateral, address indexed _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateral | address | Address of the ERC20 collateral token |
_collateralJoin | address | Address of the deployed CollateralJoin contract |
DisableCollateralJoin
Emitted when a CollateralJoin contract is disabled
event DisableCollateralJoin(address indexed _collateralJoin);
Parameters
Name | Type | Description |
---|---|---|
_collateralJoin | address | Address of the disabled CollateralJoin contract |
Errors
CollateralJoinFactory_CollateralJoinExistent
Throws when trying to deploy a CollateralJoin contract for an existent collateral type
error CollateralJoinFactory_CollateralJoinExistent();
CollateralJoinFactory_CollateralJoinNonExistent
Throws when trying to disable a non-existent CollateralJoin contract
error CollateralJoinFactory_CollateralJoinNonExistent();
IDelayedOracleChild
Inherits: IDelayedOracle, IFactoryChild
IDelayedOracleFactory
Inherits: IAuthorizable
Functions
deployDelayedOracle
Deploys a new DelayedOracle contract
function deployDelayedOracle(
IBaseOracle _priceSource,
uint256 _updateDelay
) external returns (IDelayedOracle _delayedOracle);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source for the DelayedOracle contract |
_updateDelay | uint256 | Delay in seconds to be applied between the price source and the delayed oracle feeds |
Returns
Name | Type | Description |
---|---|---|
_delayedOracle | IDelayedOracle | Address of the deployed DelayedOracle contract |
delayedOraclesList
Getter for the list of DelayedOracle contracts
function delayedOraclesList() external view returns (address[] memory _delayedOraclesList);
Returns
Name | Type | Description |
---|---|---|
_delayedOraclesList | address[] | List of DelayedOracle contracts |
Events
NewDelayedOracle
Emitted when a new DelayedOracle contract is deployed
event NewDelayedOracle(address indexed _delayedOracle, address _priceSource, uint256 _updateDelay);
Parameters
Name | Type | Description |
---|---|---|
_delayedOracle | address | Address of the deployed DelayedOracle contract |
_priceSource | address | Address of the price source for the DelayedOracle contract |
_updateDelay | uint256 | Delay in seconds to be applied between the price source and the delayed oracle feeds |
IDenominatedOracleChild
Inherits: IDenominatedOracle, IFactoryChild
IDenominatedOracleFactory
Inherits: IAuthorizable
Functions
deployDenominatedOracle
Deploys a new DenominatedOracle contract
The denomination quote should follow the format: (A / B) * (B / C) = A / C
If the quote is inverted, the format should be read as: (B / A)^-1 * (B / C) = A / C
function deployDenominatedOracle(
IBaseOracle _priceSource,
IBaseOracle _denominationPriceSource,
bool _inverted
) external returns (IBaseOracle _denominatedOracle);
Parameters
Name | Type | Description |
---|---|---|
_priceSource | IBaseOracle | Address of the price source for the DenominatedOracle contract |
_denominationPriceSource | IBaseOracle | Address of the denomination price source for the DenominatedOracle contract |
_inverted | bool | Boolean indicating if the denomination calculation quote should be inverted |
Returns
Name | Type | Description |
---|---|---|
_denominatedOracle | IBaseOracle | Address of the deployed DenominatedOracle contract |
denominatedOraclesList
Getter for the list of DenominatedOracle contracts
function denominatedOraclesList() external view returns (address[] memory _denominatedOraclesList);
Returns
Name | Type | Description |
---|---|---|
_denominatedOraclesList | address[] | List of DenominatedOracle contracts |
Events
NewDenominatedOracle
Emitted when a new DenominatedOracle contract is deployed
event NewDenominatedOracle(
address indexed _denominatedOracle, address _priceSource, address _denominationPriceSource, bool _inverted
);
Parameters
Name | Type | Description |
---|---|---|
_denominatedOracle | address | Address of the deployed DenominatedOracle contract |
_priceSource | address | Address of the price source for the DenominatedOracle contract |
_denominationPriceSource | address | Address of the denomination price source for the DenominatedOracle contract |
_inverted | bool | Boolean indicating if the denomination calculation quote should be inverted |
IDisableableChild
Inherits: IDisableable, IFactoryChild
IFactoryChild
Functions
factory
Getter for the address of the factory that deployed the inheriting contract
function factory() external view returns (address _factory);
Returns
Name | Type | Description |
---|---|---|
_factory | address | Factory address |
Errors
NotFactoryDeployment
Throws when the contract is being deployed by a non-contract address
error NotFactoryDeployment();
CallerNotFactory
Throws when trying to call an onlyFactory function from a non-factory address
error CallerNotFactory();
IUniV3RelayerChild
Inherits: IUniV3Relayer, IFactoryChild
IUniV3RelayerFactory
Inherits: IAuthorizable
Functions
deployUniV3Relayer
Deploys a new UniV3Relayer contract
function deployUniV3Relayer(
address _baseToken,
address _quoteToken,
uint24 _feeTier,
uint32 _quotePeriod
) external returns (IBaseOracle _uniV3Relayer);
Parameters
Name | Type | Description |
---|---|---|
_baseToken | address | Address of the base token to be quoted |
_quoteToken | address | Address of the quote reference token |
_feeTier | uint24 | Fee tier used to identify the UniV3 pool |
_quotePeriod | uint32 | Length of the period used to calculate the TWAP quote |
Returns
Name | Type | Description |
---|---|---|
_uniV3Relayer | IBaseOracle | Address of the deployed UniV3Relayer contract |
uniV3RelayersList
Getter for the list of UniV3Relayer contracts
function uniV3RelayersList() external view returns (address[] memory _uniV3RelayersList);
Returns
Name | Type | Description |
---|---|---|
_uniV3RelayersList | address[] | List of UniV3Relayer contracts |
Events
NewUniV3Relayer
Emitted when a new UniV3Relayer contract is deployed
event NewUniV3Relayer(
address indexed _uniV3Relayer, address _baseToken, address _quoteToken, uint24 _feeTier, uint32 _quotePeriod
);
Parameters
Name | Type | Description |
---|---|---|
_uniV3Relayer | address | Address of the deployed UniV3Relayer contract |
_baseToken | address | Address of the base token to be quoted by the UniV3Relayer contract |
_quoteToken | address | Address of the quote reference token for the UniV3Relayer contract |
_feeTier | uint24 | Fee tier used to identify the pool for the UniV3Relayer contract |
_quotePeriod | uint32 | Length of the period used to calculate the TWAP quote for the UniV3Relayer contract |
Contents
IHaiDelegatee
Functions
delegatee
Get the address of the delegatee of the contract
function delegatee() external view returns (address _delegatee);
Returns
Name | Type | Description |
---|---|---|
_delegatee | address | The address of the delegatee |
setDelegatee
Set the delegatee of the contract
function setDelegatee(address _delegatee) external;
Parameters
Name | Type | Description |
---|---|---|
_delegatee | address | The address of the new delegatee |
castVote
Cast a vote using the voting power delegated to this contract
function castVote(IGovernor _governor, uint256 _proposalId, uint8 _support) external returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
Returns
Name | Type | Description |
---|---|---|
_weight | uint256 | The weight of the vote |
castVoteWithReason
Cast a vote with reason using the voting power delegated to this contract
function castVoteWithReason(
IGovernor _governor,
uint256 _proposalId,
uint8 _support,
string memory _reason
) external returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
_reason | string | The reason for the vote |
Returns
Name | Type | Description |
---|---|---|
_weight | uint256 | The weight of the vote |
castVoteWithReasonAndParams
Cast a vote with reason and params using the voting power delegated to this contract
function castVoteWithReasonAndParams(
IGovernor _governor,
uint256 _proposalId,
uint8 _support,
string memory _reason,
bytes memory _params
) external returns (uint256 _weight);
Parameters
Name | Type | Description |
---|---|---|
_governor | IGovernor | The governor contract to vote on |
_proposalId | uint256 | The id of the proposal |
_support | uint8 | The vote type |
_reason | string | The reason for the vote |
_params | bytes | The params for the vote |
Events
DelegateeSet
Emitted when the delegatee of the contract is set
event DelegateeSet(address _delegatee);
Parameters
Name | Type | Description |
---|---|---|
_delegatee | address | The address of the new delegatee |
Errors
OnlyDelegatee
Throws if called by any account other than the delegatee
error OnlyDelegatee();
IHaiGovernor
Structs
HaiGovernorParams
struct HaiGovernorParams {
uint48 votingDelay;
uint32 votingPeriod;
uint48 quorumVoteExtension;
uint256 proposalThreshold;
uint256 quorumNumeratorValue;
uint256 timelockMinDelay;
}
Contents
IAccountingJob
Inherits: IAuthorizable, IModifiable, IJob
Functions
shouldWorkPopDebtFromQueue
Whether the pop debt from queue job should be worked
function shouldWorkPopDebtFromQueue() external view returns (bool _shouldWorkPopDebtFromQueue);
shouldWorkAuctionDebt
Whether the auction debt job should be worked
function shouldWorkAuctionDebt() external view returns (bool _shouldWorkAuctionDebt);
shouldWorkAuctionSurplus
Whether the auction surplus job should be worked
function shouldWorkAuctionSurplus() external view returns (bool _shouldWorkAuctionSurplus);
shouldWorkTransferExtraSurplus
Whether the transfer extra surplus job should be worked
function shouldWorkTransferExtraSurplus() external view returns (bool _shouldWorkTransferExtraSurplus);
accountingEngine
Address of the AccountingEngine contract
function accountingEngine() external view returns (IAccountingEngine _accountingEngine);
workPopDebtFromQueue
Rewarded method to pop debt from the AccountingEngine's queue
function workPopDebtFromQueue(uint256 _debtBlockTimestamp) external;
Parameters
Name | Type | Description |
---|---|---|
_debtBlockTimestamp | uint256 | Timestamp of the debt block to pop |
workAuctionDebt
Rewarded method to auction debt from the AccountingEngine
function workAuctionDebt() external;
workAuctionSurplus
Rewarded method to auction surplus from the AccountingEngine
function workAuctionSurplus() external;
workTransferExtraSurplus
Rewarded method to transfer surplus from the AccountingEngine
function workTransferExtraSurplus() external;
IJob
Inherits: IAuthorizable, IModifiable
Functions
rewardAmount
Amount of tokens to reward per job transaction [wad]
function rewardAmount() external view returns (uint256 _rewardAmount);
stabilityFeeTreasury
Address of the StabilityFeeTreasury contract
function stabilityFeeTreasury() external view returns (IStabilityFeeTreasury _stabilityFeeTreasury);
Events
Rewarded
Emitted when a reward is issued
event Rewarded(address _rewardedAccount, uint256 _rewardAmount);
Parameters
Name | Type | Description |
---|---|---|
_rewardedAccount | address | Account that received the reward |
_rewardAmount | uint256 | Amount of reward issued [wad] |
Errors
NotWorkable
Throws when trying to call a not-workable job function
error NotWorkable();
ILiquidationJob
Inherits: IAuthorizable, IModifiable, IJob
Functions
shouldWork
Whether the liquidation job should be worked
function shouldWork() external view returns (bool _shouldWork);
liquidationEngine
Address of the LiquidationEngine contract
function liquidationEngine() external view returns (ILiquidationEngine _liquidationEngine);
workLiquidation
Rewarded method to liquidate a SAFE
function workLiquidation(bytes32 _cType, address _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE to liquidate |
IOracleJob
Inherits: IAuthorizable, IModifiable, IJob
Functions
shouldWorkUpdateCollateralPrice
Whether the update collateral price job should be worked
function shouldWorkUpdateCollateralPrice() external view returns (bool _shouldWorkUpdateCollateralPrice);
shouldWorkUpdateRate
Whether the update rate job should be worked
function shouldWorkUpdateRate() external view returns (bool _shouldWorkUpdateRate);
oracleRelayer
Address of the OracleRelayer contract
function oracleRelayer() external view returns (IOracleRelayer _oracleRelayer);
pidRateSetter
Address of the PIDRateSetter contract
function pidRateSetter() external view returns (IPIDRateSetter _pidRateSetter);
workUpdateCollateralPrice
Rewarded method to update a collateral price
function workUpdateCollateralPrice(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
workUpdateRate
Rewarded method to update the redemption rate
function workUpdateRate() external;
Errors
OracleJob_InvalidPrice
Throws when trying to update an invalid collateral price
error OracleJob_InvalidPrice();
Contents
- IBaseOracle
- IBeefyVeloVaultRelayer
- IChainlinkOracle
- IChainlinkRelayer
- IDelayedOracle
- IDenominatedOracle
- IUniV3Relayer
IBaseOracle
Basic interface for a system price feed All price feeds should be translated into an 18 decimals format
Functions
symbol
Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
function symbol() external view returns (string memory _symbol);
getResultWithValidity
Fetch the latest oracle result and whether it is valid or not
This method should never revert
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
read
Fetch the latest oracle result
Will revert if is the price feed is invalid
function read() external view returns (uint256 _value);
Errors
InvalidPriceFeed
error InvalidPriceFeed();
IBeefyVeloVaultRelayer
Inherits: IBaseOracle
Functions
token0priceSource
Address of the token0 price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
function token0priceSource() external view returns (IBaseOracle _token0priceSource);
token1priceSource
Address of the token1 price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
function token1priceSource() external view returns (IBaseOracle _token1priceSource);
beefyVault
Address of the beefy vault
Assumes that the beefy vault is a valid IBeefyVaultV7
function beefyVault() external view returns (IBeefyVaultV7 _beefyVault);
veloPool
Address of the velo pool underlying the beefy vault
Assumes that the price source is a valid IVeloPool
function veloPool() external view returns (IVeloPool _veloPool);
Errors
BeefyVeloVaultRelayer_NullPriceSource
Throws if either the provided token0 price source or the token1 price source are null
error BeefyVeloVaultRelayer_NullPriceSource();
BeefyVeloVaultRelayer_NullBeefyVault
Throws if the provided beefy vault address is null
error BeefyVeloVaultRelayer_NullBeefyVault();
BeefyVeloVaultRelayer_NullVeloPool
Throws if the provided velo pool address is null
error BeefyVeloVaultRelayer_NullVeloPool();
BeefyVeloVaultRelayer_InvalidPriceSource
Throws if either of the provided price sources are invalid
error BeefyVeloVaultRelayer_InvalidPriceSource();
IChainlinkOracle
Functions
decimals
function decimals() external view returns (uint8 _decimals);
description
function description() external view returns (string memory _description);
getAnswer
function getAnswer(uint256 _roundId) external view returns (int256 _answer);
getRoundData
function getRoundData(uint256 __roundId)
external
view
returns (uint256 _roundId, int256 _answer, uint256 _startedAt, uint256 _updatedAt, uint256 _answeredInRound);
getTimestamp
function getTimestamp(uint256 _roundId) external view returns (uint256 _timestamp);
latestAnswer
function latestAnswer() external view returns (int256 _latestAnswer);
latestRound
function latestRound() external view returns (uint256 _latestRound);
latestRoundData
function latestRoundData()
external
view
returns (uint256 _roundId, int256 _answer, uint256 _startedAt, uint256 _updatedAt, uint256 _answeredInRound);
latestTimestamp
function latestTimestamp() external view returns (uint256 _latestTimestamp);
IChainlinkRelayer
Inherits: IBaseOracle
Functions
priceFeed
Address of the Chainlink price feed used to consult the price
function priceFeed() external view returns (IChainlinkOracle _priceFeed);
sequencerUptimeFeed
Address of the Chainlink sequencer uptime feed used to consult the sequencer status
function sequencerUptimeFeed() external view returns (IChainlinkOracle _sequencerUptimeFeed);
multiplier
The multiplier used to convert the quote into an 18 decimals format
function multiplier() external view returns (uint256 _multiplier);
staleThreshold
The time threshold after which a Chainlink response is considered stale
function staleThreshold() external view returns (uint256 _staleThreshold);
Errors
ChainlinkRelayer_NullPriceFeed
Throws if the provided price feed address is null
error ChainlinkRelayer_NullPriceFeed();
ChainlinkRelayer_NullSequencerUptimeFeed
Throws if the provided sequencer uptime feed address is null
error ChainlinkRelayer_NullSequencerUptimeFeed();
ChainlinkRelayer_NullStaleThreshold
Throws if the provided stale threshold is null
error ChainlinkRelayer_NullStaleThreshold();
IDelayedOracle
Inherits: IBaseOracle
Functions
priceSource
Address of the non-delayed price source
Assumes that the price source is a valid IBaseOracle
function priceSource() external view returns (IBaseOracle _priceSource);
getNextResultWithValidity
The next valid price feed, taking effect at the next updateResult call
function getNextResultWithValidity() external view returns (uint256 _result, bool _validity);
Returns
Name | Type | Description |
---|---|---|
_result | uint256 | The value in 18 decimals format of the next price feed |
_validity | bool | Whether the next price feed is valid or not |
updateDelay
The delay in seconds that should elapse between updates
function updateDelay() external view returns (uint256 _updateDelay);
lastUpdateTime
The timestamp of the last update
function lastUpdateTime() external view returns (uint256 _lastUpdateTime);
shouldUpdate
Indicates if a delay has passed since the last update
function shouldUpdate() external view returns (bool _ok);
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether the oracle should be updated or not |
updateResult
Updates the current price with the last next price, and reads the next price feed
Will revert if the delay since last update has not elapsed
function updateResult() external returns (bool _success);
Returns
Name | Type | Description |
---|---|---|
_success | bool | Whether the update was successful or not |
Events
UpdateResult
Emitted when the oracle is updated
event UpdateResult(uint256 _newMedian, uint256 _lastUpdateTime);
Parameters
Name | Type | Description |
---|---|---|
_newMedian | uint256 | The new median value |
_lastUpdateTime | uint256 | The timestamp of the update |
Errors
DelayedOracle_NullPriceSource
Throws if the provided price source address is null
error DelayedOracle_NullPriceSource();
DelayedOracle_NullDelay
Throws if the provided delay is null
error DelayedOracle_NullDelay();
DelayedOracle_DelayHasNotElapsed
Throws when trying to update the oracle before the delay has elapsed
error DelayedOracle_DelayHasNotElapsed();
DelayedOracle_NoCurrentValue
Throws when trying to read the current value and it is invalid
error DelayedOracle_NoCurrentValue();
Structs
Feed
struct Feed {
uint256 value;
bool isValid;
}
IDenominatedOracle
Inherits: IBaseOracle
Functions
priceSource
Address of the base price source that is used to calculate the price
Assumes that the price source is a valid IBaseOracle
function priceSource() external view returns (IBaseOracle _priceSource);
denominationPriceSource
Address of the base price source that is used to calculate the denominated price
Assumes that the price source is a valid IBaseOracle
function denominationPriceSource() external view returns (IBaseOracle _denominationPriceSource);
inverted
Whether the price source quote should be inverted or not
Used to fix an inverted path of token quotes into a continuous chain of tokens (e.g. '(ETH / WBTC)^-1 * (ETH / USD)')
function inverted() external view returns (bool _inverted);
Errors
DenominatedOracle_NullPriceSource
Throws if either the provided price source or denominated price source are null
error DenominatedOracle_NullPriceSource();
IUniV3Relayer
Inherits: IBaseOracle
Functions
uniV3Pool
Address of the UniswapV3Pool used to consult the TWAP
function uniV3Pool() external view returns (address _uniV3Pool);
baseToken
Address of the base token used to consult the quote from
function baseToken() external view returns (address _baseToken);
quoteToken
Address of the token used as a quote reference
function quoteToken() external view returns (address _quoteToken);
baseAmount
The amount in wei of the base token used to consult the pool for a quote
function baseAmount() external view returns (uint128 _baseAmount);
multiplier
The multiplier used to convert the quote into an 18 decimals format
function multiplier() external view returns (uint256 _multiplier);
quotePeriod
The length of the TWAP used to consult the pool
function quotePeriod() external view returns (uint32 _quotePeriod);
Errors
UniV3Relayer_InvalidPool
Throws if the provided pool (baseToken, quoteToken, feeTier) is non-existent
error UniV3Relayer_InvalidPool();
Contents
Contents
- IBasicActions
- ICollateralBidActions
- ICommonActions
- IDebtBidActions
- IGlobalSettlementActions
- IRewardedActions
- ISurplusBidActions
IBasicActions
Inherits: ICommonActions
Functions
openSAFE
Opens a brand new SAFE
function openSAFE(address _manager, bytes32 _cType, address _usr) external returns (uint256 _safeId);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_cType | bytes32 | Bytes32 representing the collateral type |
_usr | address | Address of the SAFE owner |
Returns
Name | Type | Description |
---|---|---|
_safeId | uint256 | Id of the created SAFE |
generateDebt
Generates debt and sends COIN amount to msg.sender
function generateDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
repayDebt
Repays an amount of debt
function repayDebt(
address _manager,
address _taxCollector,
address _coinJoin,
uint256 _safeId,
uint256 _deltaWad
) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of COIN to repay [wad] |
lockTokenCollateral
Locks a collateral token amount in the SAFE
function lockTokenCollateral(address _manager, address _collateralJoin, uint256 _safeId, uint256 _deltaWad) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to collateralize [wad] |
freeTokenCollateral
Unlocks a collateral token amount from the SAFE, and transfers the ERC20 collateral to the user's address
function freeTokenCollateral(address _manager, address _collateralJoin, uint256 _safeId, uint256 _deltaWad) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to free [wad] |
repayAllDebt
Repays the total amount of debt of a SAFE
This method is used to close a SAFE's debt, when the amount of debt is increasing due to stability fees
function repayAllDebt(address _manager, address _taxCollector, address _coinJoin, uint256 _safeId) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
lockTokenCollateralAndGenerateDebt
Locks a collateral token amount in the SAFE and generates debt
function lockTokenCollateralAndGenerateDebt(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safe,
uint256 _collateralAmount,
uint256 _deltaWad
) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safe | uint256 | Id of the SAFE |
_collateralAmount | uint256 | Amount of collateral to collateralize [wad] |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
openLockTokenCollateralAndGenerateDebt
Creates a SAFE, locks a collateral token amount in it and generates debt
function openLockTokenCollateralAndGenerateDebt(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
bytes32 _cType,
uint256 _collateralAmount,
uint256 _deltaWad
) external returns (uint256 _safe);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representing the collateral type |
_collateralAmount | uint256 | Amount of collateral to collateralize [wad] |
_deltaWad | uint256 | Amount of COIN to generate [wad] |
Returns
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the created SAFE |
repayDebtAndFreeTokenCollateral
Repays debt and unlocks a collateral token amount from the SAFE
function repayDebtAndFreeTokenCollateral(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safeId,
uint256 _collateralWad,
uint256 _debtWad
) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_collateralWad | uint256 | Amount of collateral to free [wad] |
_debtWad | uint256 | Amount of COIN to repay [wad] |
repayAllDebtAndFreeTokenCollateral
Repays all debt and unlocks collateral from the SAFE
function repayAllDebtAndFreeTokenCollateral(
address _manager,
address _taxCollector,
address _collateralJoin,
address _coinJoin,
uint256 _safeId,
uint256 _collateralWad
) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_taxCollector | address | Address of the TaxCollector contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_coinJoin | address | Address of the CoinJoin contract |
_safeId | uint256 | Id of the SAFE |
_collateralWad | uint256 | Amount of collateral to free [wad] |
collectTokenCollateral
Collects a collateral token amount from the SAFE handler, and transfers the ERC20 collateral to the user's address
function collectTokenCollateral(address _manager, address _collateralJoin, uint256 _safeId, uint256 _deltaWad) external;
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE |
_deltaWad | uint256 | Amount of collateral to collect [wad] |
ICollateralBidActions
Inherits: ICommonActions
Functions
buyCollateral
Buys collateral tokens from a collateral auction
This method will fail if the purchased amount is lower than the minimum, or the bid higher than the specified amount
function buyCollateral(
address _coinJoin,
address _collateralJoin,
address _collateralAuctionHouse,
uint256 _auctionId,
uint256 _minCollateralAmount,
uint256 _bidAmount
) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_collateralAuctionHouse | address | Address of the CollateralAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_minCollateralAmount | uint256 | Minimum amount of collateral tokens to buy [wad] |
_bidAmount | uint256 | Amount of system coins to bid [wad] |
Errors
ColActions_InvalidAdjustedBid
Throws if the adjusted bid is invalid
error ColActions_InvalidAdjustedBid();
ColActions_InsufficientCollateralReceived
Throws if the received collateral is less than the minimum
error ColActions_InsufficientCollateralReceived(uint256 _minCollateralAmount, uint256 _received);
ICommonActions
Functions
joinSystemCoins
Joins system coins into the safeEngine
function joinSystemCoins(address _coinJoin, address _dst, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_dst | address | Address of the SAFE to join the coins into |
_wad | uint256 | Amount of coins to join [wad] |
exitSystemCoins
Exits system coins from the safeEngine
function exitSystemCoins(address _coinJoin, uint256 _coinsToExit) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_coinsToExit | uint256 | Amount of coins to exit [rad] |
exitAllSystemCoins
Exits all system coins from the safeEngine
function exitAllSystemCoins(address _coinJoin) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
exitCollateral
Exits collateral tokens from the safeEngine
function exitCollateral(address _collateralJoin, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_collateralJoin | address | Address of the CollateralJoin contract |
_wad | uint256 | Amount of collateral tokens to exit [wad] |
Errors
OnlyDelegateCalls
Throws if the method is being directly called, without a delegate call
error OnlyDelegateCalls();
IDebtBidActions
Inherits: ICommonActions
Functions
decreaseSoldAmount
Place a bid offering to receive a lesser amount of protocol tokens for covering the auctioned debt amount
function decreaseSoldAmount(
address _coinJoin,
address _debtAuctionHouse,
uint256 _auctionId,
uint256 _soldAmount
) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_debtAuctionHouse | address | Address of the DebtAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_soldAmount | uint256 | Amount of protocol tokens to receive [wad] |
settleAuction
Settles an auction, collecting the protocol tokens if the user is the highest bidder
This method will fail if the auction is not finished
function settleAuction(address _coinJoin, address _debtAuctionHouse, uint256 _auctionId) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_debtAuctionHouse | address | Address of the DebtAuctionHouse contract |
_auctionId | uint256 | Id of the auction to settle |
collectProtocolTokens
Collects the protocol tokens that the proxy has
This method is used to collect protocol tokens from an auction that was settled by another user
function collectProtocolTokens(address _protocolToken) external;
Parameters
Name | Type | Description |
---|---|---|
_protocolToken | address | Address of the protocol token |
IGlobalSettlementActions
Inherits: ICommonActions
Functions
freeCollateral
Free remaining collateral from a SAFE after being processed by the global settlement
function freeCollateral(
address _manager,
address _globalSettlement,
address _collateralJoin,
uint256 _safeId
) external returns (uint256 _collateralAmount);
Parameters
Name | Type | Description |
---|---|---|
_manager | address | Address of the HaiSafeManager contract |
_globalSettlement | address | Address of the GlobalSettlement contract |
_collateralJoin | address | Address of the CollateralJoin contract |
_safeId | uint256 | Id of the SAFE to free collateral from |
Returns
Name | Type | Description |
---|---|---|
_collateralAmount | uint256 | Amount of collateral freed [wad] |
prepareCoinsForRedeeming
Prepare coins for redeeming
function prepareCoinsForRedeeming(address _globalSettlement, address _coinJoin, uint256 _coinAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_globalSettlement | address | Address of the GlobalSettlement contract |
_coinJoin | address | Address of the CoinJoin contract |
_coinAmount | uint256 | Amount of coins to prepare for redeeming [wad] |
redeemCollateral
Redeem collateral tokens from the global settlement
function redeemCollateral(
address _globalSettlement,
address _collateralJoin
) external returns (uint256 _collateralAmount);
Parameters
Name | Type | Description |
---|---|---|
_globalSettlement | address | Address of the GlobalSettlement contract |
_collateralJoin | address | Address of the CollateralJoin contract |
Returns
Name | Type | Description |
---|---|---|
_collateralAmount | uint256 | Amount of collateral redeemed [wad] |
IRewardedActions
Inherits: ICommonActions
Functions
startDebtAuction
Starts a debt auction and transfers the reward to the user
function startDebtAuction(address _accountingJob, address _coinJoin) external;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
startSurplusAuction
Starts a surplus auction and transfers the reward to the user
function startSurplusAuction(address _accountingJob, address _coinJoin) external;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
popDebtFromQueue
Pops debt from accounting engine's queue and transfers the reward to the user
function popDebtFromQueue(address _accountingJob, address _coinJoin, uint256 _debtTimestamp) external;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_debtTimestamp | uint256 | Timestamp of the debt to pop from the queue |
transferExtraSurplus
Transfers surplus from accounting engine and transfers the reward to the user
function transferExtraSurplus(address _accountingJob, address _coinJoin) external;
Parameters
Name | Type | Description |
---|---|---|
_accountingJob | address | Address of the AccountingJob contract |
_coinJoin | address | Address of the CoinJoin contract |
liquidateSAFE
Starts a liquidation and transfers the reward to the user
function liquidateSAFE(address _liquidationJob, address _coinJoin, bytes32 _cType, address _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_liquidationJob | address | Address of the LiquidationJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE to liquidate |
updateCollateralPrice
Updates the price of a collateral type and transfers the reward to the user
function updateCollateralPrice(address _oracleJob, address _coinJoin, bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_oracleJob | address | Address of the OracleJob contract |
_coinJoin | address | Address of the CoinJoin contract |
_cType | bytes32 | Bytes32 representation of the collateral type |
updateRedemptionRate
Updates the redemption rate and transfers the reward to the user
function updateRedemptionRate(address _oracleJob, address _coinJoin) external;
Parameters
Name | Type | Description |
---|---|---|
_oracleJob | address | Address of the OracleJob contract |
_coinJoin | address | Address of the CoinJoin contract |
ISurplusBidActions
Inherits: ICommonActions
Functions
increaseBidSize
Place a bid offering to provide a higher amount of coins for receiving the auctioned protocol tokens
function increaseBidSize(address _surplusAuctionHouse, uint256 _auctionId, uint256 _bidAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse contract |
_auctionId | uint256 | Id of the auction to bid on |
_bidAmount | uint256 | Amount of system coins to bid [wad] |
settleAuction
Settles an auction, collecting the system coins if the user is the highest bidder
This method will fail if the auction is not finished
function settleAuction(address _coinJoin, address _surplusAuctionHouse, uint256 _auctionId) external;
Parameters
Name | Type | Description |
---|---|---|
_coinJoin | address | Address of the CoinJoin contract |
_surplusAuctionHouse | address | Address of the SurplusAuctionHouse contract |
_auctionId | uint256 | Id of the auction to settle |
IHaiProxy
Inherits: IHaiOwnable2Step
Functions
execute
Executes a call to the target contract through a delegate call
The proxy will call the target through a delegate call (the target must not be a direct protocol contract)
function execute(address _target, bytes memory _data) external payable returns (bytes memory _response);
Parameters
Name | Type | Description |
---|---|---|
_target | address | Address of the target Actions contract |
_data | bytes | Encoded data of the transaction to execute |
Returns
Name | Type | Description |
---|---|---|
_response | bytes | The raw response of the target call |
Errors
TargetAddressRequired
Throws if the target address is null
error TargetAddressRequired();
IHaiProxyFactory
Functions
isProxy
Mapping of proxy addresses to boolean state
function isProxy(address _proxyAddress) external view returns (bool _exists);
proxies
Mapping of user addresses to proxy instances
function proxies(address _owner) external view returns (IHaiProxy _proxy);
nonces
Mapping of the next nonce to be used for the specified owner
function nonces(address _owner) external view returns (uint256 _nonce);
build
Deploys a new proxy instance, setting the caller as the owner
function build() external returns (address payable _proxy);
Returns
Name | Type | Description |
---|---|---|
_proxy | address payable | Address of the new proxy |
build
Deploys a new proxy instance, setting the specified address as the owner
function build(address _owner) external returns (address payable _proxy);
Parameters
Name | Type | Description |
---|---|---|
_owner | address | Address of the owner of the new proxy |
Returns
Name | Type | Description |
---|---|---|
_proxy | address payable | Address of the new proxy |
Events
Created
Emitted when a new proxy is deployed
event Created(address indexed _sender, address indexed _owner, address _proxy);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the caller that deployed the proxy |
_owner | address | Address of the owner of the new proxy |
_proxy | address | Address of the new proxy |
Errors
AlreadyHasProxy
Throws if the user already has a proxy and remains being the owner
error AlreadyHasProxy(address _owner, IHaiProxy _proxy);
IHaiSafeManager
Functions
safeEngine
Address of the SAFEEngine
function safeEngine() external view returns (address _safeEngine);
safeCan
Mapping of owner and safe permissions to a caller permissions
function safeCan(address _owner, uint256 _safeId, address _caller) external view returns (bool _ok);
handlerCan
Mapping of handler to a caller permissions
function handlerCan(address _safeHandler, address _caller) external view returns (bool _ok);
getSafes
Getter for the list of safes owned by a user
function getSafes(address _usr) external view returns (uint256[] memory _safes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user |
getSafes
Getter for the list of safes owned by a user for a given collateral type
function getSafes(address _usr, bytes32 _cType) external view returns (uint256[] memory _safes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user for the given collateral type |
getSafesData
Getter for the details of the safes owned by a user
function getSafesData(address _usr)
external
view
returns (uint256[] memory _safes, address[] memory _safeHandlers, bytes32[] memory _cTypes);
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user |
Returns
Name | Type | Description |
---|---|---|
_safes | uint256[] | List of safe ids owned by the user |
_safeHandlers | address[] | List of safe handlers addresses owned by the user |
_cTypes | bytes32[] | List of collateral types of the safes owned by the user |
safeData
Getter for the details of a SAFE
function safeData(uint256 _safe) external view returns (SAFEData memory _sData);
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
Returns
Name | Type | Description |
---|---|---|
_sData | SAFEData | Struct with the safe data |
allowSAFE
Allow/disallow a user address to manage the safe
function allowSAFE(uint256 _safe, address _usr, bool _ok) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_usr | address | Address of the user to allow/disallow |
_ok | bool | Boolean state to allow/disallow |
allowHandler
Allow/disallow a handler address to manage the safe
function allowHandler(address _usr, bool _ok) external;
Parameters
Name | Type | Description |
---|---|---|
_usr | address | Address of the user to allow/disallow |
_ok | bool | Boolean state to allow/disallow |
openSAFE
Open a new safe for a user address
function openSAFE(bytes32 _cType, address _usr) external returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_usr | address | Address of the user to open the safe for |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the new SAFE |
transferSAFEOwnership
Initiate the transfer of the ownership of a safe to a dst address
function transferSAFEOwnership(uint256 _safe, address _dst) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
acceptSAFEOwnership
Accept the transfer of the ownership of a safe
function acceptSAFEOwnership(uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
modifySAFECollateralization
Modify a SAFE's collateralization ratio while keeping the generated COIN or collateral freed in the safe handler address
function modifySAFECollateralization(uint256 _safe, int256 _deltaCollateral, int256 _deltaDebt) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_deltaCollateral | int256 | Delta of collateral to add/remove [wad] |
_deltaDebt | int256 | Delta of debt to add/remove [wad] |
transferCollateral
Transfer wad amount of safe collateral from the safe address to a dst address
function transferCollateral(uint256 _safe, address _dst, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_wad | uint256 | Amount of collateral to transfer [wad] |
transferCollateral
Transfer wad amount of any type of collateral from the safe address to a dst address
This function has the purpose to take away collateral from the system that doesn't correspond to the safe but was sent there wrongly.
function transferCollateral(bytes32 _cType, uint256 _safe, address _dst, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_wad | uint256 | Amount of collateral to transfer [wad] |
transferInternalCoins
Transfer an amount of COIN from the safe address to a dst address [rad]
function transferInternalCoins(uint256 _safe, address _dst, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst address |
_rad | uint256 | Amount of COIN to transfer [rad] |
quitSystem
Quit the system, migrating the safe (lockedCollateral, generatedDebt) to a different dst handler
function quitSystem(uint256 _safe, address _dst) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_dst | address | Address of the dst handler |
enterSystem
Enter the system, migrating the safe (lockedCollateral, generatedDebt) from a src handler to the safe handler
function enterSystem(address _src, uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_src | address | Address of the src handler |
_safe | uint256 | Id of the SAFE |
moveSAFE
Move a position from safeSrc handler to the safeDst handler
function moveSAFE(uint256 _safeSrc, uint256 _safeDst) external;
Parameters
Name | Type | Description |
---|---|---|
_safeSrc | uint256 | Id of the source SAFE |
_safeDst | uint256 | Id of the destination SAFE |
addSAFE
Add a safe to the user's list of safes (doesn't set safe ownership)
This function is meant to allow the user to add a safe to their list (if it was previously removed)
function addSAFE(uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
removeSAFE
Remove a safe from the user's list of safes (doesn't erase safe ownership)
This function is meant to allow the user to remove a safe from their list (if it was added against their will)
function removeSAFE(uint256 _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
protectSAFE
Choose a safe saviour inside LiquidationEngine for the SAFE
function protectSAFE(uint256 _safe, address _liquidationEngine, address _saviour) external;
Parameters
Name | Type | Description |
---|---|---|
_safe | uint256 | Id of the SAFE |
_liquidationEngine | address | Address of the LiquidationEngine |
_saviour | address | Address of the saviour |
Events
AllowSAFE
Emitted when calling allowSAFE with the sender address and the method arguments
event AllowSAFE(address indexed _sender, uint256 indexed _safe, address _usr, bool _ok);
AllowHandler
Emitted when calling allowHandler with the sender address and the method arguments
event AllowHandler(address indexed _sender, address _usr, bool _ok);
InitiateTransferSAFEOwnership
Emitted when calling initiateTransferSAFEOwnership with the sender address and the method arguments
event InitiateTransferSAFEOwnership(address indexed _sender, uint256 indexed _safe, address _dst);
TransferSAFEOwnership
Emitted when calling transferSAFEOwnership with the sender address and the method arguments
event TransferSAFEOwnership(address indexed _sender, uint256 indexed _safe, address _dst);
OpenSAFE
Emitted when calling openSAFE with the sender address and the method arguments
event OpenSAFE(address indexed _sender, address indexed _own, uint256 indexed _safe);
ModifySAFECollateralization
Emitted when calling modifySAFECollateralization with the sender address and the method arguments
event ModifySAFECollateralization(
address indexed _sender, uint256 indexed _safe, int256 _deltaCollateral, int256 _deltaDebt
);
TransferCollateral
Emitted when calling transferCollateral with the sender address and the method arguments
event TransferCollateral(address indexed _sender, uint256 indexed _safe, address _dst, uint256 _wad);
TransferCollateral
Emitted when calling transferCollateral (specifying cType) with the sender address and the method arguments
event TransferCollateral(address indexed _sender, bytes32 _cType, uint256 indexed _safe, address _dst, uint256 _wad);
TransferInternalCoins
Emitted when calling transferInternalCoins with the sender address and the method arguments
event TransferInternalCoins(address indexed _sender, uint256 indexed _safe, address _dst, uint256 _rad);
QuitSystem
Emitted when calling quitSystem with the sender address and the method arguments
event QuitSystem(address indexed _sender, uint256 indexed _safe, address _dst);
EnterSystem
Emitted when calling enterSystem with the sender address and the method arguments
event EnterSystem(address indexed _sender, address _src, uint256 indexed _safe);
MoveSAFE
Emitted when calling moveSAFE with the sender address and the method arguments
event MoveSAFE(address indexed _sender, uint256 indexed _safeSrc, uint256 indexed _safeDst);
ProtectSAFE
Emitted when calling protectSAFE with the sender address and the method arguments
event ProtectSAFE(address indexed _sender, uint256 indexed _safe, address _liquidationEngine, address _saviour);
Errors
ZeroAddress
Throws if the provided address is null
error ZeroAddress();
SafeNotAllowed
Throws when trying to call a function not allowed for a given safe
error SafeNotAllowed();
HandlerNotAllowed
Throws when trying to call a function not allowed for a given handler
error HandlerNotAllowed();
AlreadySafeOwner
Throws when trying to transfer safe ownership to the current owner
error AlreadySafeOwner();
CollateralTypesMismatch
Throws when trying to move a safe to another one with different collateral type
error CollateralTypesMismatch();
Structs
SAFEData
struct SAFEData {
address owner;
address pendingOwner;
address safeHandler;
bytes32 collateralType;
}
Contents
IGlobalSettlement
Inherits: IAuthorizable, IDisableable, IModifiable
Functions
params
Getter for the contract parameters struct
function params() external view returns (GlobalSettlementParams memory _globalSettlementParams);
Returns
Name | Type | Description |
---|---|---|
_globalSettlementParams | GlobalSettlementParams | GlobalSettlement parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _shutdownCooldown);
Returns
Name | Type | Description |
---|---|---|
_shutdownCooldown | uint256 | Amount of seconds to wait before calculating redemptions after shutdown |
shutdownTime
The timestamp when settlement was triggered
function shutdownTime() external view returns (uint256 _shutdownTime);
outstandingCoinSupply
The outstanding coin supply computed during the settlement process [rad]
function outstandingCoinSupply() external view returns (uint256 _outstandingCoinSupply);
finalCoinPerCollateralPrice
The final coin per collateral price computed during the settlement process
function finalCoinPerCollateralPrice(bytes32 _cType) external view returns (uint256 _finalCoinPerCollateralPrice);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_finalCoinPerCollateralPrice | uint256 | The final amount of collateral that a system coin can redeem [rad] |
collateralShortfall
The total amount of bad debt for a collateral type computed during the settlement process
function collateralShortfall(bytes32 _cType) external view returns (uint256 _collateralShortfall);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralShortfall | uint256 | The total amount of bad debt for a collateral type [wad] |
collateralTotalDebt
The total amount of debt for a collateral type computed during the settlement process
function collateralTotalDebt(bytes32 _cType) external view returns (uint256 _collateralTotalDebt);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralTotalDebt | uint256 | The total amount of debt for a collateral type [wad] |
collateralCashPrice
Final collateral cash price computed during the settlement process, accounting for surplus / shortfall
function collateralCashPrice(bytes32 _cType) external view returns (uint256 _collateralCashPrice);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralCashPrice | uint256 | The final collateral cash price [ray] |
coinBag
Mapping containing the total amount of coins a user has prepared for redeeming
function coinBag(address _coinHolder) external view returns (uint256 _coinBag);
Parameters
Name | Type | Description |
---|---|---|
_coinHolder | address | The address of the user |
Returns
Name | Type | Description |
---|---|---|
_coinBag | uint256 | Amount of coins prepared for redeeming [wad] |
coinsUsedToRedeem
Mapping containing the total amount of coins a user has used to redeem collateral
function coinsUsedToRedeem(bytes32 _cType, address _coinHolder) external view returns (uint256 _coinsUsedToRedeem);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_coinHolder | address | The address of the user |
Returns
Name | Type | Description |
---|---|---|
_coinsUsedToRedeem | uint256 | Amount of coins already used to redeem collateral [wad] |
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
liquidationEngine
Address of the LiquidationEngine contract
function liquidationEngine() external view returns (ILiquidationEngine _liquidationEngine);
oracleRelayer
Address of the OracleRelayer contract
function oracleRelayer() external view returns (IOracleRelayer _oracleRelayer);
accountingEngine
Address of the AccountingEngine contract
function accountingEngine() external view returns (IDisableable _accountingEngine);
stabilityFeeTreasury
Address of the StabilityFeeTreasury contract
function stabilityFeeTreasury() external view returns (IDisableable _stabilityFeeTreasury);
coinJoin
Address of the CoinJoin contract
function coinJoin() external view returns (IDisableable _coinJoin);
collateralJoinFactory
Address of the CollateralJoinFactory contract
function collateralJoinFactory() external view returns (IDisableable _collateralJoinFactory);
collateralAuctionHouseFactory
Address of the CollateralAuctionHouseFactory contract
function collateralAuctionHouseFactory() external view returns (IDisableable _collateralAuctionHouseFactory);
shutdownSystem
Freeze the system and start the cooldown period
This function switches the whenEnabled
/whenDisabled
modifiers across the system contracts
function shutdownSystem() external;
freezeCollateralType
Calculate a collateral type's final price according to the latest system coin redemption price
function freezeCollateralType(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to calculate the price for |
fastTrackAuction
Fast track an ongoing collateral auction
function fastTrackAuction(bytes32 _cType, uint256 _auctionId) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type associated with the auction contract |
_auctionId | uint256 | The ID of the auction to be fast tracked |
processSAFE
Cancel a SAFE's debt and leave any extra collateral in it
function processSAFE(bytes32 _cType, address _safe) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type associated with the SAFE |
_safe | address | The SAFE to be processed |
freeCollateral
Remove collateral from the caller's SAFE (requires SAFE to have no debt)
function freeCollateral(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to free |
setOutstandingCoinSupply
Set the final outstanding supply of system coins
There must be no remaining surplus in the accounting engine
function setOutstandingCoinSupply() external;
calculateCashPrice
Calculate a collateral's price taking into consideration system surplus/deficit and the finalCoinPerCollateralPrice
function calculateCashPrice(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral whose cash price will be calculated |
prepareCoinsForRedeeming
Add coins into a 'bag' so that you can use them to redeem collateral
function prepareCoinsForRedeeming(uint256 _coinAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_coinAmount | uint256 | The amount of internal system coins to add into the bag |
redeemCollateral
Redeem a specific collateral type using an amount of internal system coins from your bag
function redeemCollateral(bytes32 _cType, uint256 _coinsAmount) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The collateral type to redeem |
_coinsAmount | uint256 | The amount of internal coins to use from your bag |
Events
ShutdownSystem
Emitted when the system is shutdown and the global settlement process begins
event ShutdownSystem();
FreezeCollateralType
Emitted when a collateral type's final price is calculated
event FreezeCollateralType(bytes32 indexed _cType, uint256 _finalCoinPerCollateralPrice);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_finalCoinPerCollateralPrice | uint256 | The final amount of collateral that a system coin can redeem [rad] |
FastTrackAuction
Emitted when a collateral auction is fast tracked
event FastTrackAuction(bytes32 indexed _cType, uint256 indexed _auctionId, uint256 _collateralTotalDebt);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_auctionId | uint256 | The ID of the auction to be fast tracked |
_collateralTotalDebt | uint256 | The cumulative amount of debt for the collateral type [wad] |
ProcessSAFE
Emitted when a SAFE is processed
event ProcessSAFE(bytes32 indexed _cType, address indexed _safe, uint256 _collateralShortfall);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the processed SAFE |
_collateralShortfall | uint256 | The cumulative amount of bad debt for the collateral type [wad] |
FreeCollateral
Emitted when a SAFE's surplus collateral is withdrawn
event FreeCollateral(bytes32 indexed _cType, address indexed _sender, uint256 _collateralAmount);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_sender | address | Address of the caller (representing the SAFE) |
_collateralAmount | uint256 | The amount of collateral withdrawn [wad] |
SetOutstandingCoinSupply
Emitted when the final outstanding coin supply is set
event SetOutstandingCoinSupply(uint256 _outstandingCoinSupply);
Parameters
Name | Type | Description |
---|---|---|
_outstandingCoinSupply | uint256 | The final outstanding coin supply [rad] |
CalculateCashPrice
Emitted when a collateral type's cash price is calculated
event CalculateCashPrice(bytes32 indexed _cType, uint256 _collateralCashPrice);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_collateralCashPrice | uint256 | The final collateral cash price [ray] |
PrepareCoinsForRedeeming
Emitted when a user adds coins into a 'bag' so that they can use them to redeem collateral
event PrepareCoinsForRedeeming(address indexed _sender, uint256 _coinBag);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the caller |
_coinBag | uint256 | The cumulative of coins prepared for redeeming [wad] |
RedeemCollateral
Emitted when a user redeems a specific collateral type using an amount of internal system coins from their bag
event RedeemCollateral(
bytes32 indexed _cType, address indexed _sender, uint256 _coinsAmount, uint256 _collateralAmount
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_sender | address | Address of the caller |
_coinsAmount | uint256 | The amount of internal coins used from the bag [wad] |
_collateralAmount | uint256 | The amount of collateral redeemed [wad] |
Errors
GS_FinalCollateralPriceAlreadyDefined
Throws when trying to freeze a collateral type that has already been frozen
error GS_FinalCollateralPriceAlreadyDefined();
GS_FinalCollateralPriceNotDefined
Throws when trying to fast track an auction while the collateral type is not frozen
error GS_FinalCollateralPriceNotDefined();
GS_SafeDebtNotZero
Throws when trying to free the collateral from an unprocessed SAFE
error GS_SafeDebtNotZero();
GS_OutstandingCoinSupplyNotZero
Throws when trying to set the final outstanding coin supply, when it was already set
error GS_OutstandingCoinSupplyNotZero();
GS_OutstandingCoinSupplyZero
Throws when trying to set the final collateral cash price, when the outstanding coin supply was not set
error GS_OutstandingCoinSupplyZero();
GS_SurplusNotZero
Throws when trying to set the final outstanding coin supply, when there's still surplus in the protocol
error GS_SurplusNotZero();
GS_ShutdownCooldownNotFinished
Throws when trying to set the final outstanding coin supply, when the cooldown period has not passed
error GS_ShutdownCooldownNotFinished();
GS_CollateralCashPriceAlreadyDefined
Throws when trying to set the final collateral cash price, when it was already set
error GS_CollateralCashPriceAlreadyDefined();
GS_CollateralCashPriceNotDefined
Throws when trying to redeem collateral when the final collateral cash price was not set
error GS_CollateralCashPriceNotDefined();
GS_InsufficientBagBalance
Throws when trying to redeem more collateral than the user's bag can afford
error GS_InsufficientBagBalance();
Structs
GlobalSettlementParams
struct GlobalSettlementParams {
uint256 shutdownCooldown;
}
IPostSettlementSurplusAuctionHouse
Inherits: IAuthorizable, IModifiable, ICommonSurplusAuctionHouse
Functions
params
Getter for the contract parameters struct
function params() external view returns (PostSettlementSAHParams memory _pssahParams);
Returns
Name | Type | Description |
---|---|---|
_pssahParams | PostSettlementSAHParams | The contract parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _bidIncrease, uint256 _bidDuration, uint256 _totalAuctionLength);
Returns
Name | Type | Description |
---|---|---|
_bidIncrease | uint256 | A percentage of the last bid that needs to be added in order to take the new bid in consideration |
_bidDuration | uint256 | The duration of the bid after which an auction is considered finished |
_totalAuctionLength | uint256 | The total duration of the auction after which an auction is considered finished |
Structs
PostSettlementSAHParams
struct PostSettlementSAHParams {
uint256 bidIncrease;
uint256 bidDuration;
uint256 totalAuctionLength;
}
ISettlementSurplusAuctioneer
Inherits: IAuthorizable, IModifiable
Functions
lastSurplusTime
The last time when this contract triggered a surplus auction
function lastSurplusTime() external view returns (uint256 _lastSurplusTime);
accountingEngine
The address of the AccountingEngine
function accountingEngine() external view returns (IAccountingEngine _accountingEngine);
surplusAuctionHouse
The address of the SurplusAuctionHouse
function surplusAuctionHouse() external view returns (ISurplusAuctionHouse _surplusAuctionHouse);
safeEngine
The address of the SAFEEngine
function safeEngine() external view returns (ISAFEEngine _safeEngine);
auctionSurplus
Starts a new surplus auction
The contract reads surplus auction parameters from the AccountingEngine
function auctionSurplus() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | The id of the started auction |
Events
AuctionSurplus
Emitted when the contract triggers a surplus auction
event AuctionSurplus(uint256 indexed _id, uint256 _lastSurplusAuctionTime, uint256 _coinBalance);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | The id of the started auction |
_lastSurplusAuctionTime | uint256 | The timestamp of the surplus auction |
_coinBalance | uint256 | The remaining coin balance of the contract |
Errors
SSA_AccountingEngineStillEnabled
Throws if the AccountingEngine is still enabled
error SSA_AccountingEngineStillEnabled();
SSA_SurplusAuctionDelayNotPassed
Throws if the surplus auction delay has not passed
error SSA_SurplusAuctionDelayNotPassed();
Contents
IProtocolToken
Inherits: IERC20Metadata, IERC20Permit, IVotes, IAuthorizable
Functions
mint
Mint an amount of tokens to an account
Only authorized addresses can mint tokens
function mint(address _account, uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address of the account to mint tokens to |
_amount | uint256 | Amount of tokens to mint [wad] |
burn
Burn an amount of tokens from the sender
function burn(uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_amount | uint256 | Amount of tokens to burn [wad] |
unpause
Unpause the token transfers, minting and burning
Only authorized addresses can unpause the token
function unpause() external;
ISystemCoin
Inherits: IERC20Metadata, IAuthorizable
Functions
mint
Mint an amount of tokens to an account
Only authorized addresses can mint tokens
function mint(address _account, uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address of the account to mint tokens to |
_amount | uint256 | Amount of tokens to mint [wad] |
burn
Burn an amount of tokens from the sender
function burn(uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_amount | uint256 | Amount of tokens to burn [wad] |
ITokenDistributor
Inherits: IAuthorizable
Functions
token
Address of the ERC20 token to be distributed
function token() external view returns (IProtocolToken _token);
root
The merkle root of the token distribution
function root() external view returns (bytes32 _root);
totalClaimable
Total amount of tokens to be distributed
function totalClaimable() external view returns (uint256 _totalClaimable);
claimPeriodStart
Timestamp when the claim period starts
function claimPeriodStart() external view returns (uint256 _claimPeriodStart);
claimPeriodEnd
Timestamp when the claim period ends
function claimPeriodEnd() external view returns (uint256 _claimPeriodEnd);
canClaim
Checks if a user can claim tokens
function canClaim(bytes32[] calldata _proof, address _user, uint256 _amount) external view returns (bool _claimable);
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_user | address | Address of the user to check |
_amount | uint256 | Amount of tokens to check |
Returns
Name | Type | Description |
---|---|---|
_claimable | bool | Whether the user can claim the amount with the proof provided |
claim
Claims tokens from the distributor
function claim(bytes32[] calldata _proof, uint256 _amount) external;
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_amount | uint256 | Amount of tokens to claim |
claimAndDelegate
Claims tokens from the distributor and delegates them using a signature
function claimAndDelegate(
bytes32[] calldata _proof,
uint256 _amount,
address _delegatee,
uint256 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
Parameters
Name | Type | Description |
---|---|---|
_proof | bytes32[] | Array of bytes32 merkle proof hashes |
_amount | uint256 | Amount of tokens to claim |
_delegatee | address | Address to delegate the token votes to |
_expiry | uint256 | Expiration timestamp of the signature |
_v | uint8 | Recovery byte of the signature |
_r | bytes32 | ECDSA signature r value |
_s | bytes32 | ECDSA signature s value |
claimed
Mapping containing the users that have already claimed
function claimed(address _user) external view returns (bool _claimed);
Parameters
Name | Type | Description |
---|---|---|
_user | address | Address of the user to check |
Returns
Name | Type | Description |
---|---|---|
_claimed | bool | Boolean indicating if the user has claimed |
sweep
Withdraws tokens from the distributor to a given address after the claim period has ended
function sweep(address _sweepReceiver) external;
Parameters
Name | Type | Description |
---|---|---|
_sweepReceiver | address | Address to send the tokens to |
Events
Claimed
Emitted when a user claims tokens
event Claimed(address _user, uint256 _amount);
Parameters
Name | Type | Description |
---|---|---|
_user | address | Address of the user that claimed |
_amount | uint256 | Amount of tokens claimed |
Swept
Emitted when the distributor is swept (after the claim period has ended)
event Swept(address _sweepReceiver, uint256 _amount);
Parameters
Name | Type | Description |
---|---|---|
_sweepReceiver | address | Address that received the swept tokens |
_amount | uint256 | Amount of tokens swept |
Errors
TokenDistributor_ClaimPeriodNotEnded
Throws when trying to sweep before the claim period has ended
error TokenDistributor_ClaimPeriodNotEnded();
TokenDistributor_ClaimInvalid
Throws when trying to claim but the claim is not valid
error TokenDistributor_ClaimInvalid();
Structs
TokenDistributorParams
struct TokenDistributorParams {
bytes32 root;
uint256 totalClaimable;
uint256 claimPeriodStart;
uint256 claimPeriodEnd;
}
Contents
- IAuthorizable
- ICoinJoin
- ICollateralJoin
- IDisableable
- IHaiOwnable2Step
- IModifiable
- IModifiablePerCollateral
IAuthorizable
Functions
authorizedAccounts
Checks whether an account is authorized on the contract
function authorizedAccounts(address _account) external view returns (bool _authorized);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to check |
Returns
Name | Type | Description |
---|---|---|
_authorized | bool | Whether the account is authorized or not |
authorizedAccounts
Getter for the authorized accounts
function authorizedAccounts() external view returns (address[] memory _accounts);
Returns
Name | Type | Description |
---|---|---|
_accounts | address[] | Array of authorized accounts |
addAuthorization
Add authorization to an account
Method will revert if the account is already authorized
function addAuthorization(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to add authorization to |
removeAuthorization
Remove authorization from an account
Method will revert if the account is not authorized
function removeAuthorization(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to remove authorization from |
Events
AddAuthorization
Emitted when an account is authorized
event AddAuthorization(address _account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that is authorized |
RemoveAuthorization
Emitted when an account is unauthorized
event RemoveAuthorization(address _account);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that is unauthorized |
Errors
AlreadyAuthorized
Throws if the account is already authorized on addAuthorization
error AlreadyAuthorized();
NotAuthorized
Throws if the account is not authorized on removeAuthorization
error NotAuthorized();
Unauthorized
Throws if the account is not authorized and tries to call an onlyAuthorized
method
error Unauthorized();
ICoinJoin
Inherits: IAuthorizable, IDisableable
Functions
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
systemCoin
Address of the SystemCoin contract
function systemCoin() external view returns (ISystemCoin _systemCoin);
decimals
Number of decimals the coin has
function decimals() external view returns (uint256 _decimals);
join
Join system coins in the system
Exited coins have 18 decimals but inside the system they have 45 [rad] decimals. When we join, the amount [wad] is multiplied by 10**27 [ray]
function join(address _account, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that will receive the joined coins |
_wad | uint256 | Amount of external coins to join [wad] |
exit
Exit system coins from the system
New coins cannot be minted after the system is disabled
Inside the system, coins have 45 decimals [rad] but outside of it they have 18 decimals [wad]. When we exit, we specify a wad amount of coins and then the contract automatically multiplies wad by 10**27 to move the correct 45 decimal coin amount to this adapter
function exit(address _account, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that will receive the exited coins |
_wad | uint256 | Amount of internal coins to join (18 decimal number) |
Events
Join
Emitted when an account joins coins into the system
event Join(address _sender, address _account, uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the account that called the function (sent the ERC20 coins) |
_account | address | Address of the account that received the coins |
_wad | uint256 | Amount of coins joined [wad] |
Exit
Emitted when an account exits coins from the system
event Exit(address _sender, address _account, uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the account that called the function (sent the internal coins) |
_account | address | Address of the account that received the ERC20 coins |
_wad | uint256 | Amount of coins exited [wad] |
ICollateralJoin
Inherits: IAuthorizable, IDisableable
Functions
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
collateral
Address of the ERC20 collateral token contract
function collateral() external view returns (IERC20Metadata _collateral);
collateralType
The collateral type that this contract handles
function collateralType() external view returns (bytes32 _cType);
Returns
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateralType |
decimals
Number of decimals of the collateral token
function decimals() external view returns (uint256 _decimals);
multiplier
Multiplier used to transform collateral into 18 decimals within the system
function multiplier() external view returns (uint256 _multiplier);
join
Join collateral in the system
function join(address _account, uint256 _wei) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to which we add collateral into the system |
_wei | uint256 | Amount of collateral to transfer in the system (represented as a number with token decimals) |
exit
Exit collateral from the system
function exit(address _account, uint256 _wei) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to which we transfer the collateral out of the system |
_wei | uint256 | Amount of collateral to transfer to account (represented as a number with token decimals) |
Events
Join
Emitted when an account joins collateral tokens into the system
event Join(address _sender, address _account, uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the account that called the function (sent the ERC20 collateral tokens) |
_account | address | Address of the account that received the collateral tokens |
_wad | uint256 | Amount of collateral tokens joined [wad] |
Exit
Emitted when an account exits collateral tokens from the system
event Exit(address _sender, address _account, uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address of the account that called the function (sent the internal collateral tokens) |
_account | address | Address of the account that received the ERC20 collateral tokens |
_wad | uint256 | Amount of collateral tokens exited [wad] |
IDisableable
Inherits: IAuthorizable
Functions
contractEnabled
Check if the contract is enabled
function contractEnabled() external view returns (bool _contractEnabled);
Returns
Name | Type | Description |
---|---|---|
_contractEnabled | bool | True if the contract is enabled |
disableContract
External method to trigger the contract disablement
Triggers an internal call to _onContractDisable
virtual method
function disableContract() external;
Events
DisableContract
Emitted when the inheriting contract is disabled
event DisableContract();
Errors
ContractIsEnabled
Throws when trying to call a whenDisabled
method when the contract is enabled
error ContractIsEnabled();
ContractIsDisabled
Throws when trying to call a whenEnabled
method when the contract is disabled
error ContractIsDisabled();
NonDisableable
Throws when trying to disable a contract that cannot be disabled
error NonDisableable();
IHaiOwnable2Step
Functions
owner
Emitted when an ownership transfer is initiated
Throws if the caller account is not authorized to perform an operation
Throws if the owner is not a valid owner account
The address of the current owner
function owner() external view returns (address _owner);
pendingOwner
The address of the pending owner
function pendingOwner() external view returns (address _pendingOwner);
renounceOwnership
Leaves the contract without an owner, thereby disabling any functionality that is only available to the owner
It will not be possible to call onlyOwner
functions
Can only be called by the current owner
function renounceOwnership() external;
transferOwnership
Starts the ownership transfer of the contract to a new account
Replaces the pending transfer if there is one
Can only be called by the current owner
function transferOwnership(address _newOwner) external;
Parameters
Name | Type | Description |
---|---|---|
_newOwner | address | The address of the new owner |
acceptOwnership
Accepts the ownership transfer
Can only be called by the current pending owner
function acceptOwnership() external;
IModifiable
Inherits: IAuthorizable
Functions
modifyParameters
Set a new value for a global specific parameter
function modifyParameters(bytes32 _param, bytes memory _data) external;
Parameters
Name | Type | Description |
---|---|---|
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
Events
ModifyParameters
Event topic 1 is always a parameter, topic 2 can be empty (global params)
event ModifyParameters(bytes32 indexed _param, bytes32 indexed _cType, bytes _data);
Errors
UnrecognizedParam
error UnrecognizedParam();
UnrecognizedCType
error UnrecognizedCType();
IModifiablePerCollateral
Inherits: IAuthorizable, IModifiable
Functions
collateralList
List of all the collateral types registered in the OracleRelayer
function collateralList() external view returns (bytes32[] memory __collateralList);
Returns
Name | Type | Description |
---|---|---|
__collateralList | bytes32[] | Array of all the collateral types registered |
initializeCollateralType
Register a new collateral type in the SAFEEngine
function initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to register |
_collateralParams | bytes | Collateral parameters |
modifyParameters
Set a new value for a collateral specific parameter
function modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | String identifier of the collateral to modify |
_param | bytes32 | String identifier of the parameter to modify |
_data | bytes | Encoded data to modify the parameter |
Events
InitializeCollateralType
Emitted when a new collateral type is registered
event InitializeCollateralType(bytes32 _cType);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Errors
CollateralTypeAlreadyInitialized
error CollateralTypeAlreadyInitialized();
IAccountingEngine
Inherits: IAuthorizable, IDisableable, IModifiable
Functions
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
surplusAuctionHouse
Address of the SurplusAuctionHouse contract
function surplusAuctionHouse() external view returns (ISurplusAuctionHouse _surplusAuctionHouse);
debtAuctionHouse
Address of the DebtAuctionHouse contract
function debtAuctionHouse() external view returns (IDebtAuctionHouse _debtAuctionHouse);
postSettlementSurplusDrain
The post settlement surplus drain is used to transfer remaining surplus after settlement is triggered
Usually the SettlementSurplusAuctioneer
contract
function postSettlementSurplusDrain() external view returns (address _postSettlementSurplusDrain);
Returns
Name | Type | Description |
---|---|---|
_postSettlementSurplusDrain | address | Address of the contract that handles post settlement surplus |
extraSurplusReceiver
The extra surplus receiver is used to transfer surplus if is not being auctioned
function extraSurplusReceiver() external view returns (address _extraSurplusReceiver);
Returns
Name | Type | Description |
---|---|---|
_extraSurplusReceiver | address | Address of the contract that handles extra surplus transfers |
params
Getter for the contract parameters struct
function params() external view returns (AccountingEngineParams memory _params);
Returns
Name | Type | Description |
---|---|---|
_params | AccountingEngineParams | AccountingEngine parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (
uint256 _surplusIsTransferred,
uint256 _surplusDelay,
uint256 _popDebtDelay,
uint256 _disableCooldown,
uint256 _surplusAmount,
uint256 _surplusBuffer,
uint256 _debtAuctionMintedTokens,
uint256 _debtAuctionBidSize
);
Returns
Name | Type | Description |
---|---|---|
_surplusIsTransferred | uint256 | Whether the system transfers surplus instead of auctioning it [0/1] |
_surplusDelay | uint256 | Amount of seconds between surplus actions |
_popDebtDelay | uint256 | Amount of seconds after which debt can be popped from debtQueue |
_disableCooldown | uint256 | Amount of seconds to wait (post settlement) until surplus can be drained |
_surplusAmount | uint256 | Amount of surplus transferred or sold in one surplus action [rad] |
_surplusBuffer | uint256 | Amount of surplus that needs to accrue in this contract before any surplus action can start [rad] |
_debtAuctionMintedTokens | uint256 | Amount of protocol tokens to be minted in debt auctions [wad] |
_debtAuctionBidSize | uint256 | Amount of debt sold in one debt auction [rad] |
totalOnAuctionDebt
The total amount of debt that is currently on auction in the DebtAuctionHouse
function totalOnAuctionDebt() external view returns (uint256 _totalOnAuctionDebt);
Returns
Name | Type | Description |
---|---|---|
_totalOnAuctionDebt | uint256 | Total amount of debt that is currently on auction [rad] |
debtQueue
A mapping storing debtBlocks that need to be covered by auctions
A debtBlock can be popped from the queue (to be auctioned) if more than popDebtDelay
has elapsed since creation
function debtQueue(uint256 _blockTimestamp) external view returns (uint256 _debtBlock);
Parameters
Name | Type | Description |
---|---|---|
_blockTimestamp | uint256 | The timestamp of the debtBlock |
Returns
Name | Type | Description |
---|---|---|
_debtBlock | uint256 | The amount of debt created in the inputted blockTimestamp [rad] |
totalQueuedDebt
The total amount of debt that is currently in the debtQueue to be auctioned
function totalQueuedDebt() external view returns (uint256 _totalQueuedDebt);
Returns
Name | Type | Description |
---|---|---|
_totalQueuedDebt | uint256 | Total amount of debt in RAD that is currently in the debtQueue [rad] |
lastSurplusTime
The timestamp of the last time surplus was transferred or auctioned
function lastSurplusTime() external view returns (uint256 _lastSurplusTime);
Returns
Name | Type | Description |
---|---|---|
_lastSurplusTime | uint256 | Timestamp of when the last surplus transfer or auction was triggered |
unqueuedUnauctionedDebt
Returns the amount of bad debt that is not in the debtQueue and is not currently handled by debt auctions
The difference between the debt in the SAFEEngine and the debt in the debtQueue and on auction
function unqueuedUnauctionedDebt() external view returns (uint256 _unqueuedUnauctionedDebt);
Returns
Name | Type | Description |
---|---|---|
_unqueuedUnauctionedDebt | uint256 | Amount of debt in RAD that is currently not in the debtQueue and not on auction [rad] |
disableTimestamp
When the contract is disabled (usually by GlobalSettlement
) it has to wait disableCooldown
before any remaining surplus can be transferred to postSettlementSurplusDrain
function disableTimestamp() external view returns (uint256 _disableTimestamp);
Returns
Name | Type | Description |
---|---|---|
_disableTimestamp | uint256 | Timestamp of when the contract was disabled |
pushDebtToQueue
Push a block of debt to the debt queue
Usually called by the LiquidationEngine
when a SAFE is liquidated
Debt is locked in a queue to give the system enough time to auction collateral and gather surplus
function pushDebtToQueue(uint256 _debtBlock) external;
Parameters
Name | Type | Description |
---|---|---|
_debtBlock | uint256 | Amount of debt to push [rad] |
popDebtFromQueue
Pop a block of debt from the debt queue
A debtBlock can be popped from the queue after popDebtDelay
seconds have passed since creation
function popDebtFromQueue(uint256 _debtBlockTimestamp) external;
Parameters
Name | Type | Description |
---|---|---|
_debtBlockTimestamp | uint256 | Timestamp of the block of debt that should be popped out |
settleDebt
Destroy an equal amount of coins and debt
It can only destroy debt that is not locked in the queue and also not in a debt auction (unqueuedUnauctionedDebt
)
function settleDebt(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt to destroy [rad] |
cancelAuctionedDebtWithSurplus
Use surplus coins to destroy debt that was in a debt auction
Usually called by the DebtAuctionHouse
after a debt bid is made
function cancelAuctionedDebtWithSurplus(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt to destroy with surplus [rad] |
auctionDebt
Start a debt auction (print protocol tokens in exchange for coins so that the system can be recapitalized)
It can only auction debt that has been popped from the debt queue and is not already being auctioned
function auctionDebt() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the debt auction that was started |
auctionSurplus
Start a surplus auction (sell surplus stability fees for protocol tokens)
It can only auction surplus if surplusIsTransferred
is set to false
It can only auction surplus if surplusDelay
seconds have elapsed since the last surplus auction/transfer was triggered
It can only auction surplus if enough surplus remains in the buffer and if there is no more debt left to settle
function auctionSurplus() external returns (uint256 _id);
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the surplus auction that was started |
transferExtraSurplus
Transfer surplus to an address as an alternative to surplus auctions
It can only transfer surplus if surplusIsTransferred
is set to true
It can only transfer surplus if surplusDelay
seconds have elapsed since the last surplus auction/transfer was triggered
It can only transfer surplus if enough surplus remains in the buffer and if there is no more debt left to settle
function transferExtraSurplus() external;
transferPostSettlementSurplus
Transfer any remaining surplus after the disable cooldown has passed. Meant to be a backup in case GlobalSettlement.processSAFE has a bug, governance doesn't have power over the system and there's still surplus left in the AccountingEngine which then blocks GlobalSettlement.setOutstandingCoinSupply.
Transfer any remaining surplus after disableCooldown
seconds have passed since disabling the contract
function transferPostSettlementSurplus() external;
Events
PushDebtToQueue
Emitted when a block of debt is pushed to the debt queue
event PushDebtToQueue(uint256 indexed _timestamp, uint256 _debtAmount);
Parameters
Name | Type | Description |
---|---|---|
_timestamp | uint256 | Timestamp of the block of debt that was pushed |
_debtAmount | uint256 | Amount of debt that was pushed [rad] |
PopDebtFromQueue
Emitted when a block of debt is popped from the debt queue
event PopDebtFromQueue(uint256 indexed _timestamp, uint256 _debtAmount);
Parameters
Name | Type | Description |
---|---|---|
_timestamp | uint256 | Timestamp of the block of debt that was popped |
_debtAmount | uint256 | Amount of debt that was popped [rad] |
SettleDebt
Emitted when the contract destroys an equal amount of coins and debt
event SettleDebt(uint256 _rad, uint256 _coinBalance, uint256 _debtBalance);
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt that was destroyed [rad] |
_coinBalance | uint256 | Amount of coins that remains after debt settlement [rad] |
_debtBalance | uint256 | Amount of debt that remains after debt settlement [rad] |
CancelDebt
Emitted when the contract destroys an equal amount of coins and debt with surplus
Normally called with coins received from the DebtAuctionHouse
event CancelDebt(uint256 _rad, uint256 _coinBalance, uint256 _debtBalance);
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of coins & debt that was destroyed with surplus [rad] |
_coinBalance | uint256 | Amount of coins that remains after debt settlement [rad] |
_debtBalance | uint256 | Amount of debt that remains after debt settlement [rad] |
AuctionDebt
Emitted when a debt auction is started
event AuctionDebt(uint256 indexed _id, uint256 _initialBid, uint256 _debtAuctioned);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the debt auction that was started |
_initialBid | uint256 | Amount of protocol tokens that are initially offered in the debt auction [wad] |
_debtAuctioned | uint256 | Amount of debt that is being auctioned [rad] |
AuctionSurplus
Emitted when a surplus auction is started
event AuctionSurplus(uint256 indexed _id, uint256 _initialBid, uint256 _surplusAuctioned);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the surplus auction that was started |
_initialBid | uint256 | Amount of protocol tokens that are initially bidded in the surplus auction [wad] |
_surplusAuctioned | uint256 | Amount of surplus that is being auctioned [rad] |
TransferSurplus
Emitted when surplus is transferred to an address
event TransferSurplus(address indexed _extraSurplusReceiver, uint256 _surplusTransferred);
Parameters
Name | Type | Description |
---|---|---|
_extraSurplusReceiver | address | Address that received the surplus |
_surplusTransferred | uint256 | Amount of surplus that was transferred [rad] |
Errors
AccEng_DebtAuctionDisabled
Throws when trying to auction debt when it is disabled
error AccEng_DebtAuctionDisabled();
AccEng_SurplusAuctionDisabled
Throws when trying to auction surplus when it is disabled
error AccEng_SurplusAuctionDisabled();
AccEng_SurplusTransferDisabled
Throws when trying to transfer surplus when it is disabled
error AccEng_SurplusTransferDisabled();
AccEng_InsufficientDebt
Throws when trying to settle debt when there is not enough debt left to settle
error AccEng_InsufficientDebt();
AccEng_InsufficientSurplus
Throws when trying to auction / transfer surplus when there is not enough surplus
error AccEng_InsufficientSurplus();
AccEng_NullAmount
Throws when trying to push / pop / auction a null amount of debt / surplus
error AccEng_NullAmount();
AccEng_NullSurplusReceiver
Throws when trying to transfer surplus to a null address
error AccEng_NullSurplusReceiver();
AccEng_SurplusCooldown
Throws when trying to auction / transfer surplus before the cooldown has passed
error AccEng_SurplusCooldown();
AccEng_PopDebtCooldown
Throws when trying to pop debt before the cooldown has passed
error AccEng_PopDebtCooldown();
AccEng_PostSettlementCooldown
Throws when trying to transfer post-settlement surplus before the disable cooldown has passed
error AccEng_PostSettlementCooldown();
Structs
AccountingEngineParams
struct AccountingEngineParams {
uint256 surplusIsTransferred;
uint256 surplusDelay;
uint256 popDebtDelay;
uint256 disableCooldown;
uint256 surplusAmount;
uint256 surplusBuffer;
uint256 debtAuctionMintedTokens;
uint256 debtAuctionBidSize;
}
ICollateralAuctionHouse
Inherits: IAuthorizable, IDisableable, IModifiable
Functions
AUCTION_HOUSE_TYPE
Type of the auction house
function AUCTION_HOUSE_TYPE() external view returns (bytes32 _auctionHouseType);
Returns
Name | Type | Description |
---|---|---|
_auctionHouseType | bytes32 | Bytes32 representation of the auction house type |
auctions
Data of an auction
function auctions(uint256 _auctionId) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_auctionId | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
_auctions
Unpacked data of an auction
function _auctions(uint256 _auctionId)
external
view
returns (
uint256 _amountToSell,
uint256 _amountToRaise,
uint256 _initialTimestamp,
address _forgoneCollateralReceiver,
address _auctionIncomeRecipient
);
Parameters
Name | Type | Description |
---|---|---|
_auctionId | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_amountToSell | uint256 | How much collateral is sold in an auction [wad] |
_amountToRaise | uint256 | Total/max amount of coins to raise [rad] |
_initialTimestamp | uint256 | Time when the auction was created |
_forgoneCollateralReceiver | address | Who receives leftover collateral that is not sold in the auction (usually the liquidated SAFE) |
_auctionIncomeRecipient | address | Who receives the coins raised by the auction (usually the AccountingEngine) |
params
Getter for the contract parameters struct
function params() external view returns (CollateralAuctionHouseParams memory _cahParams);
Returns
Name | Type | Description |
---|---|---|
_cahParams | CollateralAuctionHouseParams | Auction house parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (uint256 _minimumBid, uint256 _minDiscount, uint256 _maxDiscount, uint256 _perSecondDiscountUpdateRate);
Returns
Name | Type | Description |
---|---|---|
_minimumBid | uint256 | Minimum acceptable bid [wad] |
_minDiscount | uint256 | Minimum discount at which collateral is being sold [wad %] |
_maxDiscount | uint256 | Maximum discount at which collateral is being sold [wad %] |
_perSecondDiscountUpdateRate | uint256 | Rate at which the discount will be updated in an auction [ray] |
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
liquidationEngine
Address of the LiquidationEngine contract
function liquidationEngine() external view returns (ILiquidationEngine _liquidationEngine);
oracleRelayer
Address of the OracleRelayer contract
function oracleRelayer() external view returns (IOracleRelayer _oracleRelayer);
collateralType
The collateral type of the auctions created by this contract
function collateralType() external view returns (bytes32 _cType);
Returns
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
auctionsStarted
Total amount of collateral auctions created
function auctionsStarted() external view returns (uint256 _auctionsStarted);
getAuctionDiscount
Calculates the current discount of an auction
function getAuctionDiscount(uint256 _id) external view returns (uint256 _auctionDiscount);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auctionDiscount | uint256 | Current discount of the auction [wad %] |
getCollateralBought
Calculates the amount of collateral that will be bought with a given bid
function getCollateralBought(
uint256 _id,
uint256 _wad
) external view returns (uint256 _collateralBought, uint256 _adjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_wad | uint256 | Bid amount [wad] |
Returns
Name | Type | Description |
---|---|---|
_collateralBought | uint256 | Amount of collateral that will be bought [wad] |
_adjustedBid | uint256 | Adjusted bid amount [wad] |
buyCollateral
Buys collateral from an auction
function buyCollateral(uint256 _id, uint256 _wad) external returns (uint256 _boughtCollateral, uint256 _adjustedBid);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_wad | uint256 | Bid amount [wad] |
Returns
Name | Type | Description |
---|---|---|
_boughtCollateral | uint256 | Amount of collateral that was bought [wad] |
_adjustedBid | uint256 | Adjusted bid amount [wad] |
startAuction
Starts a new collateral auction
function startAuction(
address _forgoneCollateralReceiver,
address _auctionIncomeRecipient,
uint256 _amountToRaise,
uint256 _collateralToSell
) external returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_forgoneCollateralReceiver | address | Who receives leftover collateral that is not sold in the auction (usually the liquidated SAFE) |
_auctionIncomeRecipient | address | Who receives the coins raised by the auction (usually the AccountingEngine) |
_amountToRaise | uint256 | Total/max amount of coins to raise [rad] |
_collateralToSell | uint256 | How much collateral is sold in an auction [wad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the started auction |
terminateAuctionPrematurely
Terminates an auction prematurely
Transfers collateral and coins to the authorized caller address
function terminateAuctionPrematurely(uint256 _auctionId) external;
Parameters
Name | Type | Description |
---|---|---|
_auctionId | uint256 | Id of the auction |
Events
StartAuction
Emitted when a new auction is started
event StartAuction(
uint256 indexed _id,
address indexed _auctioneer,
uint256 _blockTimestamp,
uint256 _amountToSell,
uint256 _amountToRaise
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_auctioneer | address | Address who started the auction |
_blockTimestamp | uint256 | Time when the auction was started |
_amountToSell | uint256 | How much collateral is sold in an auction [wad] |
_amountToRaise | uint256 | Total/max amount of coins to raise [rad] |
BuyCollateral
Emitted when a bid is made in an auction
event BuyCollateral(
uint256 indexed _id, address _bidder, uint256 _blockTimestamp, uint256 _raisedAmount, uint256 _soldAmount
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_bidder | address | Who made the bid |
_blockTimestamp | uint256 | Time when the bid was made |
_raisedAmount | uint256 | Amount of coins raised in the bid [rad] |
_soldAmount | uint256 | Amount of collateral sold in the bid [wad] |
SettleAuction
Emitted when an auction is settled
An auction is settled when either all collateral is sold or all coins are raised
event SettleAuction(
uint256 indexed _id, uint256 _blockTimestamp, address _leftoverReceiver, uint256 _leftoverCollateral
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was settled |
_leftoverReceiver | address | Who receives leftover collateral that is not sold in the auction (usually the liquidated SAFE) |
_leftoverCollateral | uint256 | Amount of leftover collateral that is not sold in the auction [wad] |
TerminateAuctionPrematurely
Emitted when an auction is terminated prematurely
event TerminateAuctionPrematurely(
uint256 indexed _id, uint256 _blockTimestamp, address _leftoverReceiver, uint256 _leftoverCollateral
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was terminated |
_leftoverReceiver | address | Who receives leftover collateral that is not sold in the auction (usually the liquidated SAFE) |
_leftoverCollateral | uint256 | Amount of leftover collateral that is not sold in the auction [wad] |
Errors
CAH_InvalidRedemptionPriceProvided
Throws when the redemption price is invalid
error CAH_InvalidRedemptionPriceProvided();
CAH_CollateralOracleInvalidValue
Throws when the collateral price is invalid
error CAH_CollateralOracleInvalidValue();
CAH_NoCollateralForSale
Throws when trying to start an auction without collateral to sell
error CAH_NoCollateralForSale();
CAH_NothingToRaise
Throws when trying to start an auction without coins to raise
error CAH_NothingToRaise();
CAH_DustyAuction
Throws when trying to start an auction with a dusty amount to raise
error CAH_DustyAuction();
CAH_InexistentAuction
Throws when trying to bid in a nonexistent auction
error CAH_InexistentAuction();
CAH_InvalidBid
Throws when trying to bid an invalid amount
error CAH_InvalidBid();
CAH_NullBoughtAmount
Throws when the resulting bid amount is null
error CAH_NullBoughtAmount();
CAH_InvalidLeftToRaise
Throws when the resulting bid leftover to raise is invalid
error CAH_InvalidLeftToRaise();
Structs
CollateralAuctionHouseParams
struct CollateralAuctionHouseParams {
uint256 minimumBid;
uint256 minDiscount;
uint256 maxDiscount;
uint256 perSecondDiscountUpdateRate;
}
Auction
struct Auction {
uint256 amountToSell;
uint256 amountToRaise;
uint256 initialTimestamp;
address forgoneCollateralReceiver;
address auctionIncomeRecipient;
}
ICommonSurplusAuctionHouse
Functions
AUCTION_HOUSE_TYPE
Type of the auction house
function AUCTION_HOUSE_TYPE() external view returns (bytes32 _auctionHouseType);
Returns
Name | Type | Description |
---|---|---|
_auctionHouseType | bytes32 | Bytes32 representation of the auction house type |
auctions
Data of an auction
function auctions(uint256 _id) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
_auctions
Raw data of an auction
function _auctions(uint256 _id)
external
view
returns (uint256 _bidAmount, uint256 _amountToSell, address _highBidder, uint256 _bidExpiry, uint256 _auctionDeadline);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_bidAmount | uint256 | How many system coins are offered for the protocol tokens [rad] |
_amountToSell | uint256 | How protocol tokens are sold to buy the surplus system coins [wad] |
_highBidder | address | Who the high bidder is |
_bidExpiry | uint256 | When the latest bid expires and the auction can be settled [timestamp] |
_auctionDeadline | uint256 | Hard deadline for the auction after which no more bids can be placed [timestamp] |
auctionsStarted
Total amount of surplus auctions created
function auctionsStarted() external view returns (uint256 _auctionsStarted);
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
protocolToken
Address of the ProtocolToken contract
function protocolToken() external view returns (IProtocolToken _protocolToken);
startAuction
Start a new surplus auction
function startAuction(uint256 _amountToSell, uint256 _initialBid) external returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_amountToSell | uint256 | Total amount of system coins to sell [rad] |
_initialBid | uint256 | Initial protocol token bid [wad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the started auction |
restartAuction
Restart an auction if no bids were submitted for it
function restartAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to restart |
increaseBidSize
Submit a higher protocol token bid for the same amount of system coins
function increaseBidSize(uint256 _id, uint256 _bid) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction you want to submit the bid for |
_bid | uint256 | New bid submitted [wad] |
settleAuction
Settle/finish an auction
function settleAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to settle |
Events
StartAuction
Emitted when a new auction is started
event StartAuction(
uint256 indexed _id,
address indexed _auctioneer,
uint256 _blockTimestamp,
uint256 _amountToSell,
uint256 _amountToRaise,
uint256 _auctionDeadline
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_auctioneer | address | Address who started the auction |
_blockTimestamp | uint256 | Time when the auction was started |
_amountToSell | uint256 | How many protocol tokens are initially bidded [wad] |
_amountToRaise | uint256 | Amount of system coins to raise [rad] |
_auctionDeadline | uint256 | Time when the auction expires |
RestartAuction
Emitted when an auction is restarted
event RestartAuction(uint256 indexed _id, uint256 _blockTimestamp, uint256 _auctionDeadline);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was restarted |
_auctionDeadline | uint256 | New time when the auction expires |
IncreaseBidSize
Emitted when a bid is made in an auction
event IncreaseBidSize(
uint256 indexed _id,
address _bidder,
uint256 _blockTimestamp,
uint256 _raisedAmount,
uint256 _soldAmount,
uint256 _bidExpiry
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_bidder | address | Who made the bid |
_blockTimestamp | uint256 | Time when the bid was made |
_raisedAmount | uint256 | Amount of system coins raised in the bid [rad] |
_soldAmount | uint256 | Amount of protocol tokens offered to buy in the bid [wad] |
_bidExpiry | uint256 | Time when the bid expires |
SettleAuction
Emitted when an auction is settled
event SettleAuction(uint256 indexed _id, uint256 _blockTimestamp, address _highBidder, uint256 _raisedAmount);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was settled |
_highBidder | address | Who won the auction |
_raisedAmount | uint256 | Amount of system coins raised in the auction [rad] |
Errors
SAH_AuctionNeverStarted
Throws when trying to bid in an auction that hasn't started yet
error SAH_AuctionNeverStarted();
SAH_AuctionNotFinished
Throws when trying to settle an auction that hasn't finished yet
error SAH_AuctionNotFinished();
SAH_AuctionAlreadyExpired
Throws when trying to bid in an auction that has already expired
error SAH_AuctionAlreadyExpired();
SAH_BidAlreadyExpired
Throws when trying to bid in an auction that has an expired bid
error SAH_BidAlreadyExpired();
SAH_BidAlreadyPlaced
Throws when trying to restart an auction that has an active bid
error SAH_BidAlreadyPlaced();
SAH_AmountsNotMatching
Throws when trying to place a bid that differs from the amount to raise
error SAH_AmountsNotMatching();
SAH_BidNotHigher
Throws when trying to place a bid that is not higher than the previous one
error SAH_BidNotHigher();
SAH_InsufficientIncrease
Throws when trying to place a bid that is not higher than the previous one by the minimum increase
error SAH_InsufficientIncrease();
SAH_HighBidderNotSet
Throws when trying to prematurely terminate an auction that has no bids
error SAH_HighBidderNotSet();
Structs
Auction
struct Auction {
uint256 bidAmount;
uint256 amountToSell;
address highBidder;
uint256 bidExpiry;
uint256 auctionDeadline;
}
IDebtAuctionHouse
Inherits: IAuthorizable, IDisableable, IModifiable
Functions
AUCTION_HOUSE_TYPE
Type of the auction house
function AUCTION_HOUSE_TYPE() external view returns (bytes32 _auctionHouseType);
Returns
Name | Type | Description |
---|---|---|
_auctionHouseType | bytes32 | Bytes32 representation of the auction house type |
auctions
Data of an auction
function auctions(uint256 _id) external view returns (Auction memory _auction);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_auction | Auction | Auction data struct |
_auctions
Unpacked data of an auction
function _auctions(uint256 _id)
external
view
returns (uint256 _bidAmount, uint256 _amountToSell, address _highBidder, uint256 _bidExpiry, uint256 _auctionDeadline);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Returns
Name | Type | Description |
---|---|---|
_bidAmount | uint256 | How much protocol tokens are to be minted [wad] |
_amountToSell | uint256 | How many system coins are raised [rad] |
_highBidder | address | Address of the highest bidder |
_bidExpiry | uint256 | Time when the latest bid expires and the auction can be settled |
_auctionDeadline | uint256 | Time when the auction expires |
auctionsStarted
Total amount of debt auctions created
function auctionsStarted() external view returns (uint256 _auctionsStarted);
activeDebtAuctions
Total amount of simultaneous active debt auctions
function activeDebtAuctions() external view returns (uint256 _activeDebtAuctions);
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
protocolToken
Address of the ProtocolToken contract
function protocolToken() external view returns (IProtocolToken _protocolToken);
accountingEngine
Address of the AccountingEngine contract
function accountingEngine() external view returns (address _accountingEngine);
params
Getter for the contract parameters struct
function params() external view returns (DebtAuctionHouseParams memory _dahParams);
Returns
Name | Type | Description |
---|---|---|
_dahParams | DebtAuctionHouseParams | Auction house parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (uint256 _bidDecrease, uint256 _amountSoldIncrease, uint256 _bidDuration, uint256 _totalAuctionLength);
Returns
Name | Type | Description |
---|---|---|
_bidDecrease | uint256 | Minimum bid increase compared to the last bid in order to take the new one in consideration [wad %] |
_amountSoldIncrease | uint256 | Increase in protocol tokens sold in case an auction is restarted [wad %] |
_bidDuration | uint256 | How long the auction lasts after a new bid is submitted [seconds] |
_totalAuctionLength | uint256 | Total length of the auction [seconds] |
startAuction
Start a new debt auction
function startAuction(
address _incomeReceiver,
uint256 _amountToSell,
uint256 _initialBid
) external returns (uint256 _id);
Parameters
Name | Type | Description |
---|---|---|
_incomeReceiver | address | Who receives the auction proceeds |
_amountToSell | uint256 | Initial amount of protocol tokens to be minted [wad] |
_initialBid | uint256 | Amount of debt to be sold [rad] |
Returns
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
restartAuction
Restart an auction if no bids were placed
An auction can be restarted if the auction expired with no bids
function restartAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
decreaseSoldAmount
Decrease the protocol token amount you're willing to receive in exchange for providing the same amount of system coins being raised by the auction
function decreaseSoldAmount(uint256 _id, uint256 _amountToBuy) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction for which you want to submit a new bid |
_amountToBuy | uint256 | Amount of protocol tokens to buy (must be smaller than the previous proposed amount) [wad] |
settleAuction
Settle an auction
Can only be called after the auction expired with a winning bid
function settleAuction(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
terminateAuctionPrematurely
Terminate an auction prematurely
Can only be called after the contract is disabled
The method creates an unbacked debt position in the AccountingEngine for the remaining debt
function terminateAuctionPrematurely(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
Events
StartAuction
Emitted when a new auction is started
event StartAuction(
uint256 indexed _id,
address indexed _auctioneer,
uint256 _blockTimestamp,
uint256 _amountToSell,
uint256 _amountToRaise,
uint256 _auctionDeadline
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_auctioneer | address | Address who started the auction |
_blockTimestamp | uint256 | Time when the auction was started |
_amountToSell | uint256 | How much protocol tokens are initially offered [wad] |
_amountToRaise | uint256 | Amount of system coins to raise [rad] |
_auctionDeadline | uint256 | Time when the auction expires |
RestartAuction
Emitted when an auction is restarted
event RestartAuction(uint256 indexed _id, uint256 _blockTimestamp, uint256 _auctionDeadline);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was restarted |
_auctionDeadline | uint256 | New time when the auction expires |
DecreaseSoldAmount
Emitted when a bid is made in an auction
event DecreaseSoldAmount(
uint256 indexed _id,
address _bidder,
uint256 _blockTimestamp,
uint256 _raisedAmount,
uint256 _soldAmount,
uint256 _bidExpiry
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_bidder | address | Who made the bid |
_blockTimestamp | uint256 | Time when the bid was made |
_raisedAmount | uint256 | Amount of system coins raised in the bid [rad] |
_soldAmount | uint256 | Amount of protocol tokens offered to buy in the bid [wad] |
_bidExpiry | uint256 | Time when the bid expires |
SettleAuction
Emitted when an auction is settled
An auction is settled after the winning bid or the auction expire
event SettleAuction(uint256 indexed _id, uint256 _blockTimestamp, address _highBidder, uint256 _raisedAmount);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was settled |
_highBidder | address | Who won the auction |
_raisedAmount | uint256 | Amount of system coins raised in the auction [rad] |
TerminateAuctionPrematurely
Emitted when an auction is terminated prematurely
event TerminateAuctionPrematurely(
uint256 indexed _id, uint256 _blockTimestamp, address _highBidder, uint256 _raisedAmount
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was terminated |
_highBidder | address | Who won the auction |
_raisedAmount | uint256 | Amount of system coins raised in the auction [rad] |
Errors
DAH_AuctionNeverStarted
Throws when trying to restart an auction that never started
error DAH_AuctionNeverStarted();
DAH_AuctionNotFinished
Throws when trying to restart an auction that is still active
error DAH_AuctionNotFinished();
DAH_BidAlreadyPlaced
Throws when trying to restart an auction that already has a winning bid
error DAH_BidAlreadyPlaced();
DAH_AuctionAlreadyExpired
Throws when trying to bid in an auction that already has expired
error DAH_AuctionAlreadyExpired();
DAH_BidAlreadyExpired
Throws when trying to bid in an auction that has a bid already expired
error DAH_BidAlreadyExpired();
DAH_NotMatchingBid
Throws when trying to bid in an auction with a bid that doesn't match the current bid
error DAH_NotMatchingBid();
DAH_AmountBoughtNotLower
Throws when trying to place a bid that is not lower than the current bid
error DAH_AmountBoughtNotLower();
DAH_InsufficientDecrease
Throws when trying to place a bid not lower than the current bid threshold
error DAH_InsufficientDecrease();
DAH_HighBidderNotSet
Throws when prematurely terminating an auction that has no bids
error DAH_HighBidderNotSet();
Structs
Auction
struct Auction {
uint256 bidAmount;
uint256 amountToSell;
address highBidder;
uint256 bidExpiry;
uint256 auctionDeadline;
}
DebtAuctionHouseParams
struct DebtAuctionHouseParams {
uint256 bidDecrease;
uint256 amountSoldIncrease;
uint256 bidDuration;
uint256 totalAuctionLength;
}
ILiquidationEngine
Inherits: IAuthorizable, IDisableable, IModifiable, IModifiablePerCollateral
Functions
safeEngine
The SAFEEngine is used to query the state of the SAFEs, confiscate the collateral and transfer the debt
function safeEngine() external view returns (ISAFEEngine _safeEngine);
Returns
Name | Type | Description |
---|---|---|
_safeEngine | ISAFEEngine | Address of the contract that handles the state of the SAFEs |
accountingEngine
The AccountingEngine is used to push the debt into the system, and set as the first bidder on the collateral auctions
function accountingEngine() external view returns (IAccountingEngine _accountingEngine);
Returns
Name | Type | Description |
---|---|---|
_accountingEngine | IAccountingEngine | Address of the AccountingEngine |
params
Getter for the contract parameters struct
function params() external view returns (LiquidationEngineParams memory _liqEngineParams);
Returns
Name | Type | Description |
---|---|---|
_liqEngineParams | LiquidationEngineParams | LiquidationEngine parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _onAuctionSystemCoinLimit, uint256 _saviourGasLimit);
Returns
Name | Type | Description |
---|---|---|
_onAuctionSystemCoinLimit | uint256 | Max amount of system coins to be auctioned at the same time [rad] |
_saviourGasLimit | uint256 |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (LiquidationEngineCollateralParams memory _liqEngineCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_liqEngineCParams | LiquidationEngineCollateralParams | LiquidationEngine collateral parameters struct |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType)
external
view
returns (address _collateralAuctionHouse, uint256 _liquidationPenalty, uint256 _liquidationQuantity);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_collateralAuctionHouse | address | Address of the collateral auction house handling liquidations |
_liquidationPenalty | uint256 | Penalty applied to every liquidation involving this collateral type [wad%] |
_liquidationQuantity | uint256 | Max amount of system coins to request in one auction for this collateral type [rad] |
getLimitAdjustedDebtToCover
The limit adjusted debt to cover
function getLimitAdjustedDebtToCover(bytes32 _cType, address _safe) external view returns (uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
Returns
Name | Type | Description |
---|---|---|
_wad | uint256 | The limit adjusted debt to cover |
currentOnAuctionSystemCoins
Total amount of system coins currently being auctioned
function currentOnAuctionSystemCoins() external view returns (uint256 _currentOnAuctionSystemCoins);
safeSaviours
Allowed contracts that can be chosen to save SAFEs from liquidation
function safeSaviours(address _saviour) external view returns (bool _canSave);
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | The SAFE saviour contract to check |
Returns
Name | Type | Description |
---|---|---|
_canSave | bool | Whether the contract can save SAFEs or not |
chosenSAFESaviour
Saviour contract chosen for each SAFE by its owner
function chosenSAFESaviour(bytes32 _cType, address _safe) external view returns (address _saviour);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
Returns
Name | Type | Description |
---|---|---|
_saviour | address | The SAFE's saviour contract (address(0) if none) |
removeCoinsFromAuction
Remove debt that was being auctioned
Usually called by CollateralAuctionHouse when an auction is settled
function removeCoinsFromAuction(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | The amount of debt in RAD to withdraw from currentOnAuctionSystemCoins |
liquidateSAFE
Liquidate a SAFE
A SAFE can be liquidated if the accumulated debt plus the liquidation penalty is higher than the collateral value
function liquidateSAFE(bytes32 _cType, address _safe) external returns (uint256 _auctionId);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
Returns
Name | Type | Description |
---|---|---|
_auctionId | uint256 | The auction id of the collateral auction |
protectSAFE
Choose a saviour contract for your SAFE
function protectSAFE(bytes32 _cType, address _safe, address _saviour) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | The SAFE's collateral type |
_safe | address | The SAFE's address |
_saviour | address | The chosen saviour |
connectSAFESaviour
Authed function to add contracts that can save SAFEs from liquidation
function connectSAFESaviour(address _saviour) external;
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract to be whitelisted |
disconnectSAFESaviour
Authed function to remove contracts that can save SAFEs from liquidation
function disconnectSAFESaviour(address _saviour) external;
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract to be removed |
Events
ConnectSAFESaviour
Emitted when a SAFE saviour contract is added to the allowlist
event ConnectSAFESaviour(address _saviour);
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract being allowlisted |
DisconnectSAFESaviour
Emitted when a SAFE saviour contract is removed from the allowlist
event DisconnectSAFESaviour(address _saviour);
Parameters
Name | Type | Description |
---|---|---|
_saviour | address | SAFE saviour contract being removed from the allowlist |
UpdateCurrentOnAuctionSystemCoins
Emitted when the current on auction system coins counter is updated
event UpdateCurrentOnAuctionSystemCoins(uint256 _currentOnAuctionSystemCoins);
Parameters
Name | Type | Description |
---|---|---|
_currentOnAuctionSystemCoins | uint256 | New value of the current on auction system coins counter |
Liquidate
Emitted when a SAFE is liquidated
event Liquidate(
bytes32 indexed _cType,
address indexed _safe,
uint256 _collateralAmount,
uint256 _debtAmount,
uint256 _amountToRaise,
address _collateralAuctioneer,
uint256 _auctionId
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE being liquidated |
_collateralAmount | uint256 | Amount of collateral being confiscated [wad] |
_debtAmount | uint256 | Amount of debt being transferred [wad] |
_amountToRaise | uint256 | Amount of system coins to raise in the collateral auction [rad] |
_collateralAuctioneer | address | Address of the collateral auctioneer contract handling the collateral auction |
_auctionId | uint256 | Id of the collateral auction |
SaveSAFE
Emitted when a SAFE is saved from being liquidated by a SAFE saviour contract
event SaveSAFE(bytes32 indexed _cType, address indexed _safe, uint256 _collateralAddedOrDebtRepaid);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE being saved |
_collateralAddedOrDebtRepaid | uint256 | Amount of collateral being added or debt repaid [wad] |
FailedSAFESave
Emitted when a SAFE saviour action is unsuccessful
event FailedSAFESave(bytes _failReason);
Parameters
Name | Type | Description |
---|---|---|
_failReason | bytes | Reason why the SAFE saviour action failed |
ProtectSAFE
Emitted when a SAFE saviour contract is chosen for a SAFE
event ProtectSAFE(bytes32 indexed _cType, address indexed _safe, address _saviour);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE being saved |
_saviour | address | Address of the SAFE saviour contract chosen |
Errors
LiqEng_SaviourNotOk
Throws when trying to add a reverting SAFE saviour to the allowlist
error LiqEng_SaviourNotOk();
LiqEng_InvalidAmounts
Throws when trying to add an invalid SAFE saviour to the allowlist
error LiqEng_InvalidAmounts();
LiqEng_CannotModifySAFE
Throws when trying to choose a SAFE saviour for a SAFE without the proper authorization
error LiqEng_CannotModifySAFE();
LiqEng_SaviourNotAuthorized
Throws when trying to choose a SAFE saviour that is not on the allowlist
error LiqEng_SaviourNotAuthorized();
LiqEng_SAFENotUnsafe
Throws when trying to liquidate a SAFE that is not unsafe
error LiqEng_SAFENotUnsafe();
LiqEng_LiquidationLimitHit
Throws when trying to simultaneously liquidate more debt than the limit allows
error LiqEng_LiquidationLimitHit();
LiqEng_InvalidSAFESaviourOperation
Throws when SAFE saviour action is invalid during a liquidation
error LiqEng_InvalidSAFESaviourOperation();
LiqEng_NullAuction
Throws when trying to liquidate a SAFE with a null amount of debt
error LiqEng_NullAuction();
LiqEng_NullCollateralToSell
Throws when trying to liquidate a SAFE with a null amount of collateral to sell
error LiqEng_NullCollateralToSell();
LiqEng_OnlyLiqEng
Throws when trying to call a function only the liquidator is allowed to call
error LiqEng_OnlyLiqEng();
Structs
LiquidationEngineParams
struct LiquidationEngineParams {
uint256 onAuctionSystemCoinLimit;
uint256 saviourGasLimit;
}
LiquidationEngineCollateralParams
struct LiquidationEngineCollateralParams {
address collateralAuctionHouse;
uint256 liquidationPenalty;
uint256 liquidationQuantity;
}
IOracleRelayer
Inherits: IAuthorizable, IDisableable, IModifiable, IModifiablePerCollateral
Functions
safeEngine
The SAFEEngine is called to update the price of the collateral in the system
function safeEngine() external view returns (ISAFEEngine _safeEngine);
Returns
Name | Type | Description |
---|---|---|
_safeEngine | ISAFEEngine | Address of the contract that handles the state of the SAFEs |
systemCoinOracle
The oracle used to fetch the system coin market price
function systemCoinOracle() external view returns (IBaseOracle _systemCoinOracle);
Returns
Name | Type | Description |
---|---|---|
_systemCoinOracle | IBaseOracle | Address of the contract that provides the system coin price |
params
Getter for the contract parameters struct
function params() external view returns (OracleRelayerParams memory _oracleRelayerParams);
Returns
Name | Type | Description |
---|---|---|
_oracleRelayerParams | OracleRelayerParams | An OracleRelayerParams struct |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _redemptionRateUpperBound, uint256 _redemptionRateLowerBound);
Returns
Name | Type | Description |
---|---|---|
_redemptionRateUpperBound | uint256 | Upper bound for the per-second redemption rate [ray] |
_redemptionRateLowerBound | uint256 | Lower bound for the per-second redemption rate [ray] |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (OracleRelayerCollateralParams memory _oracleRelayerCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_oracleRelayerCParams | OracleRelayerCollateralParams | An OracleRelayerCollateralParams struct |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType)
external
view
returns (IBaseOracle _oracle, uint256 _safetyCRatio, uint256 _liquidationCRatio);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_oracle | IBaseOracle | Usually a DelayedOracle that enforces delays to fresh price feeds |
_safetyCRatio | uint256 | CRatio used to compute the 'safePrice' - the price used when generating debt in SAFEEngine [ray] |
_liquidationCRatio | uint256 | CRatio used to compute the 'liquidationPrice' - the price used when liquidating SAFEs [ray] |
calcRedemptionPrice
View method to fetch the current redemption price
function calcRedemptionPrice() external view returns (uint256 _redemptionPrice);
Returns
Name | Type | Description |
---|---|---|
_redemptionPrice | uint256 | The current calculated redemption price [ray] |
marketPrice
The current system coin market price
function marketPrice() external view returns (uint256 _marketPrice);
Returns
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The current system coin market price [ray] |
redemptionRate
The redemption rate is the rate at which the redemption price changes over time
By changing the redemption rate, it changes the incentives of the system users
The redemption rate is a per-second rate [ray]
function redemptionRate() external view returns (uint256 _redemptionRate);
Returns
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The current updated redemption rate [ray] |
redemptionPriceUpdateTime
Last time when the redemption price was changed
Used to calculate the current redemption price
function redemptionPriceUpdateTime() external view returns (uint256 _redemptionPriceUpdateTime);
Returns
Name | Type | Description |
---|---|---|
_redemptionPriceUpdateTime | uint256 | The last time when the redemption price was changed [unix timestamp] |
redemptionPrice
Fetch the latest redemption price by first updating it
function redemptionPrice() external returns (uint256 _updatedPrice);
Returns
Name | Type | Description |
---|---|---|
_updatedPrice | uint256 | The newly updated redemption price [ray] |
updateCollateralPrice
Update the collateral price inside the system (inside SAFEEngine)
Usually called by a keeper, incentivized by the system to keep the prices up to date
function updateCollateralPrice(bytes32 _cType) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
updateRedemptionRate
Update the system redemption rate, the rate at which the redemption price changes over time
Usually called by the PIDRateSetter
function updateRedemptionRate(uint256 _redemptionRate) external;
Parameters
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The newly calculated redemption rate [ray] |
Events
UpdateRedemptionPrice
Emitted when the redemption price is updated
event UpdateRedemptionPrice(uint256 _redemptionPrice);
Parameters
Name | Type | Description |
---|---|---|
_redemptionPrice | uint256 | The new redemption price [ray] |
UpdateCollateralPrice
Emitted when a collateral type price is updated
event UpdateCollateralPrice(
bytes32 indexed _cType, uint256 _priceFeedValue, uint256 _safetyPrice, uint256 _liquidationPrice
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_priceFeedValue | uint256 | The new collateral price [wad] |
_safetyPrice | uint256 | The new safety price [ray] |
_liquidationPrice | uint256 | The new liquidation price [ray] |
UpdateRedemptionRate
Emitted when the redemption rate is updated
event UpdateRedemptionRate(uint256 _redemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The new redemption rate [ray] |
Errors
OracleRelayer_RedemptionPriceNotUpdated
Throws if the redemption price is not updated when updating the rate
error OracleRelayer_RedemptionPriceNotUpdated();
OracleRelayer_CollateralTypeAlreadyInitialized
Throws when trying to initialize a collateral type that is already initialized
error OracleRelayer_CollateralTypeAlreadyInitialized();
Structs
OracleRelayerParams
struct OracleRelayerParams {
uint256 redemptionRateUpperBound;
uint256 redemptionRateLowerBound;
}
OracleRelayerCollateralParams
struct OracleRelayerCollateralParams {
IBaseOracle oracle;
uint256 safetyCRatio;
uint256 liquidationCRatio;
}
IPIDController
Inherits: IAuthorizable, IModifiable
Functions
seedProposer
Returns the address allowed to call computeRate method
function seedProposer() external view returns (address _seedProposer);
params
Getter for the contract parameters struct
function params() external view returns (PIDControllerParams memory _pidParams);
Returns
Name | Type | Description |
---|---|---|
_pidParams | PIDControllerParams | The PID controller parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (
uint256 _integralPeriodSize,
uint256 _perSecondCumulativeLeak,
uint256 _noiseBarrier,
uint256 _feedbackOutputUpperBound,
int256 _feedbackOutputLowerBound
);
Returns
Name | Type | Description |
---|---|---|
_integralPeriodSize | uint256 | The minimum delay between two computeRate calls |
_perSecondCumulativeLeak | uint256 | The per second leak applied to priceDeviationCumulative before the latest deviation is added [ray] |
_noiseBarrier | uint256 | The minimum percentage deviation from the redemption price that allows the contract to calculate a non null redemption rate [wad] |
_feedbackOutputUpperBound | uint256 | The maximum value allowed for the redemption rate [ray] |
_feedbackOutputLowerBound | int256 | The minimum value allowed for the redemption rate [ray] |
deviationObservation
Returns the last deviation observation, containing latest timestamp, proportional and integral terms
function deviationObservation() external view returns (DeviationObservation memory __deviationObservation);
Returns
Name | Type | Description |
---|---|---|
__deviationObservation | DeviationObservation | The last deviation observation struct |
_deviationObservation
Raw data about the last deviation observation
function _deviationObservation() external view returns (uint256 _timestamp, int256 _proportional, int256 _integral);
Returns
Name | Type | Description |
---|---|---|
_timestamp | uint256 | The timestamp when this observation was stored |
_proportional | int256 | The proportional term stored in this observation |
_integral | int256 | The integral term stored in this observation |
controllerGains
Returns the Kp and Ki values used in this calculator
The values are expressed in WAD, Kp stands for proportional and Ki for integral terms
function controllerGains() external view returns (ControllerGains memory _cGains);
_controllerGains
Raw data about the Kp and Ki values used in this calculator
function _controllerGains() external view returns (int256 _kp, int256 _ki);
Returns
Name | Type | Description |
---|---|---|
_kp | int256 | This value is multiplied with the proportional term |
_ki | int256 | This value is multiplied with priceDeviationCumulative |
getBoundedRedemptionRate
Return a redemption rate bounded by feedbackOutputLowerBound and feedbackOutputUpperBound as well as the timeline over which that rate will take effect
function getBoundedRedemptionRate(int256 _piOutput) external view returns (uint256 _redemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_piOutput | int256 | The raw redemption rate computed from the proportional and integral terms |
Returns
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The bounded redemption rate |
computeRate
Compute a new redemption rate
function computeRate(uint256 _marketPrice, uint256 _redemptionPrice) external returns (uint256 _redemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The system coin market price |
_redemptionPrice | uint256 | The system coin redemption price |
Returns
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The computed redemption rate |
getGainAdjustedPIOutput
Apply Kp to the proportional term and Ki to the integral term (by multiplication) and then sum P and I
function getGainAdjustedPIOutput(
int256 _proportionalTerm,
int256 _integralTerm
) external view returns (int256 _piOutput);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term |
_integralTerm | int256 | The integral term |
Returns
Name | Type | Description |
---|---|---|
_piOutput | int256 | The sum of P and I |
getGainAdjustedTerms
Independently return and calculate P * Kp and I * Ki
function getGainAdjustedTerms(
int256 _proportionalTerm,
int256 _integralTerm
) external view returns (int256 _proportionalGain, int256 _integralGain);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term |
_integralTerm | int256 | The integral term |
Returns
Name | Type | Description |
---|---|---|
_proportionalGain | int256 | The proportional gain |
_integralGain | int256 | The integral gain |
getNextDeviationCumulative
Compute a new priceDeviationCumulative (integral term)
function getNextDeviationCumulative(
int256 _proportionalTerm,
uint256 _accumulatedLeak
) external returns (int256 _priceDeviationCumulative, int256 _timeAdjustedDeviation);
Parameters
Name | Type | Description |
---|---|---|
_proportionalTerm | int256 | The proportional term (redemptionPrice - marketPrice) |
_accumulatedLeak | uint256 | The total leak applied to priceDeviationCumulative before it is summed with the new time adjusted deviation |
Returns
Name | Type | Description |
---|---|---|
_priceDeviationCumulative | int256 | The new priceDeviationCumulative |
_timeAdjustedDeviation | int256 | The new time adjusted deviation |
breaksNoiseBarrier
Returns whether the P + I sum exceeds the noise barrier
function breaksNoiseBarrier(uint256 _piSum, uint256 _redemptionPrice) external view returns (bool _breaksNb);
Parameters
Name | Type | Description |
---|---|---|
_piSum | uint256 | Represents a sum between P + I |
_redemptionPrice | uint256 | The system coin redemption price |
Returns
Name | Type | Description |
---|---|---|
_breaksNb | bool | Whether the P + I sum exceeds the noise barrier |
getNextRedemptionRate
Compute and return the upcoming redemption rate
function getNextRedemptionRate(
uint256 _marketPrice,
uint256 _redemptionPrice,
uint256 _accumulatedLeak
) external view returns (uint256 _redemptionRate, int256 _proportionalTerm, int256 _integralTerm);
Parameters
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | The system coin market price |
_redemptionPrice | uint256 | The system coin redemption price |
_accumulatedLeak | uint256 | The total leak applied to priceDeviationCumulative before it is summed with the proportionalTerm |
Returns
Name | Type | Description |
---|---|---|
_redemptionRate | uint256 | The upcoming redemption rate |
_proportionalTerm | int256 | The upcoming proportional term |
_integralTerm | int256 | The upcoming integral term |
timeSinceLastUpdate
Returns the time elapsed since the last computeRate call
function timeSinceLastUpdate() external view returns (uint256 _timeSinceLastValue);
Events
UpdateDeviation
Emitted when the state of the controller is updated
event UpdateDeviation(int256 _proportionalDeviation, int256 _integralDeviation, int256 _deltaIntegralDeviation);
Parameters
Name | Type | Description |
---|---|---|
_proportionalDeviation | int256 | The new proportional term |
_integralDeviation | int256 | The new integral term |
_deltaIntegralDeviation | int256 | The delta between the new and the previous integral term |
Errors
PIDController_OnlySeedProposer
Throws if the caller of updateRate
is not the seed proposer
error PIDController_OnlySeedProposer();
PIDController_ComputeRateCooldown
Throws if the call to updateRate
is too soon since last update
error PIDController_ComputeRateCooldown();
PIDController_CannotSetPriceDeviationCumulative
Throws when trying to set the integral term with the integral gain set on
error PIDController_CannotSetPriceDeviationCumulative();
Structs
PIDControllerParams
struct PIDControllerParams {
uint256 integralPeriodSize;
uint256 perSecondCumulativeLeak;
uint256 noiseBarrier;
uint256 feedbackOutputUpperBound;
int256 feedbackOutputLowerBound;
}
DeviationObservation
struct DeviationObservation {
uint256 timestamp;
int256 proportional;
int256 integral;
}
ControllerGains
struct ControllerGains {
int256 kp;
int256 ki;
}
IPIDRateSetter
Inherits: IAuthorizable, IModifiable
Functions
oracleRelayer
The oracle relayer where the redemption price and rate are stored
function oracleRelayer() external view returns (IOracleRelayer _oracleRelayer);
pidCalculator
The PID calculator used to compute the redemption rate
function pidCalculator() external view returns (IPIDController _pidCalculator);
params
Getter for the contract parameters struct
function params() external view returns (PIDRateSetterParams memory _pidRateSetterParams);
Returns
Name | Type | Description |
---|---|---|
_pidRateSetterParams | PIDRateSetterParams | PIDRateSetter parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _updateRateDelay);
Returns
Name | Type | Description |
---|---|---|
_updateRateDelay | uint256 | Enforced gap between calls |
lastUpdateTime
The timestamp of the last update
function lastUpdateTime() external view returns (uint256 _lastUpdateTime);
updateRate
Compute and set a new redemption rate
function updateRate() external;
Events
UpdateRedemptionRate
Emitted when the redemption rate is updated
event UpdateRedemptionRate(uint256 _marketPrice, uint256 _redemptionPrice, uint256 _redemptionRate);
Parameters
Name | Type | Description |
---|---|---|
_marketPrice | uint256 | Computed price of the system coin |
_redemptionPrice | uint256 | Redemption price of the system coin |
_redemptionRate | uint256 | Resulting new redemption rate |
Errors
PIDRateSetter_InvalidPriceFeed
Throws if the market price feed returns an invalid value
error PIDRateSetter_InvalidPriceFeed();
PIDRateSetter_RateSetterCooldown
Throws if the call to updateRate
is too soon since last update
error PIDRateSetter_RateSetterCooldown();
Structs
PIDRateSetterParams
struct PIDRateSetterParams {
uint256 updateRateDelay;
}
ISAFEEngine
Inherits: IAuthorizable, IDisableable, IModifiable, IModifiablePerCollateral
Functions
params
Getter for the contract parameters struct
function params() external view returns (SAFEEngineParams memory _safeEngineParams);
Returns
Name | Type | Description |
---|---|---|
_safeEngineParams | SAFEEngineParams | The active SAFEEngineParams |
_params
Getter for the unpacked contract parameters struct
function _params() external view returns (uint256 _safeDebtCeiling, uint256 _globalDebtCeiling);
Returns
Name | Type | Description |
---|---|---|
_safeDebtCeiling | uint256 | Total amount of debt that a single safe can generate [wad] |
_globalDebtCeiling | uint256 | Maximum amount of debt that can be issued [rad] |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (SAFEEngineCollateralParams memory _safeEngineCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_safeEngineCParams | SAFEEngineCollateralParams | SAFEEngineCollateralParams for the collateral type |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType) external view returns (uint256 _debtCeiling, uint256 _debtFloor);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_debtCeiling | uint256 | Maximum amount of debt that can be generated with this collateral type |
_debtFloor | uint256 | Minimum amount of debt that must be generated by a SAFE using this collateral |
cData
Getter for the collateral data struct
function cData(bytes32 _cType) external view returns (SAFEEngineCollateralData memory _safeEngineCData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_safeEngineCData | SAFEEngineCollateralData | SAFEEngineCollateralData for the collateral type |
_cData
Getter for the unpacked collateral data struct
function _cData(bytes32 _cType)
external
view
returns (
uint256 _debtAmount,
uint256 _lockedAmount,
uint256 _accumulatedRate,
uint256 _safetyPrice,
uint256 _liquidationPrice
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_debtAmount | uint256 | Total amount of debt issued by a collateral type [wad] |
_lockedAmount | uint256 | Total amount of collateral locked in all SAFEs of the collateral type [wad] |
_accumulatedRate | uint256 | Accumulated rate of a collateral type [ray] |
_safetyPrice | uint256 | Floor price at which a SAFE is allowed to generate debt [ray] |
_liquidationPrice | uint256 | Price at which a SAFE gets liquidated [ray] |
safes
Data about each SAFE
function safes(bytes32 _cType, address _safeAddress) external view returns (SAFE memory _safeData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safeAddress | address | Address of the SAFE |
Returns
Name | Type | Description |
---|---|---|
_safeData | SAFE | SAFE data for the specified collateral type of the specified safe. |
_safes
Unpacked data about each SAFE
function _safes(
bytes32 _cType,
address _safeAddress
) external view returns (uint256 _lockedCollateral, uint256 _generatedDebt);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safeAddress | address | Address of the SAFE |
Returns
Name | Type | Description |
---|---|---|
_lockedCollateral | uint256 | Total amount of collateral locked in a SAFE [wad] |
_generatedDebt | uint256 | Total amount of debt generated by a SAFE [wad] |
safeRights
Who can transfer collateral & debt in/out of a SAFE
function safeRights(address _caller, address _account) external view returns (bool _safeRights);
Parameters
Name | Type | Description |
---|---|---|
_caller | address | Address to check for SAFE permissions for |
_account | address | Account to check if caller has permissions for |
Returns
Name | Type | Description |
---|---|---|
_safeRights | bool | Boolean representation of the SAFE rights (0/1) |
tokenCollateral
Balance of each collateral type
function tokenCollateral(bytes32 _cType, address _account) external view returns (uint256 _collateralBalance);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type to check balance for |
_account | address | Account to check balance for |
Returns
Name | Type | Description |
---|---|---|
_collateralBalance | uint256 | Collateral balance of the account [wad] |
coinBalance
Internal balance of system coins held by an account
function coinBalance(address _account) external view returns (uint256 _balance);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to check balance for |
Returns
Name | Type | Description |
---|---|---|
_balance | uint256 | Internal coin balance of the account [rad] |
debtBalance
Amount of debt held by an account
function debtBalance(address _account) external view returns (uint256 _debtBalance);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to check balance for |
Returns
Name | Type | Description |
---|---|---|
_debtBalance | uint256 | Debt balance of the account [rad] |
globalDebt
Total amount of debt (coins) currently issued
function globalDebt() external returns (uint256 _globalDebt);
Returns
Name | Type | Description |
---|---|---|
_globalDebt | uint256 | Global debt [rad] |
globalUnbackedDebt
'Bad' debt that's not covered by collateral
function globalUnbackedDebt() external view returns (uint256 _globalUnbackedDebt);
Returns
Name | Type | Description |
---|---|---|
_globalUnbackedDebt | uint256 | Global unbacked debt [rad] |
transferCollateral
Transfer collateral between accounts
function transferCollateral(bytes32 _cType, address _source, address _destination, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type transferred |
_source | address | Collateral source |
_destination | address | Collateral destination |
_wad | uint256 | Amount of collateral transferred |
transferInternalCoins
Transfer internal coins (does not affect external balances from Coin.sol)
function transferInternalCoins(address _source, address _destination, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_source | address | Coins source |
_destination | address | Coins destination |
_rad | uint256 | Amount of coins transferred |
modifyCollateralBalance
Join/exit collateral into and and out of the system
function modifyCollateralBalance(bytes32 _cType, address _account, int256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to join/exit |
_account | address | Account that gets credited/debited |
_wad | int256 | Amount of collateral |
modifySAFECollateralization
Add/remove collateral or put back/generate more debt in a SAFE
function modifySAFECollateralization(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Type of collateral to withdraw/deposit in and from the SAFE |
_safe | address | Target SAFE |
_collateralSource | address | Account we take collateral from/put collateral into |
_debtDestination | address | Account from which we credit/debit coins and debt |
_deltaCollateral | int256 | Amount of collateral added/extracted from the SAFE [wad] |
_deltaDebt | int256 | Amount of debt to generate/repay [wad] |
transferSAFECollateralAndDebt
Transfer collateral and/or debt between SAFEs
function transferSAFECollateralAndDebt(
bytes32 _cType,
address _src,
address _dst,
int256 _deltaCollateral,
int256 _deltaDebt
) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type transferred between SAFEs |
_src | address | Source SAFE |
_dst | address | Destination SAFE |
_deltaCollateral | int256 | Amount of collateral to take/add into src and give/take from dst [wad] |
_deltaDebt | int256 | Amount of debt to take/add into src and give/take from dst [wad] |
confiscateSAFECollateralAndDebt
Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else
function confiscateSAFECollateralAndDebt(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type the SAFE has locked inside |
_safe | address | Target SAFE |
_collateralSource | address | Who we take/give collateral to |
_debtDestination | address | Who we take/give debt to |
_deltaCollateral | int256 | Amount of collateral taken/added into the SAFE [wad] |
_deltaDebt | int256 | Amount of debt taken/added into the SAFE [wad] |
settleDebt
Nullify an amount of coins with an equal amount of debt
Coins & debt are like matter and antimatter, they nullify each other
function settleDebt(uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | Amount of debt & coins to destroy |
createUnbackedDebt
Allows an authorized contract to create debt without collateral
Usually called by DebtAuctionHouse in order to terminate auctions prematurely post settlement
function createUnbackedDebt(address _debtDestination, address _coinDestination, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_debtDestination | address | The account that will receive the newly created debt |
_coinDestination | address | The account that will receive the newly created coins |
_rad | uint256 | Amount of debt to create |
updateAccumulatedRate
Allows an authorized contract to accrue interest on a specific collateral type
The rateMultiplier is usually calculated by the TaxCollector contract
function updateAccumulatedRate(bytes32 _cType, address _surplusDst, int256 _rateMultiplier) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type we accrue interest for |
_surplusDst | address | Destination for the newly created surplus |
_rateMultiplier | int256 | Multiplier applied to the debtAmount in order to calculate the surplus [ray] |
updateCollateralPrice
Allows an authorized contract to update the safety price and liquidation price of a collateral type
function updateCollateralPrice(bytes32 _cType, uint256 _safetyPrice, uint256 _liquidationPrice) external;
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type we update the prices for |
_safetyPrice | uint256 | New safety price [ray] |
_liquidationPrice | uint256 | New liquidation price [ray] |
approveSAFEModification
Allow an address to modify your SAFE
function approveSAFEModification(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account to give SAFE permissions to |
denySAFEModification
Deny an address the rights to modify your SAFE
function denySAFEModification(address _account) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Account that is denied SAFE permissions |
canModifySAFE
Checks whether an account has the right to modify a SAFE
function canModifySAFE(address _safe, address _account) external view returns (bool _allowed);
Parameters
Name | Type | Description |
---|---|---|
_safe | address | The safe to check |
_account | address | The account to check |
Returns
Name | Type | Description |
---|---|---|
_allowed | bool | Whether the account can modify the safe |
Events
ApproveSAFEModification
Emitted when an address authorizes another address to modify its SAFE
event ApproveSAFEModification(address _sender, address _account);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address that sent the authorization |
_account | address | Address that is authorized to modify the SAFE |
DenySAFEModification
Emitted when an address denies another address to modify its SAFE
event DenySAFEModification(address _sender, address _account);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | Address that sent the denial |
_account | address | Address that is denied to modify the SAFE |
TransferCollateral
Emitted when collateral is transferred between accounts
event TransferCollateral(bytes32 indexed _cType, address indexed _src, address indexed _dst, uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_src | address | Address that sent the collateral |
_dst | address | Address that received the collateral |
_wad | uint256 | Amount of collateral transferred |
TransferInternalCoins
Emitted when internal coins are transferred between accounts
event TransferInternalCoins(address indexed _src, address indexed _dst, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_src | address | Address that sent the coins |
_dst | address | Address that received the coins |
_rad | uint256 | Amount of coins transferred |
ModifySAFECollateralization
Emitted when the SAFE state is modified by the owner or authorized accounts
event ModifySAFECollateralization(
bytes32 indexed _cType,
address indexed _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE |
_collateralSource | address | Address that sent/receives the collateral |
_debtDestination | address | Address that sent/receives the debt |
_deltaCollateral | int256 | Amount of collateral added/extracted from the SAFE [wad] |
_deltaDebt | int256 | Amount of debt to generate/repay [wad] |
TransferSAFECollateralAndDebt
Emitted when collateral and/or debt is transferred between SAFEs
event TransferSAFECollateralAndDebt(
bytes32 indexed _cType, address indexed _src, address indexed _dst, int256 _deltaCollateral, int256 _deltaDebt
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_src | address | Address that sent the collateral |
_dst | address | Address that received the collateral |
_deltaCollateral | int256 | Amount of collateral to take/add into src and give/take from dst [wad] |
_deltaDebt | int256 | Amount of debt to take/add into src and give/take from dst [wad] |
ConfiscateSAFECollateralAndDebt
Emitted when collateral and debt is confiscated from a SAFE
event ConfiscateSAFECollateralAndDebt(
bytes32 indexed _cType,
address indexed _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safe | address | Address of the SAFE |
_collateralSource | address | Address that sent/receives the collateral |
_debtDestination | address | Address that sent/receives the debt |
_deltaCollateral | int256 | Amount of collateral added/extracted from the SAFE [wad] |
_deltaDebt | int256 | Amount of debt to generate/repay [wad] |
SettleDebt
Emitted when an account's debt is settled with coins
Accounts (not SAFEs) can only settle unbacked debt
event SettleDebt(address indexed _account, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address of the account |
_rad | uint256 | Amount of debt & coins to destroy |
CreateUnbackedDebt
Emitted when an unbacked debt is created to an account
event CreateUnbackedDebt(address indexed _debtDestination, address indexed _coinDestination, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_debtDestination | address | Address that received the newly created debt |
_coinDestination | address | Address that received the newly created coins |
_rad | uint256 | Amount of debt to create |
UpdateAccumulatedRate
Emit when the accumulated rate of a collateral type is updated
event UpdateAccumulatedRate(bytes32 indexed _cType, address _surplusDst, int256 _rateMultiplier);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_surplusDst | address | Address that received the newly created surplus |
_rateMultiplier | int256 | Delta of the accumulated rate [ray] |
UpdateCollateralPrice
Emitted when the safety price and liquidation price of a collateral type is updated
event UpdateCollateralPrice(bytes32 indexed _cType, uint256 _safetyPrice, uint256 _liquidationPrice);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_safetyPrice | uint256 | New price at which a SAFE is allowed to generate debt [ray] |
_liquidationPrice | uint256 | New price at which a SAFE gets liquidated [ray] |
Errors
SAFEEng_CollateralTypeNotInitialized
Throws when trying to modify parameters of an uninitialized collateral type
error SAFEEng_CollateralTypeNotInitialized();
SAFEEng_SAFENotSafe
Throws when trying to modify a SAFE into an unsafe state
error SAFEEng_SAFENotSafe();
SAFEEng_DustySAFE
Throws when trying to modify a SAFE into a dusty safe (debt non-zero and below debtFloor
)
error SAFEEng_DustySAFE();
SAFEEng_GlobalDebtCeilingHit
Throws when trying to generate debt that would put the system over the global debt ceiling
error SAFEEng_GlobalDebtCeilingHit();
SAFEEng_CollateralDebtCeilingHit
Throws when trying to generate debt that would put the system over the collateral debt ceiling
error SAFEEng_CollateralDebtCeilingHit();
SAFEEng_SAFEDebtCeilingHit
Throws when trying to generate debt that would put the SAFE over the SAFE debt ceiling
error SAFEEng_SAFEDebtCeilingHit();
SAFEEng_NotSAFEAllowed
Throws when an account tries to modify a SAFE without the proper permissions
error SAFEEng_NotSAFEAllowed();
SAFEEng_NotCollateralSrcAllowed
Throws when an account tries to pull collateral from a SAFE without the proper permissions
error SAFEEng_NotCollateralSrcAllowed();
SAFEEng_NotDebtDstAllowed
Throws when an account tries to push debt to a SAFE without the proper permissions
error SAFEEng_NotDebtDstAllowed();
Structs
SAFE
struct SAFE {
uint256 lockedCollateral;
uint256 generatedDebt;
}
SAFEEngineParams
struct SAFEEngineParams {
uint256 safeDebtCeiling;
uint256 globalDebtCeiling;
}
SAFEEngineCollateralData
struct SAFEEngineCollateralData {
uint256 debtAmount;
uint256 lockedAmount;
uint256 accumulatedRate;
uint256 safetyPrice;
uint256 liquidationPrice;
}
SAFEEngineCollateralParams
struct SAFEEngineCollateralParams {
uint256 debtCeiling;
uint256 debtFloor;
}
IStabilityFeeTreasury
Inherits: IAuthorizable, IDisableable, IModifiable
Functions
allowance
Getter for the allowance struct of a given account
function allowance(address _account) external view returns (Allowance memory __allowance);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to query |
Returns
Name | Type | Description |
---|---|---|
__allowance | Allowance | Data structure containing total and per hour allowance for the given account |
_allowance
Getter for the unpacked allowance struct of a given account
A null per hour allowance means that the account has no per hour limit
function _allowance(address _account) external view returns (uint256 _total, uint256 _perHour);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to query |
Returns
Name | Type | Description |
---|---|---|
_total | uint256 | Total allowance for the given account |
_perHour | uint256 | Per hour allowance for the given account |
setTotalAllowance
Modify an address' total allowance in order to withdraw SF from the treasury
function setTotalAllowance(address _account, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | The approved address |
_rad | uint256 | The total approved amount of SF to withdraw [rad] |
setPerHourAllowance
Modify an address' per hour allowance in order to withdraw SF from the treasury
function setPerHourAllowance(address _account, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | The approved address |
_rad | uint256 | The per hour approved amount of SF to withdraw [rad] |
giveFunds
Governance transfers SF to an address
function giveFunds(address _account, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address to transfer SF to |
_rad | uint256 | Amount of internal system coins to transfer [rad] |
takeFunds
Governance takes funds from an address
function takeFunds(address _account, uint256 _rad) external;
Parameters
Name | Type | Description |
---|---|---|
_account | address | Address to take system coins from |
_rad | uint256 | Amount of internal system coins to take from the account [rad] |
pullFunds
Pull stability fees from the treasury
The caller of this method needs to have enough allowance in order to pull funds
function pullFunds(address _dstAccount, uint256 _wad) external;
Parameters
Name | Type | Description |
---|---|---|
_dstAccount | address | Address to transfer funds to |
_wad | uint256 | Amount of system coins (SF) to transfer [wad] |
transferSurplusFunds
Transfer surplus stability fees to the extraSurplusReceiver. This is here to make sure that the treasury doesn't accumulate fees that it doesn't even need in order to pay for allowances. It ensures that there are enough funds left in the treasury to account for posterior expenses
function transferSurplusFunds() external;
settleDebt
Settle as much bad debt as possible (if this contract has any)
function settleDebt() external returns (uint256 _coinBalance, uint256 _debtBalance);
Returns
Name | Type | Description |
---|---|---|
_coinBalance | uint256 | Amount of internal system coins that this contract has after settling debt |
_debtBalance | uint256 | Amount of bad debt that this contract has after settling debt |
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
coinJoin
Address of the CoinJoin contract
function coinJoin() external view returns (ICoinJoin _coinJoin);
extraSurplusReceiver
Address that receives surplus funds when treasury exceeds capacity (or is disabled)
function extraSurplusReceiver() external view returns (address _extraSurplusReceiver);
systemCoin
Address of the SystemCoin contract
function systemCoin() external view returns (ISystemCoin _systemCoin);
latestSurplusTransferTime
Timestamp of the last time that surplus funds were transferred
function latestSurplusTransferTime() external view returns (uint256 _latestSurplusTransferTime);
pulledPerHour
Amount of internal coins a given account has pulled from the treasury in a given block hour
function pulledPerHour(address _account, uint256 _blockHour) external view returns (uint256 _pulledPerHour);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account to query |
_blockHour | uint256 | The block hour to query |
Returns
Name | Type | Description |
---|---|---|
_pulledPerHour | uint256 | Amount of coins pulled from the treasury by the account in the given block hour [rad] |
params
Getter for the contract parameters struct
function params() external view returns (StabilityFeeTreasuryParams memory _sfTreasuryParams);
Returns
Name | Type | Description |
---|---|---|
_sfTreasuryParams | StabilityFeeTreasuryParams | StabilityFee parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (uint256 _treasuryCapacity, uint256 _pullFundsMinThreshold, uint256 _surplusTransferDelay);
Returns
Name | Type | Description |
---|---|---|
_treasuryCapacity | uint256 | Maximum amount of internal coins that the treasury can hold [rad] |
_pullFundsMinThreshold | uint256 | Minimum amount of internal coins that the treasury must hold in order to allow pulling funds [rad] |
_surplusTransferDelay | uint256 | Minimum amount of time that must pass between surplus transfers [seconds] |
Events
SetTotalAllowance
Emitted when an account's total allowance is modified
event SetTotalAllowance(address indexed _account, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account whose allowance was modified |
_rad | uint256 | The new total allowance [rad] |
SetPerHourAllowance
Emitted when an account's per hour allowance is modified
event SetPerHourAllowance(address indexed _account, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account whose allowance was modified |
_rad | uint256 | The new per hour allowance [rad] |
GiveFunds
Emitted when governance gives funds to an account
event GiveFunds(address indexed _account, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account that received funds |
_rad | uint256 | The amount of funds that were given [rad] |
TakeFunds
Emitted when governance takes funds from an account
event TakeFunds(address indexed _account, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_account | address | The account from which the funds are taken |
_rad | uint256 | The amount of funds that were taken [rad] |
PullFunds
Emitted when an account pulls funds from the treasury
event PullFunds(address indexed _sender, address indexed _dstAccount, uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | The account that triggered the pull |
_dstAccount | address | The account that received funds |
_rad | uint256 | The amount of funds that were pulled [rad] |
TransferSurplusFunds
Emitted when surplus funds are transferred to the extraSurplusReceiver
event TransferSurplusFunds(address _extraSurplusReceiver, uint256 _fundsToTransfer);
Parameters
Name | Type | Description |
---|---|---|
_extraSurplusReceiver | address | The account that received the surplus funds |
_fundsToTransfer | uint256 | The amount of funds that were transferred [rad] |
JoinCoins
Emitted when ERC20 coins are joined into the system
event JoinCoins(uint256 _wad);
Parameters
Name | Type | Description |
---|---|---|
_wad | uint256 | The amount of ERC20 coins that were joined [wad] |
SettleDebt
Emitted when treasury coins are used to settle debt
event SettleDebt(uint256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_rad | uint256 | The amount of internal system coins and debt that were destroyed [rad] |
Errors
SFTreasury_AccountCannotBeTreasury
Throws when trying to pull/give/take funds from/to the treasury itself
error SFTreasury_AccountCannotBeTreasury();
SFTreasury_OutstandingBadDebt
Throws when trying to transfer surplus funds without having settled all debt
error SFTreasury_OutstandingBadDebt();
SFTreasury_NotEnoughFunds
Throws when trying to transfer more funds than the treasury has
error SFTreasury_NotEnoughFunds();
SFTreasury_NotAllowed
Throws when trying to pull funds above the account's total allowance
error SFTreasury_NotAllowed();
SFTreasury_PerHourLimitExceeded
Throws when trying to pull funds above the account's per hour allowance
error SFTreasury_PerHourLimitExceeded();
SFTreasury_DstCannotBeAccounting
Throws when trying to pull funds to the accounting contract
error SFTreasury_DstCannotBeAccounting();
SFTreasury_NullTransferAmount
Throws when trying to transfer a null amount of funds
error SFTreasury_NullTransferAmount();
SFTreasury_BelowPullFundsMinThreshold
Throws when trying to pull funds while the coin balance is below the minimum threshold
error SFTreasury_BelowPullFundsMinThreshold();
SFTreasury_TransferCooldownNotPassed
Throws when trying to transfer surplus funds before the cooldown period has passed
error SFTreasury_TransferCooldownNotPassed();
SFTreasury_NotEnoughSurplus
Throws when trying to transfer surplus funds while the treasury is below capacity
error SFTreasury_NotEnoughSurplus();
Structs
StabilityFeeTreasuryParams
struct StabilityFeeTreasuryParams {
uint256 treasuryCapacity;
uint256 pullFundsMinThreshold;
uint256 surplusTransferDelay;
}
Allowance
struct Allowance {
uint256 total;
uint256 perHour;
}
ISurplusAuctionHouse
Inherits: IAuthorizable, IDisableable, IModifiable, ICommonSurplusAuctionHouse
Functions
params
Getter for the contract parameters struct
function params() external view returns (SurplusAuctionHouseParams memory _sahParams);
Returns
Name | Type | Description |
---|---|---|
_sahParams | SurplusAuctionHouseParams | Auction house parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (
uint256 _bidIncrease,
uint256 _bidDuration,
uint256 _totalAuctionLength,
address _bidReceiver,
uint256 _recyclingPercentage
);
Returns
Name | Type | Description |
---|---|---|
_bidIncrease | uint256 | Minimum bid increase compared to the last bid in order to take the new one in consideration [wad %] |
_bidDuration | uint256 | How long the auction lasts after a new bid is submitted [seconds] |
_totalAuctionLength | uint256 | Total length of the auction [seconds] |
_bidReceiver | address | Receiver of protocol tokens |
_recyclingPercentage | uint256 | Percentage of protocol tokens to recycle [wad %] |
terminateAuctionPrematurely
Terminate an auction prematurely.
function terminateAuctionPrematurely(uint256 _id) external;
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | ID of the auction to settle/terminate |
Events
TerminateAuctionPrematurely
Emitted when an auction is prematurely terminated
event TerminateAuctionPrematurely(
uint256 indexed _id, uint256 _blockTimestamp, address _highBidder, uint256 _raisedAmount
);
Parameters
Name | Type | Description |
---|---|---|
_id | uint256 | Id of the auction |
_blockTimestamp | uint256 | Time when the auction was terminated |
_highBidder | address | Who won the auction |
_raisedAmount | uint256 | Amount of protocol tokens raised in the auction [rad] |
Errors
SAH_NullProtTokenReceiver
Throws when trying to start an auction with non-zero recycling percentage and null bid receiver
error SAH_NullProtTokenReceiver();
Structs
SurplusAuctionHouseParams
struct SurplusAuctionHouseParams {
uint256 bidIncrease;
uint256 bidDuration;
uint256 totalAuctionLength;
address bidReceiver;
uint256 recyclingPercentage;
}
ITaxCollector
Inherits: IAuthorizable, IModifiable, IModifiablePerCollateral
Functions
params
Getter for the contract parameters struct
function params() external view returns (TaxCollectorParams memory _taxCollectorParams);
Returns
Name | Type | Description |
---|---|---|
_taxCollectorParams | TaxCollectorParams | Tax collector parameters struct |
_params
Getter for the unpacked contract parameters struct
function _params()
external
view
returns (
address _primaryTaxReceiver,
uint256 _globalStabilityFee,
uint256 _maxStabilityFeeRange,
uint256 _maxSecondaryReceivers
);
Returns
Name | Type | Description |
---|---|---|
_primaryTaxReceiver | address | Primary tax receiver address |
_globalStabilityFee | uint256 | Global stability fee [ray] |
_maxStabilityFeeRange | uint256 | Max stability fee range [ray] |
_maxSecondaryReceivers | uint256 | Max number of secondary tax receivers |
cParams
Getter for the collateral parameters struct
function cParams(bytes32 _cType) external view returns (TaxCollectorCollateralParams memory _taxCollectorCParams);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_taxCollectorCParams | TaxCollectorCollateralParams | Tax collector collateral parameters struct |
_cParams
Getter for the unpacked collateral parameters struct
function _cParams(bytes32 _cType) external view returns (uint256 _stabilityFee);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_stabilityFee | uint256 | Stability fee [ray] |
cData
Getter for the collateral data struct
function cData(bytes32 _cType) external view returns (TaxCollectorCollateralData memory _taxCollectorCData);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_taxCollectorCData | TaxCollectorCollateralData | Tax collector collateral data struct |
_cData
Getter for the unpacked collateral data struct
function _cData(bytes32 _cType)
external
view
returns (uint256 _nextStabilityFee, uint256 _updateTime, uint256 _secondaryReceiverAllotedTax);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
Returns
Name | Type | Description |
---|---|---|
_nextStabilityFee | uint256 | Per second borrow rate to be applied at the next taxation [ray] |
_updateTime | uint256 | When Stability Fee was last collected |
_secondaryReceiverAllotedTax | uint256 | Percentage of SF that goes to other addresses apart from the primary receiver |
secondaryTaxReceivers
Getter for the data about a specific secondary tax receiver
function secondaryTaxReceivers(
bytes32 _cType,
address _receiver
) external view returns (TaxReceiver memory _secondaryTaxReceiver);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_receiver | address | Tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_secondaryTaxReceiver | TaxReceiver | Tax receiver struct |
_secondaryTaxReceivers
Getter for the unpacked data about a specific secondary tax receiver
function _secondaryTaxReceivers(
bytes32 _cType,
address _receiver
) external view returns (address _secondaryReceiver, bool _canTakeBackTax, uint256 _taxPercentage);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_receiver | address | Tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_secondaryReceiver | address | Secondary tax receiver address |
_canTakeBackTax | bool | Whether this receiver can accept a negative rate (taking SF from it) |
_taxPercentage | uint256 | Percentage of SF allocated to this receiver |
safeEngine
Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
collectedManyTax
Check if multiple collateral types are up to date with taxation
function collectedManyTax(uint256 _start, uint256 _end) external view returns (bool _ok);
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index of the first collateral type to check |
_end | uint256 | Index of the last collateral type to check |
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether all collateral types are up to date |
taxManyOutcome
Check how much SF will be charged (to collateral types between indexes 'start' and 'end' in the collateralList) during the next taxation
function taxManyOutcome(uint256 _start, uint256 _end) external view returns (bool _ok, int256 _rad);
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index in collateralList from which to start looping and calculating the tax outcome |
_end | uint256 | Index in collateralList at which we stop looping and calculating the tax outcome |
Returns
Name | Type | Description |
---|---|---|
_ok | bool | Whether the tax outcome can be computed |
_rad | int256 | The total amount of SF that will be charged during the next taxation |
taxSingleOutcome
Get how much SF will be distributed after taxing a specific collateral type
function taxSingleOutcome(bytes32 _cType) external view returns (uint256 _newlyAccumulatedRate, int256 _deltaRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to compute the taxation outcome for |
Returns
Name | Type | Description |
---|---|---|
_newlyAccumulatedRate | uint256 | The newly accumulated rate |
_deltaRate | int256 | The delta between the new and the last accumulated rates |
secondaryReceiversListLength
Get the secondary tax receiver list length
function secondaryReceiversListLength() external view returns (uint256 _secondaryReceiversListLength);
collateralListLength
Get the collateralList length
function collateralListLength() external view returns (uint256 _collateralListLength);
isSecondaryReceiver
Check if a tax receiver is at a certain position in the list
function isSecondaryReceiver(address _receiver) external view returns (bool _isSecondaryReceiver);
Parameters
Name | Type | Description |
---|---|---|
_receiver | address | Tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_isSecondaryReceiver | bool | Whether the tax receiver for at least one collateral type |
secondaryReceiversList
Get the list of all secondary tax receivers
function secondaryReceiversList() external view returns (address[] memory _secondaryReceiversList);
secondaryReceiverRevenueSourcesList
Get the list of all collateral types for which a specific address is a secondary tax receiver
function secondaryReceiverRevenueSourcesList(address _secondaryReceiver)
external
view
returns (bytes32[] memory _secondaryReceiverRevenueSourcesList);
Parameters
Name | Type | Description |
---|---|---|
_secondaryReceiver | address | Secondary tax receiver address to check |
Returns
Name | Type | Description |
---|---|---|
_secondaryReceiverRevenueSourcesList | bytes32[] | List of collateral types for which the address is a secondary tax receiver |
taxMany
Collect tax from multiple collateral types at once
function taxMany(uint256 _start, uint256 _end) external;
Parameters
Name | Type | Description |
---|---|---|
_start | uint256 | Index in collateralList from which to start looping and calculating the tax outcome |
_end | uint256 | Index in collateralList at which we stop looping and calculating the tax outcome |
taxSingle
Collect tax from a single collateral type
function taxSingle(bytes32 _cType) external returns (uint256 _latestAccumulatedRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Collateral type to tax |
Returns
Name | Type | Description |
---|---|---|
_latestAccumulatedRate | uint256 | The newly accumulated rate after taxation |
Events
SetPrimaryReceiver
Emitted when a new primary tax receiver is set
event SetPrimaryReceiver(bytes32 indexed _cType, address indexed _receiver);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_receiver | address | Address of the new primary tax receiver |
SetSecondaryReceiver
Emitted when a new secondary tax receiver is set
(taxPercentage, canTakeBackTax) = (0, false) means that the receiver is removed
event SetSecondaryReceiver(
bytes32 indexed _cType, address indexed _receiver, uint256 _taxPercentage, bool _canTakeBackTax
);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_receiver | address | Address of the new secondary tax receiver |
_taxPercentage | uint256 | Percentage of SF allocated to this receiver |
_canTakeBackTax | bool | Whether this receiver can accept a negative rate (taking SF from it) |
CollectTax
Emitted once when a collateral type taxation is processed
event CollectTax(bytes32 indexed _cType, uint256 _latestAccumulatedRate, int256 _deltaRate);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_latestAccumulatedRate | uint256 | The newly accumulated rate |
_deltaRate | int256 | The delta between the new and the last accumulated rates |
DistributeTax
Emitted when a collateral type taxation is distributed (one event per receiver)
SF can be negative if the receiver can take back tax
event DistributeTax(bytes32 indexed _cType, address indexed _target, int256 _taxCut);
Parameters
Name | Type | Description |
---|---|---|
_cType | bytes32 | Bytes32 representation of the collateral type |
_target | address | Address of the tax receiver |
_taxCut | int256 | Amount of SF collected for this receiver |
Errors
TaxCollector_InvalidIndexes
Throws when inputting an invalid index for the collateral type list
error TaxCollector_InvalidIndexes();
TaxCollector_NullAccount
Throws when trying to add a null address as a tax receiver
error TaxCollector_NullAccount();
TaxCollector_PrimaryReceiverCannotBeSecondary
Throws when trying to add a tax receiver that is already the primary receiver
error TaxCollector_PrimaryReceiverCannotBeSecondary();
TaxCollector_CollateralTypeNotInitialized
Throws when trying to modify parameters for a collateral type that is not initialized
error TaxCollector_CollateralTypeNotInitialized();
TaxCollector_ExceedsMaxReceiverLimit
Throws when trying to add a tax receiver that would surpass the max number of receivers
error TaxCollector_ExceedsMaxReceiverLimit();
TaxCollector_NullSF
Throws when trying to collect tax for a receiver with null tax percentage
error TaxCollector_NullSF();
TaxCollector_TaxCutExceedsHundred
Throws when trying to add a receiver such that the total tax percentage would surpass 100%
error TaxCollector_TaxCutExceedsHundred();
TaxCollector_TaxCutTooBig
Throws when trying to modify a receiver such that the total tax percentage would surpass 100%
error TaxCollector_TaxCutTooBig();
Structs
TaxCollectorParams
struct TaxCollectorParams {
address primaryTaxReceiver;
uint256 globalStabilityFee;
uint256 maxStabilityFeeRange;
uint256 maxSecondaryReceivers;
}
TaxCollectorCollateralParams
struct TaxCollectorCollateralParams {
uint256 stabilityFee;
}
TaxCollectorCollateralData
struct TaxCollectorCollateralData {
uint256 nextStabilityFee;
uint256 updateTime;
uint256 secondaryReceiverAllotedTax;
}
TaxReceiver
struct TaxReceiver {
address receiver;
bool canTakeBackTax;
uint256 taxPercentage;
}
Contents
Assertions
This library contains assertions for common requirement checks
Functions
assertGt
Asserts that _x
is greater than _y
and returns _x
function assertGt(uint256 _x, uint256 _y) internal pure returns (uint256 __x);
assertGt
Asserts that _x
is greater than _y
and returns _x
function assertGt(int256 _x, int256 _y) internal pure returns (int256 __x);
assertGtEq
Asserts that _x
is greater than or equal to _y
and returns _x
function assertGtEq(uint256 _x, uint256 _y) internal pure returns (uint256 __x);
assertGtEq
Asserts that _x
is greater than or equal to _y
and returns _x
function assertGtEq(int256 _x, int256 _y) internal pure returns (int256 __x);
assertLt
Asserts that _x
is lesser than _y
and returns _x
function assertLt(uint256 _x, uint256 _y) internal pure returns (uint256 __x);
assertLt
Asserts that _x
is lesser than _y
and returns _x
function assertLt(int256 _x, int256 _y) internal pure returns (int256 __x);
assertLtEq
Asserts that _x
is lesser than or equal to _y
and returns _x
function assertLtEq(uint256 _x, uint256 _y) internal pure returns (uint256 __x);
assertLtEq
Asserts that _x
is lesser than or equal to _y
and returns _x
function assertLtEq(int256 _x, int256 _y) internal pure returns (int256 __x);
assertNonNull
Asserts that _x
is not null and returns _x
function assertNonNull(uint256 _x) internal pure returns (uint256 __x);
assertNonNull
Asserts that _address
is not null and returns _address
function assertNonNull(address _address) internal pure returns (address __address);
assertHasCode
Asserts that _address
contains code and returns _address
function assertHasCode(address _address) internal view returns (address __address);
Errors
NotGreaterThan
Throws if _x
is not greater than _y
error NotGreaterThan(uint256 _x, uint256 _y);
NotLesserThan
Throws if _x
is not lesser than _y
error NotLesserThan(uint256 _x, uint256 _y);
NotGreaterOrEqualThan
Throws if _x
is not greater than or equal to _y
error NotGreaterOrEqualThan(uint256 _x, uint256 _y);
NotLesserOrEqualThan
Throws if _x
is not lesser than or equal to _y
error NotLesserOrEqualThan(uint256 _x, uint256 _y);
IntNotGreaterThan
Throws if _x
is not greater than _y
error IntNotGreaterThan(int256 _x, int256 _y);
IntNotLesserThan
Throws if _x
is not lesser than _y
error IntNotLesserThan(int256 _x, int256 _y);
IntNotGreaterOrEqualThan
Throws if _x
is not greater than or equal to _y
error IntNotGreaterOrEqualThan(int256 _x, int256 _y);
IntNotLesserOrEqualThan
Throws if _x
is not lesser than or equal to _y
error IntNotLesserOrEqualThan(int256 _x, int256 _y);
NullAmount
Throws if checked amount is null
error NullAmount();
NullAddress
Throws if checked address is null
error NullAddress();
NoCode
Throws if checked address contains no code
error NoCode(address _contract);
Encoding
This library contains functions for decoding data into common types
Functions
toUint256
Decodes a bytes array into a uint256
function toUint256(bytes memory _data) internal pure returns (uint256 _uint256);
toInt256
Decodes a bytes array into an int256
function toInt256(bytes memory _data) internal pure returns (int256 _int256);
toAddress
Decodes a bytes array into an address
function toAddress(bytes memory _data) internal pure returns (address _address);
toBool
Decodes a bytes array into a bool
function toBool(bytes memory _data) internal pure returns (bool _bool);
Math
This library contains common math functions
Functions
add
Calculates the sum of an unsigned integer and a signed integer
function add(uint256 _x, int256 _y) internal pure returns (uint256 _add);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | int256 | Signed integer |
Returns
Name | Type | Description |
---|---|---|
_add | uint256 | Unsigned sum of _x and _y |
sub
Calculates the substraction of an unsigned integer and a signed integer
function sub(uint256 _x, int256 _y) internal pure returns (uint256 _sub);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | int256 | Signed integer |
Returns
Name | Type | Description |
---|---|---|
_sub | uint256 | Unsigned substraction of _x and _y |
sub
Calculates the substraction of two unsigned integers
function sub(uint256 _x, uint256 _y) internal pure returns (int256 _sub);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | uint256 | Unsigned integer |
Returns
Name | Type | Description |
---|---|---|
_sub | int256 | Signed substraction of _x and _y |
mul
Calculates the multiplication of an unsigned integer and a signed integer
function mul(uint256 _x, int256 _y) internal pure returns (int256 _mul);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | int256 | Signed integer |
Returns
Name | Type | Description |
---|---|---|
_mul | int256 | Signed multiplication of _x and _y |
rmul
Calculates the multiplication of two unsigned RAY integers
function rmul(uint256 _x, uint256 _y) internal pure returns (uint256 _rmul);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned RAY integer |
_y | uint256 | Unsigned RAY integer |
Returns
Name | Type | Description |
---|---|---|
_rmul | uint256 | Unsigned multiplication of _x and _y in RAY precision |
rmul
Calculates the multiplication of an unsigned and a signed RAY integers
function rmul(uint256 _x, int256 _y) internal pure returns (int256 _rmul);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned RAY integer |
_y | int256 | Signed RAY integer |
Returns
Name | Type | Description |
---|---|---|
_rmul | int256 | Signed multiplication of _x and _y in RAY precision |
wmul
Calculates the multiplication of two unsigned WAD integers
function wmul(uint256 _x, uint256 _y) internal pure returns (uint256 _wmul);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned WAD integer |
_y | uint256 | Unsigned WAD integer |
Returns
Name | Type | Description |
---|---|---|
_wmul | uint256 | Unsigned multiplication of _x and _y in WAD precision |
wmul
Calculates the multiplication of an unsigned and a signed WAD integers
function wmul(uint256 _x, int256 _y) internal pure returns (int256 _wmul);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned WAD integer |
_y | int256 | Signed WAD integer |
Returns
Name | Type | Description |
---|---|---|
_wmul | int256 | Signed multiplication of _x and _y in WAD precision |
wmul
Calculates the multiplication of two signed WAD integers
function wmul(int256 _x, int256 _y) internal pure returns (int256 _wmul);
Parameters
Name | Type | Description |
---|---|---|
_x | int256 | Signed WAD integer |
_y | int256 | Signed WAD integer |
Returns
Name | Type | Description |
---|---|---|
_wmul | int256 | Signed multiplication of _x and _y in WAD precision |
rdiv
Calculates the division of two unsigned RAY integers
function rdiv(uint256 _x, uint256 _y) internal pure returns (uint256 _rdiv);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned RAY integer |
_y | uint256 | Unsigned RAY integer |
Returns
Name | Type | Description |
---|---|---|
_rdiv | uint256 | Unsigned division of _x by _y in RAY precision |
rdiv
Calculates the division of two signed RAY integers
function rdiv(int256 _x, int256 _y) internal pure returns (int256 _rdiv);
Parameters
Name | Type | Description |
---|---|---|
_x | int256 | Signed RAY integer |
_y | int256 | Signed RAY integer |
Returns
Name | Type | Description |
---|---|---|
_rdiv | int256 | Signed division of _x by _y in RAY precision |
wdiv
Calculates the division of two unsigned WAD integers
function wdiv(uint256 _x, uint256 _y) internal pure returns (uint256 _wdiv);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned WAD integer |
_y | uint256 | Unsigned WAD integer |
Returns
Name | Type | Description |
---|---|---|
_wdiv | uint256 | Unsigned division of _x by _y in WAD precision |
rpow
Calculates the power of an unsigned RAY integer to an unsigned integer
function rpow(uint256 _x, uint256 _n) internal pure returns (uint256 _rpow);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned RAY integer |
_n | uint256 | Unsigned integer exponent |
Returns
Name | Type | Description |
---|---|---|
_rpow | uint256 | Unsigned _x to the power of _n in RAY precision |
max
Calculates the maximum of two unsigned integers
function max(uint256 _x, uint256 _y) internal pure returns (uint256 _max);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | uint256 | Unsigned integer |
Returns
Name | Type | Description |
---|---|---|
_max | uint256 | Unsigned maximum of _x and _y |
min
Calculates the minimum of two unsigned integers
function min(uint256 _x, uint256 _y) internal pure returns (uint256 _min);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
_y | uint256 | Unsigned integer |
Returns
Name | Type | Description |
---|---|---|
_min | uint256 | Unsigned minimum of _x and _y |
toInt
Casts an unsigned integer to a signed integer
Throws if _x
is too large to fit in an int256
function toInt(uint256 _x) internal pure returns (int256 _int);
Parameters
Name | Type | Description |
---|---|---|
_x | uint256 | Unsigned integer |
Returns
Name | Type | Description |
---|---|---|
_int | int256 | Signed integer |
riemannSum
Calculates the Riemann sum of two signed integers
function riemannSum(int256 _x, int256 _y) internal pure returns (int256 _riemannSum);
Parameters
Name | Type | Description |
---|---|---|
_x | int256 | Signed integer |
_y | int256 | Signed integer |
Returns
Name | Type | Description |
---|---|---|
_riemannSum | int256 | Riemann sum of _x and _y |
absolute
Calculates the absolute value of a signed integer
function absolute(int256 _x) internal pure returns (uint256 _z);
Parameters
Name | Type | Description |
---|---|---|
_x | int256 | Signed integer |
Returns
Name | Type | Description |
---|---|---|
_z | uint256 | Unsigned absolute value of _x |
Errors
IntOverflow
Throws when trying to cast a uint256 to an int256 that overflows
error IntOverflow();
Constants
MAX_RAD
Max uint256 value that a RAD can represent without overflowing
uint256 constant MAX_RAD = type(uint256).max / RAY;
RAD
Uint256 representation of 1 RAD
uint256 constant RAD = 10 ** 45;
RAY
Uint256 representation of 1 RAY
uint256 constant RAY = 10 ** 27;
WAD
Uint256 representation of 1 WAD
uint256 constant WAD = 10 ** 18;
YEAR
Uint256 representation of 1 year in seconds
uint256 constant YEAR = 365 days;
HOUR
Uint256 representation of 1 hour in seconds
uint256 constant HOUR = 3600;