🔗 CHAINLINK ORACLES: Datos del Mundo Real en Blockchain

Sin oráculos no hay DeFi ” cómo traer precios confiables y calcular el Health Factor

Semanas 7-8: Lending y Oráculos
Price FeedsStaleness CheckHealth FactorLiquidation Threshold
🔗 El problema del oráculo: Los smart contracts son deterministas ” no pueden llamar a una API externa. Pero los protocolos de lending necesitan saber el precio actual de ETH para calcular si un préstamo está subcapitalizado. Chainlink resuelve esto con una red de nodos descentralizados que agregan precios de múltiples fuentes y los envían a un contrato en la blockchain. Siempre debes verificar el timestamp del oráculo ” un precio "stale" (desactualizado) de hace 24 horas puede ser explotado en un ataque de precio manipulado.
📚 Refs: Chainlink Docs ” Price Feeds · "The Oracle Problem" ” Vitalik Buterin · Venus Protocol hack (2021) por oracle manipulation

Live Price Feeds (simulado)

ETH/USD$2,000hace 0s
BTC/USD$65,000hace 0s
LINK/USD$14.50hace 0s
BNB/USD$580hace 0s

Health Factor Calculator

5 ETH
5000
80%

Health Factor en Tiempo Real

$10,000
Colateral USD
$5,000
Deuda total
50%
LTV actual
1.60
Health Factor
Health Factor
HF: 1.60
0 ” Liquidado1.0 ” Umbral2.0+ ” Seguro
… POSICIÓN SALUDABLE ” Sin riesgo de liquidación

Solidity ” Chainlink Price Feed + HF

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract LendingWithOracle {
  AggregatorV3Interface immutable ethPriceFeed;
  uint256 constant LIQUIDATION_THRESHOLD = 80; // 80%
  uint256 constant STALENESS_THRESHOLD  = 3600; // 1 hora

  function getEthPrice() public view returns (uint256) {
    (
      ,          // roundId
      int256 price,    // precio con 8 decimales
      ,          // startedAt
      uint256 updatedAt,  // timestamp crítico
    ) = ethPriceFeed.latestRoundData();

    // CRÍTICO: verificar que el precio no sea stale
    require(
      block.timestamp - updatedAt < STALENESS_THRESHOLD,
      "Oracle: stale price"
    );
    require(price > 0, "Oracle: invalid price");
    return uint256(price) / 1e8; // normalizar a USD
  }

  function healthFactor(address user) public view
    returns (uint256) {
    uint256 collateralUSD =
      positions[user].ethAmount * getEthPrice();
    uint256 maxBorrow =
      collateralUSD * LIQUIDATION_THRESHOLD / 100;
    // HF = colateral ajustado / deuda (× 1e18 para precision)
    return maxBorrow * 1e18 / positions[user].debtUSD;
  }
}
🔗 Inicia el feed para ver precios en tiempo real. Ajusta colateral y deuda para ver cómo el Health Factor determina el riesgo de liquidación.