For the complete documentation index, see llms.txt. This page is also available as Markdown.

Deleverage

📄 View Source Code

Overview

Deleverage is the debt reduction engine of Ripe Protocol, enabling users to reduce their debt positions by liquidating their own collateral in a controlled, prioritized manner. Unlike liquidations which are triggered by external actors when positions become unhealthy, deleveraging is a proactive mechanism that allows users (or authorized callers) to unwind positions gracefully.

Core Functions:

  • Prioritized Asset Liquidation: Processes collateral in a three-phase order (stability pool assets → priority assets → remaining vaults)

  • Batch Operations: Deleverage multiple users or specific assets in single transactions

  • Collateral Swapping: Swap collateral between vaults while maintaining debt health

  • Underscore Integration: Special deleverage support for underscore leverage vaults

  • Volatile Asset Handling: Dedicated path for volatile collateral that bypasses stability pool logic

Deleverage implements efficient gas optimization through transient storage for caching vault addresses and asset configurations. It works closely with CreditEngine for debt repayment, AuctionHouse for collateral withdrawal, Teller as the user entry point, and EndaomentFunds as the recipient for transferred assets.

Architecture & Modules

Deleverage is built using a modular architecture with the following components:

Addys Module

  • Location: contracts/modules/Addys.vy

  • Purpose: Provides protocol-wide address resolution

  • Key Features:

    • Access to all protocol contract addresses

    • Validation of caller permissions

    • Centralized address management

  • Exported Interface: Address utilities via addys.__interface__

DeptBasics Module

  • Location: contracts/modules/DeptBasics.vy

  • Purpose: Provides department-level functionality

  • Key Features:

    • Pause mechanism for emergency stops

    • No Green minting capability

    • No Ripe minting capability

  • Exported Interface: Department basics via deptBasics.__interface__

Module Initialization

System Architecture Diagram

Data Structures

DeleverageUserRequest Struct

Request parameters for batch user deleverage:

DeleverageAsset Struct

Specific asset deleverage parameters:

GenLiqConfig Struct

General liquidation configuration from MissionControl:

AssetLiqConfig Struct

Per-asset liquidation configuration:

VaultData Struct

Vault reference information:

UserBorrowTerms Struct

Aggregated borrowing parameters:

UserDebt Struct

Current debt state for a user:

Events

DeleverageUser

Emitted when a user is deleveraged:

StabAssetBurntDuringDeleverage

Emitted when stability pool assets are burned:

EndaomentTransferDuringDeleverage

Emitted when assets are transferred to Endaoment:

CollateralSwapped

Emitted when collateral is swapped between vaults:

DeleverageUserWithVolatileAssets

Emitted when volatile assets are deleveraged:

State Variables

Constants

  • UNDERSCORE_LEGOBOOK_ID: uint256 = 3 - Registry ID for underscore lego book

  • UNDERSCORE_VAULT_REGISTRY_ID: uint256 = 10 - Registry ID for underscore vault registry

  • HUNDRED_PERCENT: uint256 = 100_00 - 100.00% in basis points

  • ONE_PERCENT: uint256 = 1_00 - 1.00% in basis points

  • PRIORITY_LIQ_VAULT_DATA: uint256 = 20 - Max priority liquidation vaults

  • MAX_STAB_VAULT_DATA: uint256 = 10 - Max stability pool vaults

  • MAX_DELEVERAGE_USERS: uint256 = 25 - Max users per batch deleverage

  • MAX_DELEVERAGE_ASSETS: uint256 = 25 - Max assets per specific deleverage

Transient Storage (Cache)

  • vaultAddrs: HashMap[uint256, address] - Cached vault addresses

  • assetLiqConfig: HashMap[address, AssetLiqConfig] - Cached asset configs

  • didHandleAsset: HashMap[address, HashMap[uint256, HashMap[address, bool]]] - Processed asset tracking

  • didHandleVaultId: HashMap[address, HashMap[uint256, bool]] - Processed vault tracking

Inherited State Variables

From DeptBasics:

  • isPaused: bool - Department pause state

Constructor

__init__

Initializes Deleverage contract without special minting permissions.

Parameters

Name
Type
Description

_ripeHq

address

RipeHq contract address

Example Usage

Main Deleverage Functions

deleverageUser

Deleverages a single user by liquidating their collateral to repay debt.

Parameters

Name
Type
Description

_user

address

User to deleverage

_caller

address

Original caller address

_targetRepayAmount

uint256

Target debt reduction (0=max)

_a

addys.Addys

Cached addresses (optional)

Returns

Type
Description

uint256

Actual amount repaid

Access

Only callable by Teller contract

Events Emitted

  • DeleverageUser - Deleverage completion details

  • StabAssetBurntDuringDeleverage - If stability assets burned

  • EndaomentTransferDuringDeleverage - If assets transferred

