Oracle Integration Patterns
Oracles bridge the gap between on-chain smart contracts and off-chain data sources, enabling decentralized applications to access real-world information.
Oracle Architecture Overview
Chainlink Integration
Price Feed Integration
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor(address _priceFeed) {
priceFeed = AggregatorV3Interface(_priceFeed);
}
function getLatestPrice() public view returns (int256) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceFeed.latestRoundData();
require(block.timestamp - updatedAt < 3600, "Stale price");
require(price > 0, "Invalid price");
return price;
}
function getDecimals() public view returns (uint8) {
return priceFeed.decimals();
}
}
Chainlink VRF (Verifiable Random Function)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
contract RandomNumberConsumer is VRFConsumerBaseV2 {
VRFCoordinatorV2Interface COORDINATOR;
bytes32 keyHash;
uint64 subId;
uint16 requestConfirmations = 3;
uint32 callbackGasLimit = 100000;
uint32 numWords = 1;
uint256[] public randomWords;
mapping(uint256 => bool) public requestFulfilled;
constructor(
address _coordinator,
bytes32 _keyHash,
uint64 _subId
) VRFConsumerBaseV2(_coordinator) {
COORDINATOR = VRFCoordinatorV2Interface(_coordinator);
keyHash = _keyHash;
subId = _subId;
}
function requestRandomWords() external returns (uint256 requestId) {
requestId = COORDINATOR.requestRandomWords(
keyHash,
subId,
requestConfirmations,
callbackGasLimit,
numWords
);
requestIds.push(requestId);
}
function fulfillRandomWords(
uint256 requestId,
uint256[] memory _randomWords
) internal override {
randomWords = _randomWords;
requestFulfilled[requestId] = true;
emit RandomWordsFulfilled(requestId, _randomWords[0]);
}
function getRandomNumber() external view returns (uint256) {
require(randomWords.length > 0, "No random words");
return randomWords[0];
}
}
Chainlink Automation (Keepers)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@chainlink/contracts/src/v0.8/AutomationCompatible.sol";
contract AutomationConsumer is AutomationCompatible {
uint256 public lastExecution;
uint256 public interval = 1 hours;
function checkUpkeep(
bytes calldata
) external view override returns (bool upkeepNeeded, bytes memory performData) {
upkeepNeeded = (block.timestamp - lastExecution) > interval;
performData = abi.encode(block.timestamp);
}
function performUpkeep(bytes calldata calldataData) external override {
require(
(block.timestamp - lastExecution) > interval,
"Upkeep not needed"
);
lastExecution = block.timestamp;
// Perform automated task
_executeTask();
}
function _executeTask() internal {
// Custom logic here
}
}
Band Protocol
Band Data Integration
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@bandprotocol/contracts/v5/core/Bandoracle.sol";
import "@bandprotocol/contracts/v5/core/IBandoracle.sol";
contract BandConsumer {
IBandOracle public oracle;
constructor(address _oracle) {
oracle = IBandOracle(_oracle);
}
function getRate(string calldata symbol) public view returns (uint256) {
(bool success, bytes memory data) = oracle.staticcall(
abi.encodeWithSignature("getRate(string)", symbol)
);
require(success, "Oracle call failed");
return abi.decode(data, (uint256));
}
function getReferenceData(
string calldata base,
string calldata quote
) public view returns (uint256 rate, uint256 lastUpdate, uint256 volatility) {
(
bool success,
bytes memory data
) = oracle.staticcall(
abi.encodeWithSignature(
"getReferenceData(string,string)",
base,
quote
)
);
require(success, "Oracle call failed");
return abi.decode(data, (uint256, uint256, uint256));
}
}
TWAP (Time-Weighted Average Price)
On-Chain TWAP Implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract TWAPOracle {
struct Observation {
uint256 timestamp;
uint256 priceCumulative;
uint256 blockTimestamp;
}
Observation[] public observations;
uint256 public constant PERIOD = 30 minutes;
function observe(uint256 period) public view returns (uint256 twap) {
require(observations.length >= 2, "Insufficient observations");
uint256 timeElapsed = block.timestamp - observations[observations.length - 1].blockTimestamp;
require(timeElapsed >= period, "Period not elapsed");
uint256[] memory prices = new uint256[](observations.length);
uint256[] memory weights = new uint256[](observations.length);
for (uint256 i = 0; i < observations.length; i++) {
if (i > 0) {
uint256 timeDelta = observations[i].blockTimestamp - observations[i-1].blockTimestamp;
uint256 priceDelta = observations[i].priceCumulative - observations[i-1].priceCumulative;
prices[i] = priceDelta / timeDelta;
weights[i] = timeDelta;
}
}
// Calculate weighted average
uint256 totalWeight = 0;
uint256 weightedSum = 0;
for (uint256 i = 1; i < observations.length; i++) {
weightedSum += prices[i] * weights[i];
totalWeight += weights[i];
}
twap = weightedSum / totalWeight;
}
function update(uint256 price) external {
if (observations.length == 0) {
observations.push(Observation({
timestamp: block.timestamp,
priceCumulative: 0,
blockTimestamp: block.timestamp
}));
}
uint256 timeElapsed = block.timestamp - observations[observations.length - 1].blockTimestamp;
uint256 newPriceCumulative = observations[observations.length - 1].priceCumulative + (price * timeElapsed);
observations.push(Observation({
timestamp: block.timestamp,
priceCumulative: newPriceCumulative,
blockTimestamp: block.timestamp
}));
}
}
TWAP Formula
Where:
- = Price at interval
- = Duration of interval
- = Number of intervals
Oracle Manipulation Resistance
Price Deviation Detection
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract OracleGuard {
uint256 public constant MAX_DEVIATION = 500; // 5%
uint256 public constant MIN_LIQUIDITY = 1000000; // 1M USD
mapping(address => uint256) public lastPrice;
mapping(address => uint256) public lastUpdate;
modifier onlyTrustedOracle(address oracle) {
require(trustedOracles[oracle], "Untrusted oracle");
_;
}
function checkPrice(
address oracle,
address token,
uint256 newPrice
) public returns (bool) {
require(trustedOracles[oracle], "Untrusted oracle");
if (lastPrice[token] == 0) {
lastPrice[token] = newPrice;
lastUpdate[token] = block.timestamp;
return true;
}
uint256 deviation = _calculateDeviation(lastPrice[token], newPrice);
require(deviation <= MAX_DEVIATION, "Price deviation too high");
lastPrice[token] = newPrice;
lastUpdate[token] = block.timestamp;
return true;
}
function _calculateDeviation(uint256 oldPrice, uint256 newPrice) internal pure returns (uint256) {
if (newPrice > oldPrice) {
return ((newPrice - oldPrice) * 10000) / oldPrice;
} else {
return ((oldPrice - newPrice) * 10000) / oldPrice;
}
}
}
Circuit Breaker Pattern
contract CircuitBreaker {
uint256 public constant COOLDOWN = 1 hours;
uint256 public constant MAX_PRICE_CHANGE = 1000; // 10%
bool public circuitBroken;
uint256 public lastPriceUpdate;
function updatePrice(uint256 newPrice) external {
require(!circuitBroken, "Circuit breaker active");
uint256 priceChange = _calculatePriceChange(lastPrice, newPrice);
require(priceChange <= MAX_PRICE_CHANGE, "Price change too large");
lastPrice = newPrice;
lastPriceUpdate = block.timestamp;
}
function triggerCircuitBreaker() external onlyOwner {
circuitBroken = true;
emit CircuitBreakerTriggered(block.timestamp);
}
function resetCircuitBreaker() external onlyOwner {
require(block.timestamp - lastPriceUpdate >= COOLDOWN, "Cooldown not elapsed");
circuitBroken = false;
emit CircuitBreakerReset(block.timestamp);
}
}
Data Verification
Signature Verification
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
contract OracleVerifier {
mapping(address => bool) public trustedOracles;
modifier onlyTrustedOracle() {
require(trustedOracles[msg.sender], "Untrusted oracle");
_;
}
function verifyData(
address oracle,
bytes32 dataHash,
uint256 timestamp,
bytes calldata signature
) public view returns (bool) {
require(trustedOracles[oracle], "Untrusted oracle");
require(block.timestamp - timestamp < 300, "Data too old");
bytes32 messageHash = keccak256(
abi.encodePacked(dataHash, timestamp, address(this))
);
bytes32 ethSignedHash = MessageHashEthSigned(messageHash);
address signer = ECDSA.recover(ethSignedHash, signature);
return signer == oracle;
}
}
Oracle Networks
Multi-Oracle Aggregation
contract MultiOracle {
struct OracleData {
uint256 price;
uint256 timestamp;
bool submitted;
}
address[] public oracleNodes;
mapping(address => OracleData) public oracleSubmissions;
mapping(bytes32 => uint256) public submissionCount;
uint256 public constant REQUIRED_SUBMISSIONS = 3;
uint256 public constant STALENESS_THRESHOLD = 300;
function submitPrice(
bytes32 requestId,
uint256 price
) external onlyOracleNode {
require(!oracleSubmissions[msg.sender].submitted, "Already submitted");
oracleSubmissions[msg.sender] = OracleData({
price: price,
timestamp: block.timestamp,
submitted: true
});
submissionCount[requestId]++;
if (submissionCount[requestId] >= REQUIRED_SUBMISSIONS) {
_aggregatePrices(requestId);
}
}
function _aggregatePrices(bytes32 requestId) internal {
uint256 totalPrice = 0;
uint256 validSubmissions = 0;
for (uint256 i = 0; i < oracleNodes.length; i++) {
OracleData memory data = oracleSubmissions[oracleNodes[i]];
if (data.submitted && block.timestamp - data.timestamp < STALENESS_THRESHOLD) {
totalPrice += data.price;
validSubmissions++;
}
}
require(validSubmissions >= REQUIRED_SUBMISSIONS, "Insufficient valid submissions");
aggregatedPrices[requestId] = totalPrice / validSubmissions;
emit PriceAggregated(requestId, aggregatedPrices[requestId]);
}
}
Fallback Oracles
Primary/Secondary Oracle Pattern
contract FallbackOracle {
address public primaryOracle;
address public secondaryOracle;
address public tertiaryOracle;
uint256 public constant STALENESS_THRESHOLD = 300;
function getPrice(
string calldata pair
) external view returns (uint256) {
try IOracle(primaryOracle).getPrice(pair) returns (uint256 price) {
if (price > 0 && block.timestamp - lastUpdate[primaryOracle] < STALENESS_THRESHOLD) {
return price;
}
} catch {}
try IOracle(secondaryOracle).getPrice(pair) returns (uint256 price) {
if (price > 0 && block.timestamp - lastUpdate[secondaryOracle] < STALENESS_THRESHOLD) {
return price;
}
} catch {}
return IOracle(tertiaryOracle).getPrice(pair);
}
}
Trade-offs
| Oracle | Decentralization | Cost | Latency | Security |
|---|---|---|---|---|
| Chainlink | High | High | Medium | High |
| Band Protocol | High | Medium | Low | High |
| TWAP | Low | Very Low | High | Medium |
| Custom | Low | Low | Variable | Variable |
Real-World Example: Aave Price Oracle
Aave uses Chainlink for price feeds with fallback mechanisms:
// Simplified Aave Oracle
contract AaveOracle {
mapping(bytes32 => address) public priceFeeds;
function getAssetPrice(address asset) external view returns (uint256) {
address feed = priceFeeds[asset];
require(feed != address(0), "No price feed");
(, int256 price, , uint256 updatedAt, ) = AggregatorV3Interface(feed).latestRoundData();
require(block.timestamp - updatedAt < 3600, "Stale price");
require(price > 0, "Invalid price");
return uint256(price);
}
function getAssetsPrices(
address[] calldata assets
) external view returns (uint256[] memory) {
uint256[] memory prices = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
prices[i] = getAssetPrice(assets[i]);
}
return prices;
}
}
Interview Questions
-
Explain the difference between synchronous and asynchronous oracle patterns. When would you use each?
-
How does Chainlink VRF ensure randomness that cannot be predicted or manipulated by miners?
-
Design a multi-oracle system that aggregates prices from 5 different sources with outlier detection and fallback mechanisms.
Quiz Questions
-
What is the purpose of TWAP (Time-Weighted Average Price) in DeFi?
- A) Provide instant price data
- B) Prevent flash loan attacks
- C) Reduce oracle costs
- D) Increase transaction speed
-
Which Chainlink service provides verifiable randomness for smart contracts?
- A) Price Feeds
- B) VRF
- C) Automation
- D) Data Feeds
-
What is the primary purpose of a circuit breaker in oracle systems?
- A) Increase gas efficiency
- B) Prevent price manipulation
- C) Reduce latency
- D) Improve decentralization