Logo

Recursive Queries

Updating a Variable Every n Seconds

Using scheduled queries and a trick in __callback method, one can inject a changing data every n seconds, repetitively which is called recursive queries. This method is useful for implementing periodic updates of on-chain reference data such as a cryptocurrency price or checking an off-chain condition, regularly. Using a new call in __callback method will be result in implementing recursive queries.

Notice: Recursive queries should be used cautiously, as the contract will pay to the oracle every time that sends a new query. Therefore it is recommended to use purposeful queries.

In the following example if send_query function is executed for the first time, after that as long as the contract has enough fund to pay for Bridge fee, BTC/EUR exchange rate will be updated in res variable every 60 seconds.

pragma solidity ^0.5.9;
import "./BridgePublicAPI.sol";
contract BTCprice is BridgePublicAPI {
function send_query(uint256 delay_time) public {
bridge_query(delay_time, "URL", "json(https://www.therocktrading.com/api/ticker/BTCEUR).result.0.last");
}
string public res;
event btcPrice(string _price);
function __callback(bytes32 _myid, string memory _result) public {
require(msg.sender == oracle_cbAddress());
res = _result;
emit btcPrice(_result);
send_query(60);
}
}