The following is an example of a smart contract using Chainlink.Request
to make a call to a Covalent API pricing endpoint. This example is adapted from the one found on Chainlink’s docs - refer to this in order to get details of the contract setup.
The process is as follows:
oracle
address and jobId
and fee
. In the example below, we are using a Get > Uint256 node on the Kovan testnet to get pricing data in Uint256.oracle
node address, jobId
and fee
in the constructor.request.add(...)
path
string array as shownaddress
.address
some LINK tokens. You can find a list of LINK testnet faucets here.getETHPrice()
methodprice
variable to get the ETH price in the smart contract fetched via the Covalent API!Example smart contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
contract CovalentAPIConsumer is ChainlinkClient {
using Chainlink for Chainlink.Request;
uint256 public price;
address private oracle;
bytes32 private jobId;
uint256 private fee;
/**
* Network: Kovan
* Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink Devrel
* Node)
* Job ID: d5270d1c311941d0b08bead21fea7747
* Fee: 0.1 LINK
*/
constructor() {
setPublicChainlinkToken();
oracle = 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8;
jobId = "d5270d1c311941d0b08bead21fea7747";
fee = 0.1 * 10 ** 18; // (Varies by network and job)
}
function getETHPrice() public returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request using the Covalent API
request.add("get", "<https://api.covalenthq.com/v1/pricing/tickers/?quote-currency=USD&format=JSON&tickers=ETH&key=ckey_docs>");
/* The response looks like:
data: {
items: [
{
...
quote_rate: 3101.778,
...
}
*/
string[] memory path = new string[](4);
path[0] = "data";
path[1] = "items";
path[2] = "0";
path[3] = "quote_rate";
request.addStringArray("path", path);
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId)
{
price = _price;
}
// function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract
}