🔗 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 Feeds Staleness Check Health Factor Liquidation 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,000 hace 0s
BTC/USD $65,000 hace 0s
LINK/USD $14.50 hace 0s
BNB/USD $580 hace 0s
Iniciar Feed
ï¸ STALE PRICE DETECTED ” El precio ETH tiene más de 3600s. Transacción revertida.
Health Factor en Tiempo Real
Health Factor
0 ” Liquidado 1.0 ” Umbral 2.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.
🏅 ¡INSIGNIA ORACLE INTEGRATOR!
Integraste Chainlink y calculaste Health Factors. ¡Sin oráculos confiables no existe el DeFi lending!
Smart Contracts DeFi · Semana 7-8 · Chainlink Price Feeds · Health Factor