Tutorial To Connect APIs From Ethereum Smart Contracts Using Chainlink Oracles

 

Since Blockchain ecosystems are decentralized, on-chain smart contracts cannot access off-chain data natively. However, Chainlink furnishes a platform for blockchain oracles, which are nodes on the network that serves as a bridge between on-chain & off-chain data. Oracles enable smart contracts to retrieve external data.   

Each oracle node can be configured to perform a vast range of chores relying on the adapters it supports. Some of these adapters include HTTP POST, HTTP GET, JSON Parse, Multiply, etc.  

In this blog, we will explain how one can call Aviationstack.com API from Ethereum smart contracts using Chainlink’s oracle. 

4 Steps To Call Aviationstack.com API From Ethereum Smart Contracts Using Chainlink’s Oracle

Using Chainlink’s Oracles, the latest data can be retrieved by using any REST API call from a smart contract in real-time. The four simple steps stated below will help you know how to call the REST endpoint provided by Aviation Data in Solidity to get real-time flight status, i.e., scheduled, delayed, landed, etc. 

Step 1: Add A Testnet To MetaMask Wallet 

We will use the goerli TestNet for this example.    

  • Open Metamask and then click on the Networks and choose Goerli test network.   
  • In the remix, select Injected provider Metamask to connect to goerli test network.   
  • Before starting development, add some test coins from the test faucet from here. 

Also, get Link tokens from Chainlink’s test faucet.

Chainlink’s test faucet

Step 2: Find The Oracle Address For Your Chain   

From https://docs.chain.link/any-api/testnet-oracles/ get the list of different test net addresses of oracles.  

We are using goerli test net oracle with the address
0xcc79157eb46f5624204f47ab42b3906caa40eab7  

with jobId —7d80a6386ef543a3abb52817f6707e3b 

Whenever we request something through the Chainlink oracle, we request that through Chainlink jobs. Simple jobs define when, how, why, etc., that need to be done via Chainlink nodes. This job id (7d80a6386ef543a3abb52817f6707e3b) describes to the oracle that we need to return the response in a String of other jobs. It returns a response in bool, int256, unit 256, etc. 

Step 3: Add The Code To Your Solidity Smart Contract 

Integrate the following code into your smart contract: 

//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'; 

 

contract UseAviationApi is ChainlinkClient, ConfirmedOwner { 

using Chainlink for Chainlink.Request; 

string public flightStatus; 

 

bytes32 private jobId; 

uint256 private fee; 

 

event RequestFulfilled(bytes32 indexed requestId, string indexed data); 

/** 

* Goerli Testnet details: 

* Link Token: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB 

* Oracle: 0xCC79157eb46F5624204f47AB42b3906cAA40eaB7 

* jobId: 7d80a6386ef543a3abb52817f6707e3b 

*/ 

constructor() ConfirmedOwner(msg.sender) { 

setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB); 

setChainlinkOracle(0xCC79157eb46F5624204f47AB42b3906cAA40eaB7); 

jobId = '7d80a6386ef543a3abb52817f6707e3b'; 

fee = (1 * LINK_DIVISIBILITY) / 10; // 0,1 * 10**18 (Varies by network and job) 

} 

 

/** 

* @notice Request variable bytes from the oracle 

*/ 

function requestFlightStatus() public { 

Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); 

req.add( 

'get', 

'http://api.aviationstack.com/v1/flights?access_key=a6656fabf7fbe4fde6e4061f5be7042a&flight_number=611&airline_name=Qantas&limit=1' //aviationstack url 

); 

req.add('path', 'data,0,flight_status'); // parse the json tree 

sendChainlinkRequest(req, fee);  

} 

 

/** 

* @notice Fulfillment function for variable bytes 

* @dev This is called by the oracle. recordChainlinkFulfillment must be used. 

*/ 

function fulfill(bytes32 requestId, string memory data) public recordChainlinkFulfillment(requestId) { 

emit RequestFulfilled(requestId, data); 

flightStatus = data; 

} 

 

