Using chainlink oracle on matic network

Time:2022-1-10

Original title: using chainlink oracles on matic network
Original address: https://blog.chain.link/matic-defi-price-feeds/
Original author: Harry papacharissiou

Using chainlink oracle on matic network

Since the launch of matic network at the beginning of this year, thanks to its secure and scalable infrastructure and real-time transaction features, it has quickly become a popular layer 2 solution among Ethereum developers. Matic’s high-performance, low fee infrastructure provides a viable platform for defi applications to promote large-scale applications. Similarly, in the field of blockchain Oracle, chainlink has become the preferred Oracle solution for the defi protocol,Chainlink’s price feeds)It is now guarding assets worth hundreds of millions of dollars. In this technical article, we will show you how to use chainlink’s Oracle in matic’s defi application and how to use chainlink’s feed price to give the application access to high-quality and tamper proof data, which is not vulnerable to such problems asOracle vulnerabilities and lightning attacksAnd other risks.

Demand for scalable and secure defi protocol

This year has witnessed the outbreak of the defi protocol. The total value lock-in (TVL) of defi has increased rapidly from US $680 million in January to more than US $14 billion now. With the growth of TVL, the number of transactions on the chain has also reached a new level, but it has also attracted some unnecessary attention. The perpetrators began to take advantage of these protocol loopholes for their own interests.

Due to the increase in the number and level of transactions on the chain brought about by the growth of defi, the performance of Ethereum becomes congested, which is also due to the limitation of scalability and low throughput of Ethereum blockchain. This has caused a series of related reactions that perplex users’ experience of using the defi protocol and lengthy transaction time. (P.S. congestion will lead to high gas fees, otherwise miners will not pack; at the same time, the transaction confirmation time will be extended, unless higher gas fees are given)

Slow transaction speed and high transaction costs are the two most important constraints that hinder defi from entering the mainstream. Layer 2 networks such as matic can unlock the growth of defi in the next stage, thanks to its enhanced scalability, high throughput and low-cost transactions. The matic side chain is also composable and fully compatible with EVM. One of the core values of defi is its unlicensed composability. Matic provides an attractive choice for developers seeking to build various valuable defi applications. These defi applications are scalable, can provide low-cost transactions, ensure unlicensed composability, and provide a seamless user experience.

However, these defi applications still need to access high-quality trusted external data. As we have seen many times this year, the defi protocol may suffer from various forms of attacks, such as price Oracle attack. The perpetrators combine flash loan and low-quality Oracle to manipulate the market to achieve a favorable situation for them, which damages the interests of other users.

Chainlink’s price feeding mechanism reduces the risk that defi applications are vulnerable to these attacks by providing summary data from a variety of high-quality data providers. These data are released and linked by the decentralized oracle on the chainlink network. Chainlink’s decentralized architecture and extensive high-quality data sources ensure that the final price reflects a wide range of market coverage, which in fact means that the price is determined after aggregating a series of different prices in the whole market, not just a small subset.

Now that we understand the advantages of building the defi protocol on the matic network and the important role played by the chainlink Oracle and the pricing mechanism, we will show the case of using chainlink pricing when building the defi application on the matic network.

Using chainlink pricing mechanism on matic network

Chainlink’s price feeding mechanism uses a variety of high-quality data inputs and combines them with the chainlink Oracle network. The prediction opportunity feeds the price data to the reference contracts, in which the data results will be aggregated. Defi protocol attaches great importance to data quality and integrity, which is particularly important. Chainlink pricing mechanism provides the best and strictly tested production environment solution for these protocols that want to protect themselves from various attacks caused by data quality problems or transmission problems.

The following two tutorials can also be viewed through the complete smart contract in Remix.

The first step of using chainlink pricing mechanism and oracle on matic network is to set up your metamask wallet and use it to connect to matic’s Mumbai test network. Then you can obtain some matic tokens on Mumbai test network and use them in defi smart contract.

Using chainlink oracle on matic network
Setting up the matic Mumbai test network in metamask
**

Get test net matic token