Example Usage

deleverageManyUsers

Batch deleverages multiple users in a single transaction.

Parameters

Name
Type
Description

_users

DynArray[DeleverageUserRequest, 25]

Array of user requests

_caller

address

Original caller address

_a

addys.Addys

Cached addresses (optional)

Returns

Type
Description

uint256

Total amount repaid

Access

Only callable by Teller contract

Example Usage

deleverageWithSpecificAssets

Deleverages a user using specific assets in a specified order. Requires trusted caller or delegation.

Parameters

Name
Type
Description

_user

address

User to deleverage

_assets

DynArray[DeleverageAsset, 25]

Ordered list of assets

_caller

address

Original caller address

_a

addys.Addys

Cached addresses (optional)

Returns

Type
Description

uint256

Total amount repaid

Access

Only callable by Teller contract. Caller must be:

  • The user themselves

  • A valid Ripe address

  • An underscore address

  • Have borrow delegation from the user

Example Usage

Special Deleverage Functions

deleverageWithVolAssets

Deleverages volatile collateral assets only, skipping stability pool and endaoment transfer assets.

Parameters

Name
Type
Description

_user

address

User to deleverage

_assets

DynArray[DeleverageAsset, 25]

Volatile assets to use

Returns

Type
Description

uint256

Total amount repaid

Access

Only callable by Switchboard or valid Ripe addresses

Events Emitted

  • DeleverageUserWithVolatileAssets - Completion details

Example Usage

swapCollateral

Swaps collateral from one vault/asset to another while maintaining debt health. The deposit asset must have LTV >= withdraw asset LTV.

Parameters

Name
Type
Description

_user

address

User whose collateral to swap

_withdrawVaultId

uint256

Source vault ID

_withdrawAsset

address

Asset to withdraw

_depositVaultId

uint256

Destination vault ID

_depositAsset

address

Asset to deposit

_withdrawAmount

uint256

Amount to withdraw (max=all)

Returns

Type
Description

uint256

Amount withdrawn

uint256

Amount deposited

Access

Only callable by valid Ripe addresses or governance

Events Emitted

  • CollateralSwapped - Swap details

Example Usage

deleverageForWithdrawal

Special deleverage triggered by underscore vaults to maintain utilization ratio when users withdraw.

Parameters

Name
Type
Description

_user

address

User withdrawing

_vaultId

uint256

Vault ID (0 to auto-detect)

_asset

address

Asset being withdrawn

_amount

uint256

Withdrawal amount

Returns

Type
Description

bool

True if deleverage was successful

Access

Only callable by underscore addresses or valid Ripe addresses

Key Logic

Uses a weighted LTV formula to calculate required repayment:

Applies a 1% buffer and caps at max deleveragable amount.

Example Usage

View Functions

getDeleverageInfo

Returns the maximum deleveragable USD value and effective weighted LTV for a user.

Parameters

Name
Type
Description

_user

address

User to check

Returns

Type
Description

uint256

Max deleveragable USD value

uint256

Effective weighted LTV

Example Usage

getMaxDeleverageAmount

Returns the maximum amount an untrusted caller can deleverage for a user.

Parameters

Name
Type
Description

_user

address

User to check

Returns

Type
Description

uint256

Maximum repayable amount

Access

Public view function

Key Logic

Only returns non-zero if:

  • User has debt

  • User is not in liquidation

  • User has collateral

  • Collateral value is below redemption threshold

Applies LTV payback buffer to be conservative.

Example Usage

Key Mathematical Functions

Three-Phase Deleverage Algorithm

The contract processes assets in a specific priority order:

  1. Phase 1 - Stability Pool Assets: Burns GREEN/sGREEN directly from stability pools

  2. Phase 2 - Priority Liquidation Assets: Processes assets marked as priority in MissionControl

  3. Phase 3 - All User Vaults: Iterates through remaining user positions

Amount to Pay Calculation

For untrusted callers, the maximum repayable amount is calculated to bring the position back to a safe LTV:

Deleverage Eligibility Check

Withdrawal Deleverage Formula

For underscore vault withdrawals:

Security Considerations

  1. Access Control: Main functions only callable by Teller; special functions by Switchboard/Ripe/governance

  2. Transient Storage: Uses EIP-1153 transient storage for gas-efficient caching within transactions

  3. Delegation Checks: Specific asset ordering requires trusted caller or borrow delegation

  4. LTV Validation: Collateral swaps validate that deposit asset LTV >= withdraw asset LTV

  5. Reentrancy Protection: External calls follow checks-effects-interactions pattern

  6. Buffer Application: 1% buffer applied to withdrawal deleverage calculations

  7. Pause Mechanism: All functions respect isPaused flag for emergency stops

  8. Cap Enforcement: Maximum users (25) and assets (25) per batch to prevent gas exhaustion

Last updated