Loading...
Hello, World!
Today we are going to look into another application provided by the chainlink that is How can we get data from public API in a smart contract . This smart book is gonna very interesting as this related to the api . In this smart book we are gonna to cover the basic defination of the API , JOBS , HOW THE API GET FETCH , AND finallly we understand the CODE .
API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.
for example every time we use the app like instagram or any news app , weather app etc all these app's are setup on the api itshelf.
The request and receive cycle describes how a smart contract requests data from an oracle and receives the response in a separate transaction. If you need a refresher, check out the Basic Request Model.
For contract that uses like VRF random and the data feed all these send the request to the oracle cloud and then wait for thr transcation . The fulfillment function is already given to us from the VRFConsumerBase contract, so oracles already know where to send the response to. However, with API calls, the contract itself defines which function it wants to receive the response to.
Before moving forward its important to understand what are Jobs .
Chainlink nodes require Jobs to do anything useful.Whenever we request something through the chainlink oracle basically we are requesting that thing through a chainlink jobs. In simple Jobs basically defines when , how , why , etc chainlink nodes need to do .
To read in depth about the Jobs you can read the official docs published on the Chainlink https://docs.chain.link/docs/advanced-tutorial/
Before going through the code lets understand the basic what is all about our smart contract code is . The code is all about to get the ETH/USD Volume price for a 24 hours chart timeline . So for fetching this we need the api of the currency provided by the chainlink which we request from that api to get the voulme of the particular currency via chainlink Jobs .
{"RAW":
{"ETH":
{"USD":
{
...,
"VOLUMEDAYTO":953806939.7194247,
"VOLUME24HOUR":703946.0675653099,
"VOLUME24HOURTO":1265826345.488568
...,
}
}
}
}
The above is basically HTTP GET result for the ETH/USD , in this we want only VOLUME 24 HOUR which can be obtained by adding path to " RAW,ETH,USD,VOLUME24HOUR " .
Now lets see the code for the API
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@chainlink/contracts/src/v0.8/ChainlinkClient.sol';
import '@chainlink/contracts/src/v0.8/ConfirmedOwner.sol';
/**
* Request testnet LINK and ETH here: https://faucets.chain.link/
* Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/
*/
/**
* THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY.
* PLEASE DO NOT USE THIS CODE IN PRODUCTION.
*/
contract APIConsumer is ChainlinkClient, ConfirmedOwner {
using Chainlink for Chainlink.Request;
uint256 public volume;
bytes32 private jobId;
uint256 private fee;
event RequestVolume(bytes32 indexed requestId, uint256 volume);
/**
* @notice Initialize the link token and target oracle
*
* Rinkeby Testnet details:
* Link Token: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709
* Oracle: 0xf3FBB7f3391F62C8fe53f89B41dFC8159EE9653f (Chainlink DevRel)
* jobId: ca98366cc7314957b8c012c72f05aeeb
*
*/
constructor() ConfirmedOwner(msg.sender) {
setChainlinkToken(0x01BE23585060835E02B77ef475b0Cc51aA1e0709);
setChainlinkOracle(0xf3FBB7f3391F62C8fe53f89B41dFC8159EE9653f);
jobId = 'ca98366cc7314957b8c012c72f05aeeb';
fee = (1 * LINK_DIVISIBILITY) / 10; // 0,1 * 10**18 (Varies by network and job)
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
*/
function requestVolumeData() 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', 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD');
// Set the path to find the desired data in the API response, where the response format is:
// {"RAW":
// {"ETH":
// {"USD":
// {
// "VOLUME24HOUR": xxx.xxx,
// }
// }
// }
// }
// request.add("path", "RAW.ETH.USD.VOLUME24HOUR"); // Chainlink nodes prior to 1.0.0 support this format
req.add('path', 'RAW,ETH,USD,VOLUME24HOUR'); // Chainlink nodes 1.0.0 and later support this format
// Multiply the result by 1000000000000000000 to remove decimals
int256 timesAmount = 10**18;
req.addInt('times', timesAmount);
// Sends the request
return sendChainlinkRequest(req, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId) {
emit RequestVolume(_requestId, _volume);
volume = _volume;
}
/**
* Allow withdraw of Link tokens from the contract
*/
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), 'Unable to transfer');
}
}
NOTE : in this we are using the Rinkeby token , Oracle id , Job id these all are avialable on the chainlink market place .
Where is the api in this code ?
https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD
This the api of the ETH/USD using in our code with the get parametre .
Here is a breakdown of each component of this contract:
Note: The calling contract should own enough LINK to pay the fee, which by default is 0.1 LINK. You can use this tutorial to learn how to fund your contract. To get the link in the smart contract watch this video ---> , VIDEO
You can also make the tweet by using the twitter api , Connect a Tesla Vehicle API to a Smart Contract , OAuth and API Authentication in Smart Contracts and there are many more things to see in the API to get the full depth knowledge refer the documentation published on the chainlink provied below