Oracles enable smart contracts to incorporate off-chain data intheir execution and push information from a blockchain to external systems.The oracle pattern employs an external call to another service smart contract(data source) to register the request for off-chain data. This registration callinformation should also be kept in bookkeeping variables inside the contractitself. When the data is ready in the service contract, it will inform the maincontract about the result by calling a specific callback function. To model this,the callback function of the smart contract is excluded by default and is includedwhen the smart contract calls an oracle.
The activities and relations DCR model of this pattern is reflecting the following Solidity contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOracleService {
function requestData() external;
function getResult() external view returns (string memory);
}
contract Oracle {
address public oracleServiceAddress;
string public data;
bool public isDataReady = false;
constructor(address _oracleServiceAddress) {
oracleServiceAddress = _oracleServiceAddress;
}
function requestOffChainData() public {
IOracleService(oracleServiceAddress).requestData();
// Bookkeeping: Registration call information
isDataReady = false;
}
function callback(string memory _data) public {
require(msg.sender == oracleServiceAddress, "Only the Oracle Service can call this function");
data = _data;
isDataReady = true;
}
}
The Oracle contract interacts with an external Oracle Service (represented by the IOracleService
interface). The main contract (Oracle) can request off-chain data by calling the requestOffChainData
function. This function, in turn, calls the requestData
function of the Oracle Service. The Oracle Service, when it has the data ready, will call the callback
function of the main contract to provide the data. The isDataReady
variable acts as a bookkeeping variable to keep track of whether the data is ready or not.
Here, as it is demonstrated by the model in the next section, the only role able to call the callback
function is the oracle.