NEW

CCIP is now available on testnet for all developers. Get started today.

Call an API with HTTP Query Parameters

This tutorial shows you how to send a request to a Decentralized Oracle Network to call the Cryptocompare GET /data/pricemultifull API. After OCR completes off-chain computation and aggregation, it returns the asset price for ETH/USD to your smart contract. This guide also shows you how to configure HTTP query parameters to request different asset prices.

Before you begin

  1. Complete the setup steps in the Getting Started guide: The Getting Started Guide shows you how to set up your environment with the necessary tools for these tutorials. You can re-use the same consumer contract for each of these tutorials.

  2. Make sure your subscription has enough LINK to pay for your requests. Read Get Subscription details to learn how to check your subscription balance. If your subscription runs out of LINK, follow the Fund a Subscription guide.

  3. Check out the tutorials branch of the Chainlink Functions Starter Kit. You can locate this tutorial in the /tutorials/2-call-api directory.

    git checkout tutorials

Tutorial

This tutorial is configured to get the ETH/USD price. For a detailed explanation of the code example, read the Explanation section.

  • Open config.js. The args value is ["ETH", "USD"], which fetches the current ETH/USD price. You can adapt args to fetch another asset price. See the CryptoCompare API docs to get the list of supported symbols. Read the request config explanation for a more detailed explanation about the request config file.
  • Open source.js to analyze the JavaScript source code. Read the source code explanation for a more detailed explanation.

Simulation

The Chainlink Functions Hardhat Starter Kit includes a simulator to test your Functions code on your local machine. The functions-simulate command executes your code in a local runtime environment and simulates an end-to-end fulfillment. This helps you to fix any issues before you submit your functions to a Decentralized Oracle Network.

Run the functions-simulate task to run the source code locally and make sure config.js and source.js are correctly written:

npx hardhat functions-simulate --configpath REPLACE_CONFIG_PATH

Example:

$ npx hardhat functions-simulate --configpath tutorials/2-call-api/config.js
secp256k1 unavailable, reverting to browser version

__Compiling Contracts__
Nothing to compile
Duplicate definition of Transfer (Transfer(address,address,uint256,bytes), Transfer(address,address,uint256))

Executing JavaScript request source code locally...

__Console log messages from sandboxed code__
HTTP GET Request to https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD
ETH price is: 1813.50 USD

__Output from sandboxed source code__
Output represented as a hex string: 0x000000000000000000000000000000000000000000000000000000000002c466
Decoded as a uint256: 181350

__Simulated On-Chain Response__
Response returned to client contract represented as a hex string: 0x000000000000000000000000000000000000000000000000000000000002c466
Decoded as a uint256: 181350

Gas used by sendRequest: 367881
Gas used by client callback function: 75029

Reading the output of the example above, you can see that the ETH/USD price is: 1813.50 USD. Because Solidity does not support decimals, we move the decimal point so that the value looks like an integer 181350 before returning the bytes encoded value 0x000000000000000000000000000000000000000000000000000000000002c466 in the callback. Read the source code explanation for more information about the source code.

Request

Send a request to the Decentralized Oracle Network to fetch the asset price. Run the functions-request task with the subid (subscription ID) and contract parameters. This task passes the functions JavaScript source code, arguments, and secrets to the executeRequest function in your deployed FunctionsConsumer contract. Read the functionsConsumer section for more information about the consumer contract.

npx hardhat functions-request --subid REPLACE_SUBSCRIPTION_ID --contract REPLACE_CONSUMER_CONTRACT_ADDRESS --network REPLACE_NETWORK --configpath REPLACE_CONFIG_PATH

Example:

$ npx hardhat functions-request --subid 443 --contract 0x4B4BA2Fd6b93aDF8d6b6002E10540E58394388Ea --network polygonMumbai --configpath tutorials/2-call-api/config.js
secp256k1 unavailable, reverting to browser version
Estimating cost if the current gas price remains the same...

The transaction to initiate this request will charge the wallet (0x9d087fC03ae39b088326b67fA3C788236645b717):
0.000496339505294288 MATIC, which (using mainnet value) is $0.0005516547067031669

