Building a Query

In this section, we'll demonstrate how to build an on-chain query using the example of accessing credentials-protected CoinMarketCap price data, as discussed earlier in this documentation.

1. Registering the Request Components

The first step is to register each component of the query separately to create a unique feedID. This involves:

  • HTTPRequest: Specify the method, host, path, headers, and parameters.

  • HTTPPrivatePatch: Include the encrypted API key.

  • JQFilter: Define how to filter and process the response.

  • ResultSchema: Specify the data format (e.g., int256 for integer values).

Each of these components can be registered using the smart contract functions. For example:

uint256 requestId = requestRegistry.addRequest(
 HTTPRequest({
     method: RequestMethod.Get,
     host: "pro-api.coinmarketcap.com",
     path: "/v2/cryptocurrency/quotes/latest",
     headers: new RequestHeader,
     parameters: [QueryParameter({key: "id", value: "1"})]
 })
);

uint256 patchId = requestRegistry.addPrivatePatch(
HTTPPrivatePatch({
headers : [RequestHeaderPatch({key : "X-CMC_PRO_API_KEY", ciphertext : "encrypted_api_key_here"})],
parameters : new QueryParameterPatch,
path_suffix : "",
body : ""
})
);

uint256 filterId = requestRegistry.addJqFilter(".data[\"1\"].quote.USD.price * 1000000 | round");
uint256 schemaId = requestRegistry.addResultSchema("int256");

2. Saving the feedID

Once the request components are registered, the feedID is generated by saving the combined request components:

uint256 feedId = requestRegistry.saveFeedId(requestId, patchId, filterId, schemaId);

3. Querying the Oracle

To query your request to the oracle, use the queryOracle function with the following parameters:

   uint256 queryId = requestProxy.queryOracle(
    feedId,
    logContractAddress,
    callbackAddress,
    callbackSignature
);
  • feedId: The unique identifier for the registered query components, specifying the data source and processing instructions. We've demonstrated how to calculate the feedId value in the previous section

  • logContractAddress: A hardcoded value obtained from public sources, based on the network you're using and the log type (ILog for general data or ILog32 for fixed-width integer data).

  • callbackAddress: The address of the contract where the callback function will be executed after data retrieval.

  • callbackSignature: The function selector for the callback function, indicating which function to call with the retrieved data.

This function triggers the off-chain execution flow, sending the query details to the TEE for processing. The signed response is then returned on-chain by our oracle network and verified within the smart contract, ensuring it comes from a secure source and that no incorrect data can be saved in the data log.

Last updated