TL;DR:
All that you need to fetch a response from an API endpoint and publish it on-chain using Chainlink.
Recipe
How does it work?
Q. How do you read off-chain data on-chain?
A. Write it to a state variable on-chain!
Here is the workflow:
In the smart contract, you'll need to:
- Specify the validator contract address, (Chainlink's) LINK token contract address, and a
jobId
. - Construct your API call in the Chainlink request object.
- Store the data in the callback function--after the validator fetches the GET request response, it will call the smart contract's callback function with the value, and remember to save that value to a state where you can query later.
Here are the steps:
Write a Solidity smart contract that saves your data in a state variable. Here is a boilerplate smart contract you can copy from the Chainlink tutorial
Replace the API url in the following line of code:
// Set the URL to perform the GET request on
req.add(
"get",
"https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD"
);
- If you need to pass in params, pass them in the function and construct the URL accordingly. Here is an example using the boilerplate code above:
function requestVolumeData(string memory _fsymbol) public returns (bytes32 requestId) {
Chainlink.Request memory req = buildChainlinkRequest(
jobId,
address(this),
this.fulfill.selector
);
// Set the URL to perform the GET request on
req.add(
"get",
abi.encodePacked(
"https://min-api.cryptocompare.com/data/pricemultifull?fsyms=",
_fsymbol,
"&tsyms=USD"
)
);
......
- If the API response returns a JSON object (most likely). Define the path of the data in the response.
req.add("path", "data,total"); // {data: {total: 123}}
- There is one required param missing from the example, which you need to add before sending the request:
req.addInt("multiply", 1);
If the Goerli testnet validator from Chainlink does not work, try to use this node validator: https://github.com/oraclelabs-link/chainlink-node-public-jobs/tree/master/ethereum-goerli
Remember, you need to send LINK tokens to the smart contract you deployed, otherwise all transactions will fail.
If you encounter other issues, go to Chainlink support Discord to get answers.
ingredients
Here are all the resources that you need:
Top comments (0)