If the request's callback uses all 100,000 gas, this request will charge the subscription:
0.200148503810857266 LINK

Continue? Enter (y) Yes / (n) No
y
Simulating Functions request locally...

__Console log messages from sandboxed code__
HTTP GET Request to https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD
ETH price is: 1813.96 USD

__Output from sandboxed source code__
Output represented as a hex string: 0x000000000000000000000000000000000000000000000000000000000002c494
Decoded as a uint256: 181396

⣾ Request 0x5e89f3e84cbf80d65de53de816052d1b79c50c1f1f9f283aadc3ad36d33d41aa has been initiated. Waiting for fulfillment from the Decentralized Oracle Network...

ℹ Transaction confirmed, see https://mumbai.polygonscan.com/tx/0x36029c2e49d0d890d00a1b554e4bea564444e48c5449f9d5deaed5d42114d91e for more details.

✔ Request 0x5e89f3e84cbf80d65de53de816052d1b79c50c1f1f9f283aadc3ad36d33d41aa fulfilled! Data has been written on-chain.

Response returned to client contract represented as a hex string: 0x000000000000000000000000000000000000000000000000000000000002c48b
Decoded as a uint256: 181387

Actual amount billed to subscription #443:
┌──────────────────────┬─────────────────────────────┐
│         Type         │           Amount            │
├──────────────────────┼─────────────────────────────┤
│  Transmission cost:  │  0.000063268449037502 LINK  │
│      Base fee:       │          0.2 LINK           │
│                      │                             │
│     Total cost:      │  0.200063268449037502 LINK  │
└──────────────────────┴─────────────────────────────┘

The output of the example above gives you the following information:

  • The executeRequest function was successfully called in the FunctionsConsumer contract. The transaction in this example is 0x36029c2e49d0d890d00a1b554e4bea564444e48c5449f9d5deaed5d42114d91e.
  • The request ID is 0x5e89f3e84cbf80d65de53de816052d1b79c50c1f1f9f283aadc3ad36d33d41aa.
  • The DON successfully fulfilled your request. The total cost was: 0.200063268449037502 LINK.
  • The consumer contract received a response in bytes with a value of 0x000000000000000000000000000000000000000000000000000000000002c48b. Decoding it off-chain to a uint256 gives you a result: 181387.

At any time, you can run the functions-read task again with the contract parameter to read the latest received response.

npx hardhat functions-read  --contract REPLACE_CONSUMER_CONTRACT_ADDRESS --network REPLACE_NETWORK --configpath REPLACE_CONFIG_PATH

Example:

$ npx hardhat functions-read  --contract 0x4B4BA2Fd6b93aDF8d6b6002E10540E58394388Ea  --network polygonMumbai --configpath tutorials/2-call-api/config.js
secp256k1 unavailable, reverting to browser version
Reading data from Functions client contract 0x4B4BA2Fd6b93aDF8d6b6002E10540E58394388Ea on network mumbai

On-chain response represented as a hex string: 0x000000000000000000000000000000000000000000000000000000000002c48b
Decoded as a uint256: 181387

Explanation