/** 

* 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'); 

} 

}  

Open this code in Gist    

The breakdown of each component of this contract is as follows –   

  1. Constructor: Sets up the contract with the Oracle address, Job ID, and LINK fee that oracle charges for the job  
  2. requestFlightStatus function: Builds and sends a request. The request includes fulfillment functions selector – to the oracle. Notice how it adds the get, path, and parameters. These are read by the tasks in the job to perform correctly. ‘get’ is used by HTTP, and ‘path’ is used by JSON Parse.
  3. fulfill function: This is where the result is sent upon the completion of Oracle’s Job.
  4. WithdrawLink Function: This method is used to withdraw the user’s link token from their smart contract.   

Note: The calling contract should own enough LINK to pay the fee, which by default is 0.1 LINK. 

Step 4: Deploy And Test   

  • Now choose Injected Web3 as your Environment in Remix and deploy your contract to the goerli TestNet.  
  • Next, choose the requestFlightStatus() function, it will then pay the transaction fee, and when the transaction becomes successful, it calls the flightStatus, and the result is displayed as shown below.

Deploy and Test 

Ending Words

Well, if you want to connect APIs from Ethereum smart contracts using chainlink oracles in your existing or new Blockchain-based projects, get in touch with one of the excellent Blockchain development companies (Infrablok). It will help you get a professional who can handle your project from scratch. 

Accessing Real Time Data Using Chainlink Oracles

 

Blockchain and its new cryptocurrencies and chains are becoming popular day by day, making it one of the fastest-growing technologies in the business world. The first chain that came into the market after Bitcoin was Ethereum which brought the concept of “smart contracts.”  

These smart contracts are paving the way for solving various real-world problems in the immutable, decentralized, distributed, yet trustworthy network. It means that Blockchain is no longer fixed for the cryptocurrency market. But it can also be employed to solve realistic problems by setting up terms or agreements in the form of some computation done in smart contracts (written in a programming language).

With this breakthrough, new ideas sprang up that brought solutions to the problems of the centralized world into the decentralized world. But with this, some significant bottlenecks in the advancement of Blockchain came up.    

Before discussing accessing real-time data using Chainlink Oracles, it’s also essential to know the Blockchain technology bottlenecks. By knowing this, you can overcome challenges in less time. 

3 Major Bottlenecks In The Advancement Of Blockchain

Blockchain Oracles Problems

1. Every Transaction In Blockchain Takes Place On Blockchain

Every computation, be that solving a simple calculation from the Blockchain data (called on-chain data) or a complex computation that involves data from the real world (called off-chain data), in real-time, is needed to take place Blockchain itself.  

It means that there had to be a way devised for an isolated system like Blockchain to access not only its on-chain data but also off-chain data. If this is achieved, putting a massive amount of data (off-chain data) on Blockchain would create extremely high levels of redundancy in every system that processes blockchain transactions.   

2. No Relation Between Real World Data & Smart Contracts

There is no link between off-chain data & smart contracts, which means smart contracts could not process any computation related to off-chain data.   

3. Bigger Transaction = Higher Cost

If any real-world problem ought to solve with Blockchain, then data has to be migrated over to Blockchain to solve that transaction, which means more time consumption will lead to a higher transaction (gas) cost.

How To Access Real-Time Data Employing Chainlink Oracles?

To solve the real-world computation off-chain & feed the solution to the on-chain smart contract, some mechanism that can make off-chain data immutable, decentralized, distributed, & secure was required. To make this possible, Chainlink created Oracles and combined them to form a Decentralized Oracles Network (DONs). 

Oracles acted as entities that could connect off-chain data with the Blockchain’s smart contract. Oracles can solve all off-chain computations by preserving all the core fundamentals of Blockchain & acted as a bridge to feed the solution to the Blockchain’s smart contract. 

Additionally, they enabled 2-way communication by creating a communication link between on-chain & off-chain data. It means all high costing computations can now be done off-chain while keeping it immutable, decentralized, distributed, & secure. 

Oracles can achieve this connectivity by interfacing with external APIs & data feeds, allowing them to pull data for or push data from a smart contract. 

Did You Know One Oracle Can Mislay Whole Trustworthiness?

Well, one Oracle could not be called decentralized or distributed as it certainly wasn’t giving immutability. This resulted in a loss of whole trustworthiness as data was received from outside a blockchain network. To feed any data to Blockchain, any system outside the Blockchain must have the same fundamentals. 

Decentralized Oracle Network (DONs) To Maintain Credibility

To maintain trustworthiness, DONs were formed. The DONs is a network where several Blockchain oracles run by independent node operators are selected to retrieve & validate data from multiple off-chain sources. It ultimately helped achieve a Blockchain kind network outside of Blockchain in the real world to process any off-chain data.  

It works as a Blockchain because the oracle nodes of these DONs have a resultant value aggregated to get a single trusted data point fed to the on-chain smart contract for further execution.  

Moreover, the independent network of multiple DONs running simultaneously and independently of each other formed the chainlink network. In simple terms, Chainlink is a decentralized network of Oracles that lets users securely connect off-chain data to on-chain smart contracts & vice versa. 

Know How Users Can Securely Connect Off-Chain Data To On-Chain Smart Contracts & Vice Versa

Here we have given an example that will help you understand the working to know how users can securely connect off-chain data to on-chain smart contracts & vice versa. 

how users can securely connect off-chain data to on-chain smart contracts

Assume there is an insurance company that insures packages delivered across the globe. John visits this company and asks to insure his package that requires to reach its destination in 3 days. In this case, if the package gets delayed due to any reason related to the flight carrier, John gets the claim. But, in case of delivery delays, various checks are done by the insurance company to ensure that the package was not delivered on time due to the lagging of the flight carrier; thus, settlement of the claim becomes a lengthy process. 

To solve the above issue, the insurance company decides to opt for a Blockchain-based solution, & to fetch flight data in real-time, they opt for oracles. This oracle-based insurance company will monitor data coming through oracles via API and transmit the required information to the Blockchain. Then, with the help of smart contracts (based on the preset agreement between the client & company) and oracles, the Blockchain will determine if the events are occurring as per the preset agreement or not through consensus.

Smart contracts will then control the action to release a claim or not. Being on Blockchain, the whole process gets transparent, allowing the clients to track the status of the flight, henceforth, their packages. Thus, making it automated and trustless increases faith in the process, paving the path for smoother and faster claims.   

Wrapping Up

Chainlink is also developing optional attributes such as advanced oracle computations, oracle and data privacy, and much more. By ensuring high security & credibility guarantees on par with the Blockchain, Chainlink oracles enable more refined smart contracts. Moreover, to know major things related to Blockchain Oracles, click here. 

If you are looking to access real-time data using Chainlink Oracles or want to overcome Blockchain oracle issues in your blockchain ecosystem, take help from the best Blockchain development company (Infrablok). It will help by offering innovative Blockchain solutions.