The TRON Developer Hub

Welcome to the TRON developer hub. You'll find comprehensive guides and documentation to help you start working with TRON as quickly as possible, as well as support if you get stuck. Let's jump right in!

Tronweb.contract()

Recent Posts

Archive

Tags

Custom Oracle Implementation

Smart contracts are able to run algorithmic calculations and store and retrieve data. Since the contracts are limited to the blockchain, it’s not possible to make network requests from a Tron contract. Oracles solve this problem by watching the blockchain for events and responding to them by publishing the results of a network request back to the contract. In this way, contracts can interact with the off-chain world.

Deploying the Smart Contract

Now that we have the smart contract written, we are going to deploy it onto the Shasta testnet using Tron Studio. Copy and paste the PriceOracle.sol contract into Tron Studio.

Configure your existing settings to point to the Shasta testnet. Make sure to switch your Environment to Testnet as well.

Developing and Running the Oracle

Now that you have your contract compiled and Tron Studio pointed at Shasta testnet, let's develop the oracle that will be listening for events, fetching price data from an external API, and writing it back to the contract.

Run mkdir PriceOracle and cd into the project directory by running cd PriceOracle in your terminal.

Next, run npm init to initiate a Node.js instance, configure your package.json properties, and open the project directory in your text editor.

Moving on, run npm install tronweb and *npm install request in your project directory to add the necessary dependancies to the oracle.

Finally, create a new javascript file called index.js and copy the below code to the file.

The oracle is now listening for events on the deployed PriceOracle contract. In Tron Studio, call the initUpdate function to update the price data within the contract.

Upon successfully calling the initUpdate function, the InitUpdate event is emitted and the oracle picks up on the emitted event, calls and parses the price data api response, and calls the PriceOracle updatePrice contract function to write the price data through this code in the oracle index.js file.

Upon successfully writing the price data through the updatePrice function, the PriceUpdate event is emitted. The oracle will pick up on this emitted event and display the price data from the contract through this code. You will see this in the console of your project.

Congratulations, you have successfully developed a custom oracle that works with the Tron blockchain!