FunctionsConsumer.sol

  • To write a Chainlink Functions consumer contract, your contract must import FunctionsClient.sol. You can read the API reference: FunctionsClient.

    This contract is not available in an NPM package, so you must download and import it from within your project.

    import {Functions, FunctionsClient} from "./dev/functions/FunctionsClient.sol";
  • Use the Functions.sol library to get all the functions needed for building a Chainlink Functions request. You can read the API reference: Functions.

    using Functions for Functions.Request;
    
  • The latest request id, latest received response, and latest received error (if any) are defined as state variables. Note latestResponse and latestError are encoded as dynamically sized byte array bytes, so you will still need to decode them to read the response or error:

    bytes32 public latestRequestId;
    bytes public latestResponse;
    bytes public latestError;
  • We define the OCRResponse event that your smart contract will emit during the callback

    event OCRResponse(bytes32 indexed requestId, bytes result, bytes err);
  • Pass the oracle address for your network when you deploy the contract:

    constructor(address oracle) FunctionsClient(oracle)
  • At any time, you can change the oracle address by calling the updateOracleAddress function.

  • The two remaining functions are:

    • executeRequest for sending a request. It receives the JavaScript source code, encrypted secrets, list of arguments to pass to the source code, subscription id, and callback gas limit as parameters. Then:

      • It uses the Functionslibrary to initialize the request and add any passed encrypted secrets or arguments. You can read the API Reference for Initializing a request, adding secrets, and adding arguments.

        Functions.Request memory req;
        req.initializeRequest(Functions.Location.Inline, Functions.CodeLanguage.JavaScript, source);
        if (secrets.length > 0) {
          req.addRemoteSecrets(secrets);
        }
        if (args.length > 0) req.addArgs(args);
      • It sends the request to the oracle by calling the FunctionsClient sendRequest function. You can read the API reference for sending a request. Finally, it stores the request id in latestRequestId.

        bytes32 assignedReqID = sendRequest(req, subscriptionId, gasLimit);
        latestRequestId = assignedReqID;
    • fulfillRequest to be invoked during the callback. This function is defined in FunctionsClient as virtual (read fulfillRequest API reference). So, your smart contract must override the function to implement the callback. The implementation of the callback is straightforward: the contract stores the latest response and error in latestResponse and latestError before emitting the OCRResponse event.

      latestResponse = response;
      latestError = err;
      emit OCRResponse(requestId, response, err);

config.js

Read the Request Configuration section for a detailed description of each setting. In this example, the settings are the following:

  • codeLocation: Location.Inline: The JavaScript code is provided within the request.
  • codeLanguage: CodeLanguage.JavaScript: The source code is developed in the JavaScript language.
  • source: fs.readFileSync(path.resolve(__dirname, "source.js")).toString(): The source code must be a script object. This example uses fs.readFileSync to read source.js and calls toString() to get the content as a string object.
  • args: ["ETH", "USD"]: These arguments are passed to the source code. This example requests the ETH/USD price.
  • expectedReturnType: ReturnType.uint256: The response received by the DON is encoded in bytes. Because the asset price is a uint256, define ReturnType.uint256 to inform users how to decode the response received by the DON.

source.js

To check the expected API response, you can directly paste the following URL in your browser https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD or run the curl command in your terminal:

curl -X 'GET' \
  'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD' \
  -H 'accept: application/json'

The response should be similar to the following example:

{
  "RAW": {
    "ETH": {
      "USD": {
        "TYPE": "5",
        "MARKET": "CCCAGG",
        "FROMSYMBOL": "ETH",
        "TOSYMBOL": "USD",
        "FLAGS": "2049",
        "PRICE": 2867.04,
        "LASTUPDATE": 1650896942,
        "MEDIAN": 2866.2,
        "LASTVOLUME": 0.16533939,
        "LASTVOLUMETO": 474.375243849,
        "LASTTRADEID": "1072154517",
        "VOLUMEDAY": 195241.78281014622,
        "VOLUMEDAYTO": 556240560.4621655,
        "VOLUME24HOUR": 236248.94641103,
        ...
}

The price is located at RAW,ETH,USD,PRICE.

Read the JavaScript code section for a detailed explanation of how to write a compatible JavaScript source code. This JavaScript source code uses Functions.makeHttpRequest to make HTTP requests. To request the ETH/USD price, the source code calls the https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD URL. If you read the Functions.makeHttpRequest documentation, you see that you must provide the following parameters:

  • url: https://min-api.cryptocompare.com/data/pricemultifull

  • params: The query parameters object:

    {
      fsyms: fromSymbol,
      tsyms: toSymbol
    }

The fromSymbol and toSymbol values are fetched from args. See the request config section for more details.

The code is self-explanatory and has comments to help you understand all the steps. The main steps are:

  • Construct the HTTP object cryptoCompareRequest using Functions.makeHttpRequest.
  • Make the HTTP call.
  • Read the asset price from the response.
  • Return the result as a buffer using the Functions.encodeUint256 helper function. Because solidity doesn't support decimals, multiply the result by 100 and round the result to the nearest integer. Note: Read this article if you are new to Javascript Buffers and want to understand why they are important.

Stay updated on the latest Chainlink news