ERGO
DeFi Primitives
Advanced
2-4 weeks

CDP / Collateralized Lending Pattern

Borrow stable/credit tokens against locked ERG with liquidation rules

GitHub

문제

Users want to borrow against their ERG holdings without selling, and lenders want to earn yield on stable assets.

솔루션

Collateralized Debt Positions (CDPs) lock ERG as collateral and mint/borrow stable tokens. Oracle prices determine collateralization ratio. Under-collateralized positions are liquidated.

작동 방식

  1. 1User deposits ERG into CDP box as collateral
  2. 2Oracle provides ERG/USD price
  3. 3User can borrow up to (collateral * price * maxLTV)
  4. 4Borrowed tokens are minted or drawn from lending pool
  5. 5If collateral ratio falls below liquidation threshold, anyone can liquidate
  6. 6Liquidator repays debt and receives collateral at discount

코드 예제

{
  // CDP (Collateralized Debt Position) Box
  // R4: Owner public key
  // R5: Debt amount (in stable tokens)
  // R6: Minimum collateral ratio (e.g., 150 = 150%)
  // R7: Liquidation ratio (e.g., 120 = 120%)
  
  val owner = SELF.R4[SigmaProp].get
  val debtAmount = SELF.R5[Long].get
  val minRatio = SELF.R6[Int].get
  val liqRatio = SELF.R7[Int].get
  
  val collateralErg = SELF.value
  val stableTokenId = fromBase64("STABLE_TOKEN_ID")
  
  // Oracle price (nanoERG per stable token)
  val oracleBox = CONTEXT.dataInputs(0)
  val oracleNFT = fromBase64("ORACLE_NFT_ID")
  val validOracle = oracleBox.tokens(0)._1 == oracleNFT
  val ergPrice = oracleBox.R4[Long].get  // e.g., 2000000 = $2 per ERG
  
  // Calculate collateral ratio
  val collateralValue = collateralErg * ergPrice / 1000000000L
  val currentRatio = if (debtAmount > 0) collateralValue * 100 / debtAmount else 999
  
  // Owner operations (add collateral, repay debt, withdraw)
  val ownerAction = {
    val newCdp = OUTPUTS(0)
    val newDebt = newCdp.R5[Long].get
    val newCollateral = newCdp.value
    
    // Can add collateral freely
    val addingCollateral = newCollateral > collateralErg && newDebt == debtAmount
    
    // Can repay debt (must provide stable tokens)
    val repayingDebt = newDebt < debtAmount
    
    // Can withdraw if ratio stays above minimum
    val newRatio = newCollateral * ergPrice * 100 / (newDebt * 1000000000L)
    val safeWithdraw = newRatio >= minRatio
    
    owner && (addingCollateral || (repayingDebt && safeWithdraw))
  }
  
  // Liquidation (anyone can call if under-collateralized)
  val liquidation = {
    val underCollateralized = currentRatio < liqRatio
    
    // Liquidator must repay debt
    val debtRepaid = OUTPUTS.exists(o =>
      o.tokens.exists(t => t._1 == stableTokenId && t._2 >= debtAmount)
    )
    
    // Liquidator receives collateral at discount (e.g., 10%)
    val liquidatorBonus = 10  // 10% discount
    val liquidatorReceives = collateralErg * (100 - liquidatorBonus) / 100
    
    underCollateralized && debtRepaid
  }
  
  validOracle && (ownerAction || liquidation)
}

CDP contract with oracle-based pricing. Owner can manage position, anyone can liquidate if under-collateralized.

사용 사례

  • Stablecoin minting (like MakerDAO)
  • Leveraged trading
  • Yield farming collateral
  • Self-repaying loans
  • Credit lines

보안 고려사항

  • !Oracle manipulation is critical risk - use multiple sources
  • !Set conservative collateral ratios (150%+)
  • !Implement circuit breakers for extreme price moves
  • !Consider flash loan attacks on liquidations
  • !Audit liquidation math thoroughly

실제 구현 사례

SigmaUSD

Algorithmic stablecoin with reserve-backed CDPs

리소스

수수료 고려사항

Liquidation transactions can be gas-intensive. Ensure liquidation bonus covers fees.

ErgoScript 실력을 향상시키세요

새로운 패턴, 튜토리얼, 개발자 리소스 알림을 받으세요.

Follow for daily updates