Matic is a local token on matic network, which can be compared with eth token on Ethereum. In order to interact with the matic network, matic tokens will be used to pay gas fees. In order to obtain the matic token of Mumbai test network, go to the matic faucet, select the matic token and Mumbai test network, enter the metamask wallet address and click Submit.

Using chainlink oracle on matic network
Obtaining testnet matic

Using chainlink oracle on matic network

Note: confirmation is required after submission, and you can go to the browser to view this transaction: https://explorer-mumbai.maticvigil.com/tx/0x742aa8e4c1fb12105b424840e435193b1b24324e2d77d926d4903fcc54142772/internal-transactions
By checking the wallet, you can find that the test token has been obtained (0.1 matic for two times):

Using chainlink oracle on matic network

Using chainlink oracle on matic network

Create smart contract

The easiest way to start building smart contracts using chainlink pricing mechanism on matic networks is to use standard price consumer contracts. This is a basic standard contract that can make a request to chainlink’s price feeding mechanism. We will open the contract in the remix editor and modify it to meet our own needs. The demonstration of this article will be obtained at eth / USD price. The first step is to initialize the Pricing Reference contract of matic in the constructor. The address of eth / USD Pricing Reference contract deployed on Mumbai test network is:_ 0x0715A7794a1dc8e42615F059dD6e406A6594651A。`

priceFeed = AggregatorV3Interface(0x0715A7794a1dc8e42615F059dD6e406A6594651A);

Next, we need a function to get the latest price from the price feed aggregator contract, which is instantiated in the constructor above. To achieve this goal, we already have a function called latestrounddata in the aggregation contract, which will return the current aggregation contract status. In this case, we will take the current price and return it.

function getLatestPrice() public view returns (int) {  ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; }

Deploy and test smart contracts

Now we can deploy and test our smart contract. Compile the smart contract in remix, then change the environment to “injected Web3” on the deployment page, ensure that the wallet address is the address containing matic tokens, click the deploy button, and follow the next steps. The end result is the successful deployment of smart contracts to the matic Mumbai test network.
After deployment, we just need to simply execute the “getlatestprice” function. The result will be the latest price data returned by the function in the ETH / USD aggregation contract, which can be used in the defi application on the matic network.

Using chainlink oracle on matic network
Eth / USD price feeding results

Using chainlink oracle on matic network

In some scenarios on matic, smart contracts need off chain data, which is not provided by chainlink’s feed price. This is where we need to use chainlink oracle. We now modify our smart contract to obtain the market price that cannot be provided by the price feeder using chainlink. In this case, we use eth / EUR price.

Get the link token of the test network

You need to get some link tokens of the test network to send requests to chainlink’s Oracle. In order to obtain the link token of Mumbai test network, you need to join matic’s discord community, post your metamask wallet address, and ask matic team members to send some link tokens of Mumbai test network. Once you get some matic and link into your wallet, you can enter the step of smart contract.

Create smart contract

In matic, the simplest way to use chainlink Oracle to establish smart contract is to use the standard chainlink apiconsumer contract. This is the basic standard contract, which is used to initiate a request to obtain external data through the chainlink oracle. We modify this contract in Remix to meet our needs.

First, we need to rename the “volume” parameter to “ethprice”, and then change the “requestvolumedata” function name to “requestethereumpress”. After completion, we need to modify the constructor to:

  • Mumbai test online link token address is_ 0x70d1f773a9f81c852087b77f6ae6d3032b02d2ab, we transfer it to the “setchainlinktoken” function_
  • As indicated in the matic document, there is a Oracle contract running on the Mumbai test network at_ 0x1cf7d49be7e0c6ac30ded720623490b64f572e1, we set the Oracle variable to this value_
  • The API we will use will request through HTTP get, and the returned value is an unsigned integer. The Oracle running on the Mumbai test network has many different job specifications that can be used. According to the jobs listed in the matic document, what meets our needs is this:_ d8fcf41ee8984d3b8b0eae7b74eca7dd,_ Because we want to execute the HTTP get request and the returned data is an unsigned integer, we set the “jobid” variable to this value
  • Modify the “fee” variable to 1Link and remove the “0.1” prefix. This is a piece of payment data sent to the Oracle along with the external data request (link token is paid for this request).
constructor() public {  setChainlinkToken(0x70d1F773A9f81C852087B77F6Ae6d3032B02D2AB); oracle = 0x1cf7D49BE7e0c6AC30dEd720623490B64F572E17; jobId = "d8fcf41ee8984d3b8b0eae7b74eca7dd"; fee = 10 ** 18; // 1 LINK }

Now that we have completed the constructor, we can move to the “requestethereumprice” function and the “full” function.

The working principle of chainlink Oracle meeting the request is to adopt chainlink’s request and response design mode, in which the function on the chain will create and send the request, the Oracle detects the request, and thenresponseWill be sent to another function of the same contract. In our example, the “requestethereumprice” function will create and send the request, and the “full” function will process the response. The response specification is defined in this fulfill. In the selector.

The ETH / EUR price data API we will consume is from crypto Com. Click this link in the browser, and you can see the JSON format of the returned data.
In our “requestethereumprice” function, we modify it as follows:

  • Set the URL to the ETH / EUR interface endpoint
  • Set the “path” variable in the request to “EUR”, which is the path of the JSON response we want to find and return. The output result of the endpoint contains the current eth price
  • Multiply the result by 100 because solidity does not process data with decimal points
  • Send request to chainlink Oracle
function requestEthereumPrice() public returns (bytes32 requestId)  { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);  

// Set the URL to perform the GET request on 
request.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=EUR");  

// Set the path to find the desired data in the API response, where the response format is: 
// {"USD":243.33} 
request.add("path", "EUR");  

// Multiply the result by 100 to remove decimals 
request.addInt("times", 100);  

// Sends the request 
return sendChainlinkRequestTo(oracle, request, fee); }

In the “full” function, we can see that the Oracle sends back a response to_ The price parameter, and then the parameter value is saved to the ethereumprice variable in the contract.

function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId)  { ethereumPrice = _price; }

Now our contract is ready and can be compiled and deployed to the matic Mumbai test network.

Deploy and test contracts

Compile the contract in Remix and then deploy the contract to the Mumbai test network. We have done these steps in the previous feed contract.

The next step is to add a certain link token to the contract, so it can send a request to the chainlink oracle. To complete this step, get the address of the deployed contract, and then send 1Link tokens to this address through the metamask wallet.

Using chainlink oracle on matic network
Charge the contract with link token

Once the contract deployment is completed and link is recharged, we can click the “request Ethereum price” button to call the function and send a request to the chainlink Oracle to obtain the current Ethereum price. We will also send link as the oracle to pay to chainlink to complete this request.

Using chainlink oracle on matic network
Contract for test deployment

After the request is completed, the chainlink Oracle will complete it, and then the “full” function in the contract will be called by the chainlink node Oracle contract. This will take a few seconds to complete, and then we can view the API request results by executing the getter function of “ethereumprice”. The result should be the current eth price in EUR, which is now saved to the contract and waiting for the defi application running on the matic network to consume this data.

Using chainlink oracle on matic network
View returned results

summary

The matic network itself has the characteristics of fast, cheap and reliable transaction, which provides a practical layer 2 solution for building the defi protocol. The chainlink Oracle and chainlink’s price feeder further enhance the value proposition of building the defi protocol on matic. The chainlink Oracle and chainlink’s price feeder enable these protocols to access external data and events, including high-quality aggregate price data that can be used in a variety of valuable defi applications, such as decentralized exchange (DEX) and liquidity pool, Loan agreements, decentralized insurance and automated market makers (AMMS), etc.

If you are a developer, you want to quickly connect your application to chainlink’s price reference data, access developer documentation, and access discord technology discussion. If you want to arrange a call to discuss the integration of matic / chainlink more deeply, please contact here.

Website | Twitter | Reddit | YouTube | Telegram | Events | GitHub | Price Feeds | DeFi

END.