Logo

dev-resources.site

for different kinds of informations.

How to publish data on-chain with Chainlink?

Published at
2/7/2023
Categories
solidity
chainlink
web3
api
Author
CP
Categories
4 categories in total
solidity
open
chainlink
open
web3
open
api
open
How to publish data on-chain with Chainlink?

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:

  1. Specify the validator contract address, (Chainlink's) LINK token contract address, and a jobId.
  2. Construct your API call in the Chainlink request object.
  3. 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:

  1. 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

  2. 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"
);
  1. 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"
        )
     );

    ......
  1. 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}}
  1. There is one required param missing from the example, which you need to add before sending the request:
    req.addInt("multiply", 1);
  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

  2. Remember, you need to send LINK tokens to the smart contract you deployed, otherwise all transactions will fail.

  3. If you encounter other issues, go to Chainlink support Discord to get answers.

ingredients

Here are all the resources that you need:

Featured ones: