Return Custom Data Types
In this tutorial, you 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 several responses to your smart contract. The response includes an asset price, daily volume, and market name to your smart contract. The example uses query parameters to specify the ETH/USD asset pair, but you can configure HTTP query parameters to make requests for different assets.
Before you begin
-
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.
-
Make sure your subscription has enough LINK to pay for your requests. You can check your subscription details (including the balance in LINK) in the Chainlink Functions frontend. If your subscription runs out of LINK, follow the Fund a Subscription guide.
-
You can locate the scripts used in this tutorial in the examples/3-custom-response directory.
Tutorial
This tutorial is configured to get the ETH/USD
, daily volume, and market in a single request. For a detailed explanation of the code example, read the Examine the code section.
To run the example:
-
Open the file
request.js
, which is located in the3-custom-response
folder. -
Replace the consumer contract address and the subscription ID with your own values.
const consumerAddress = "0x8dFf78B7EE3128D00E90611FBeD20A71397064D9" // REPLACE this with your Functions consumer address const subscriptionId = 3 // REPLACE this with your subscription ID
-
Make a request:
node examples/3-custom-response/request.js
The script runs your function in a sandbox environment before making an on-chain transaction:
$ node examples/3-custom-response/request.js secp256k1 unavailable, reverting to browser version Start simulation... Performing simulation with the following versions: deno 1.36.3 (release, aarch64-apple-darwin) v8 11.6.189.12 typescript 5.1.6 Simulation result { capturedTerminalOutput: 'HTTP GET Request to https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD\n' + 'ETH price is: 1632.14 USD. 24h Volume is 57645.66 USD. Market: Kraken\n', responseBytesHexstring: '0x7b227072696365223a22313633322e3134222c22766f6c756d65223a2235373634352e3636222c226c6173744d61726b6574223a224b72616b656e227d' } ✅ Decoded response to string: {"price":"1632.14","volume":"57645.66","lastMarket":"Kraken"} Estimate request costs... Duplicate definition of Transfer (Transfer(address,address,uint256,bytes), Transfer(address,address,uint256)) Fulfillment cost estimated to 0.000000000000215 LINK Make request... ✅ Functions request sent! Transaction hash 0x99b70944262ff2f0f8c4c98eaa9927c3519267522fd82d5442a5cfcc6cf913d4 - Request id is 0x121db06a58c4646ca9282520b6a526d83bf84831647bb2c7fc99e36cbd343aa4. Waiting for a response... See your request in the explorer https://mumbai.polygonscan.com/tx/0x99b70944262ff2f0f8c4c98eaa9927c3519267522fd82d5442a5cfcc6cf913d4 ✅ Request 0x121db06a58c4646ca9282520b6a526d83bf84831647bb2c7fc99e36cbd343aa4 fulfilled with code: 0. Cost is 0.00003809801507364 LINK. Complete response: { requestId: '0x121db06a58c4646ca9282520b6a526d83bf84831647bb2c7fc99e36cbd343aa4', subscriptionId: 3, totalCostInJuels: 38098015073640n, responseBytesHexstring: '0x7b227072696365223a22313633322e3634222c22766f6c756d65223a2235373637332e3336222c226c6173744d61726b6574223a224269747374616d70227d', errorString: '', returnDataBytesHexstring: '0x', fulfillmentCode: 0 } ✅ Decoded response to string: {"price":"1632.64","volume":"57673.36","lastMarket":"Bitstamp"}
The output of the example gives you the following information:
-
Your request is first run on a sandbox environment to ensure it is correctly configured.
-
The fulfillment costs are estimated before making the request.
-
Your request was successfully sent to Chainlink Functions. The transaction in this example is 0x99b70944262ff2f0f8c4c98eaa9927c3519267522fd82d5442a5cfcc6cf913d4 and the request ID is
0x121db06a58c4646ca9282520b6a526d83bf84831647bb2c7fc99e36cbd343aa4
. -
The DON successfully fulfilled your request. The total cost was:
0.00003809801507364 LINK
. -
The consumer contract received a response in
bytes
with a value of0x7b227072696365223a22313633322e3634222c22766f6c756d65223a2235373637332e3336222c226c6173744d61726b6574223a224269747374616d70227d
. Decoding it off-chain tostring
gives you a result:{"price":"1632.64","volume":"57673.36","lastMarket":"Bitstamp"}
-
Examine the code
FunctionsConsumerExample.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {FunctionsClient} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/FunctionsClient.sol";
import {ConfirmedOwner} from "@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/libraries/FunctionsRequest.sol";
/**
* THIS IS AN EXAMPLE CONTRACT THAT USES HARDCODED VALUES FOR CLARITY.
* THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE.
* DO NOT USE THIS CODE IN PRODUCTION.
*/
contract FunctionsConsumerExample is FunctionsClient, ConfirmedOwner {
using FunctionsRequest for FunctionsRequest.Request;
bytes32 public s_lastRequestId;
bytes public s_lastResponse;
bytes public s_lastError;
error UnexpectedRequestID(bytes32 requestId);
event Response(bytes32 indexed requestId, bytes response, bytes err);
constructor(
address router
) FunctionsClient(router) ConfirmedOwner(msg.sender) {}
/**
* @notice Send a simple request
* @param source JavaScript source code
* @param encryptedSecretsUrls Encrypted URLs where to fetch user secrets
* @param donHostedSecretsSlotID Don hosted secrets slotId
* @param donHostedSecretsVersion Don hosted secrets version
* @param args List of arguments accessible from within the source code
* @param bytesArgs Array of bytes arguments, represented as hex strings
* @param subscriptionId Billing ID
*/
function sendRequest(
string memory source,
bytes memory encryptedSecretsUrls,
uint8 donHostedSecretsSlotID,
uint64 donHostedSecretsVersion,
string[] memory args,
bytes[] memory bytesArgs,
uint64 subscriptionId,
uint32 gasLimit,
bytes32 jobId
) external onlyOwner returns (bytes32 requestId) {
FunctionsRequest.Request memory req;
req.initializeRequestForInlineJavaScript(source);
if (encryptedSecretsUrls.length > 0)
req.addSecretsReference(encryptedSecretsUrls);
else if (donHostedSecretsVersion > 0) {
req.addDONHostedSecrets(
donHostedSecretsSlotID,
donHostedSecretsVersion
);
}
if (args.length > 0) req.setArgs(args);
if (bytesArgs.length > 0) req.setBytesArgs(bytesArgs);
s_lastRequestId = _sendRequest(
req.encodeCBOR(),
subscriptionId,
gasLimit,
jobId
);
return s_lastRequestId;
}
/**
* @notice Send a pre-encoded CBOR request
* @param request CBOR-encoded request data
* @param subscriptionId Billing ID
* @param gasLimit The maximum amount of gas the request can consume
* @param jobId ID of the job to be invoked
* @return requestId The ID of the sent request
*/
function sendRequestCBOR(
bytes memory request,
uint64 subscriptionId,
uint32 gasLimit,
bytes32 jobId
) external onlyOwner returns (bytes32 requestId) {
s_lastRequestId = _sendRequest(
request,
subscriptionId,
gasLimit,
jobId
);
return s_lastRequestId;
}
/**
* @notice Store latest result/error
* @param requestId The request ID, returned by sendRequest()
* @param response Aggregated response from the user code
* @param err Aggregated error from the user code or from the execution pipeline
* Either response or error parameter will be set, but never both
*/
function fulfillRequest(
bytes32 requestId,
bytes memory response,
bytes memory err
) internal override {
if (s_lastRequestId != requestId) {
revert UnexpectedRequestID(requestId);
}
s_lastResponse = response;
s_lastError = err;
emit Response(requestId, s_lastResponse, s_lastError);
}
}
-
To write a Chainlink Functions consumer contract, your contract must import FunctionsClient.sol and FunctionsRequest.sol. You can read the API references: FunctionsClient and FunctionsRequest.
These contracts are available in an NPM package, so you can import them from within your project.
import {FunctionsClient} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/FunctionsClient.sol"; import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/libraries/FunctionsRequest.sol";
-
Use the FunctionsRequest.sol library to get all the functions needed for building a Chainlink Functions request.
using FunctionsRequest for FunctionsRequest.Request;
-
The latest request id, latest received response, and latest received error (if any) are defined as state variables:
bytes32 public s_lastRequestId; bytes public s_lastResponse; bytes public s_lastError;
-
We define the
Response
event that your smart contract will emit during the callbackevent Response(bytes32 indexed requestId, bytes response, bytes err);
-
Pass the router address for your network when you deploy the contract:
constructor(address router) FunctionsClient(router)
-
The three remaining functions are:
-
sendRequest
for sending a request. It receives the JavaScript source code, encrypted secretsUrls (in case the encrypted secrets are hosted by the user), DON hosted secrets slot id and version (in case the encrypted secrets are hosted by the DON), list of arguments to pass to the source code, subscription id, and callback gas limit as parameters. Then:-
It uses the
FunctionsRequest
library to initialize the request and add any passed encrypted secrets reference or arguments. You can read the API Reference for Initializing a request, adding user hosted secrets, adding DON hosted secrets, adding arguments, and adding bytes arguments.FunctionsRequest.Request memory req; req.initializeRequestForInlineJavaScript(source); if (encryptedSecretsUrls.length > 0) req.addSecretsReference(encryptedSecretsUrls); else if (donHostedSecretsVersion > 0) { req.addDONHostedSecrets( donHostedSecretsSlotID, donHostedSecretsVersion ); } if (args.length > 0) req.setArgs(args); if (bytesArgs.length > 0) req.setBytesArgs(bytesArgs);
-
It sends the request to the router by calling the
FunctionsClient
sendRequest
function. You can read the API reference for sending a request. Finally, it stores the request id ins_lastRequestId
then return it.s_lastRequestId = _sendRequest( req.encodeCBOR(), subscriptionId, gasLimit, jobId ); return s_lastRequestId;
Note:
_sendRequest
accepts requests encoded inbytes
. Therefore, you must encode it using encodeCBOR.
-
-
sendRequestCBOR
for sending a request already encoded inbytes
. It receives the request object encoded inbytes
, subscription id, and callback gas limit as parameters. Then, it sends the request to the router by calling theFunctionsClient
sendRequest
function. Note: This function is helpful if you want to encode a request off-chain before sending it, saving gas when submitting the request.
-
-
fulfillRequest
to be invoked during the callback. This function is defined inFunctionsClient
asvirtual
(readfulfillRequest
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 ins_lastResponse
ands_lastError
before emitting theResponse
event.s_lastResponse = response; s_lastError = err; emit Response(requestId, s_lastResponse, s_lastError);
JavaScript example
source.js
The Decentralized Oracle Network will run the JavaScript code. The code is self-explanatory and has comments to help you understand all the steps. Note: The custom source code you want to execute in a Functions request can use vanilla deno but cannot use any require statements or imported modules.
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 }
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
, the volume is at RAW,ETH,USD,VOLUME24HOUR
, and the market is at RAW,ETH,USD,LASTMARKET
.
The main steps of the scripts are:
-
Fetch
fromSymbol
andtoSymbol
fromargs
. -
Construct the HTTP object
cryptoCompareRequest
usingFunctions.makeHttpRequest
. -
Make the HTTP call.
-
Read the asset price, daily volume, and market from the response.
-
Construct a JSON object.
const result = { price: price.toFixed(2), volume: volume.toFixed(2), lastMarket, }
-
Convert the JSON object to a JSON string using
JSON.stringify(result)
. This step is mandatory before encodingstring
tobytes
. -
Return the result as a buffer using the
Functions.string
helper function. Note: Read this article if you are new to Javascript Buffers and want to understand why they are important.
request.js
This explanation focuses on the request.js script and shows how to use the Chainlink Functions NPM package in your own JavaScript/TypeScript project to send requests to a DON. The code is self-explanatory and has comments to help you understand all the steps.
The script imports:
- path and fs : Used to read the source file.
- ethers: Ethers.js library, enables the script to interact with the blockchain.
@chainlink/functions-toolkit
: Chainlink Functions NPM package. All its utilities are documented in the NPM README.@chainlink/env-enc
: A tool for loading and storing encrypted environment variables. Read the official documentation to learn more.../abi/functionsClient.json
: The abi of the contract your script will interact with. Note: The script was tested with this FunctionsConsumerExample contract.
The script has two hardcoded values that you have to change using your own Functions consumer contract and subscription ID:
const consumerAddress = "0x8dFf78B7EE3128D00E90611FBeD20A71397064D9" // REPLACE this with your Functions consumer address
const subscriptionId = 3 // REPLACE this with your subscription ID
The primary function that the script executes is makeRequestMumbai
. This function can be broken into five main parts:
-
Definition of necessary identifiers:
routerAddress
: Chainlink Functions router address on Polygon Mumbai.donId
: Identifier of the DON that will fulfill your requests on Polygon Mumbai.explorerUrl
: Block explorer url of Polygon Mumbai.source
: The source code must be a string object. That's why we usefs.readFileSync
to readsource.js
and then calltoString()
to get the content as astring
object.args
: During the execution of your function, These arguments are passed to the source code. Theargs
value is["ETH", "USD"]
, which fetches the currentETH/USD
price. You can adaptargs
to fetch another asset price. See the CryptoCompare API docs to get the list of supported symbols.gasLimit
: Maximum gas that Chainlink Functions can use when transmitting the response to your contract.- Initialization of ethers
signer
andprovider
objects. The signer is used to make transactions on the blockchain, and the provider reads data from the blockchain.
-
Simulating your request in a local sandbox environment:
- Use
simulateScript
from the Chainlink Functions NPM package. - Read the
response
of the simulation. If successful, use the Functions NPM packagedecodeResult
function andReturnType
enum to decode the response to the expected returned type (ReturnType.string
in this example).
- Use
-
Estimating the costs:
- Initialize a
SubscriptionManager
from the Functions NPM package, then call theestimateFunctionsRequestCost
. - The response is returned in Juels (1 LINK = 10**18 Juels). Use the
ethers.utils.formatEther
utility function to convert the output to LINK.
- Initialize a
-
Making a Chainlink Functions request:
- Initialize your functions consumer contract using the contract address, abi, and ethers signer.
- Make a static call to the
sendRequest
function of your consumer contract to return the request ID that Chainlink Functions will generate. - Call the
sendRequest
function of your consumer contract.
-
Waiting for the response:
- Initialize a
ResponseListener
from the Functions NPM package and then call thelistenForResponse
function to wait for a response. By default, this function waits for five minutes. - Upon reception of the response, use the Functions NPM package
decodeResult
function andReturnType
enum to decode the response to the expected returned type (ReturnType.string
in this example).
- Initialize a