How to create a DApp using Truffle, Oraclize, ethereum-bridge and Webpack

Defihut author: WWWillems profile picture

WWWillems

A simple guide on using external API data in a Smart Contract front-end.

About this tutorial

After completing this tutorial you’ll have a working DApp (Decentralised Application) reacting to Events emitted via a Solidity Smart Contract using Oraclize to fetch external API data from Coinbase. For science!

We’ll be:

  • - Writing & deploying a simple Smart Contract
  • - Setting up a local ethereum-bridge for Oracle communication
  • - Fetching external data from the Coinbase API using an Oracle
  • - Creating a custom front-end to show the API data
  • - Doing this in a local development environment

How To Create A Dapp Hero Image

Note
There’s a screenshot of what we’ll be making at the bottom of the article

About me

Hi, my name is Lander. I’m a Digital Consultant and product builder from Belgium. When I’m not dabbling in Solidity, I’m working on Defihut, a platform for Decentralised Finance news, tutorials and interviews.


Start

Prerequisites

  • - You’re able to clone a git repository & install it’s dependencies via npm
  • - You have basic knowledge of HTML, JavaScript, Webpack, terminal, …
  • - You’re looking to learn more about using Oraclize & Solidity Events

What will we be making?

We’ll be writing a Smart Contract that fetches external API Data using a locally running Oracle. We’ll do this by emulating the Oracle using ethereum-bridge. The contract fetches the current Ethereum USD price from the Coinbase ETH-USD spot price API.

We’ll be creating a simple HTML page that shows our contract’s total ETH balance both in ETH and in USD. The total USD value of your contract is calculated using the Coinbase API. The values auto-update until the contract runs out of funds.

Tools used

“Oracles allow external data, as in non-blockchain data, to be sent to contracts.”

Oracles are trusted data feeds that send information into the Smart Contract, removing the need for Smart Contracts to directly access information outside their network, thus lightening their workload. Oracles are usually supplied by third parties and are authorized by the companies that use them.

The oracle/oracle network is the party in charge of connecting you to the data-source. If you’d like to read more about Oracles, see here.


Let's go

Install Truffle

First of all, let’s fire up our terminal and install Truffle globally:

$ npm install -g truffle

We’ll use Truffle to migrate our contracts, run our development testnet and install Oraclize. It’s an essential tool if you’re serious about Solidity development.

Create a new Truffle project

Create a new folder for our project, called oraclize-test:

$ mkdir oraclize-test

Navigate into the folder and create a new Truffle project. We’re starting from a Truffle webpack box, which will make it easier for us to create our DApp’s front-end.

$ cd oraclize-test
$ truffle unbox webpack

Afterwards, start the Truffle testnet (testrpc):

$ truffle develop

You should see something like this: truffle-develop-image

Notice:

  • - How the second line prints Truffle Develop started at http://127.0.0.1:9545 Write down this host:port combination, you’ll need this in order to start ethereum-bridge.
  • - The amount of accounts created (=10)

Nice, you’ve created a bootstrap Truffle project, and launched the Truffle development testnet. Close the testnet by pressing (ctrl+c) and continue by adding Oraclize to Truffle.

Add Oraclize to Truffle

Add Oraclize to Truffle and restart the Truffle development testnet

$ truffle install oraclize-api
$ truffle develop

Notice how, after installing oraclize-api, a new folder has been created in our oraclize-test folder: installed_contracts. In it, you’ll find the Oraclize contract called usingOraclize.sol which our Solidity Contract will be inheriting from.

Our oraclize-test folder now looks like this

oraclize-test folder contents

Keep the testnet active, and open a new terminal window to install ethereum-bridge.

Install ethereum-bridge

Create a new folder (next to oraclize-test) called ethereum-bridge Clone the ethereum-bridge repository, and install it’s dependencies:

$ mkdir ethereum-bridge
$ git clone https://github.com/oraclize/ethereum-bridge ethereum-bridge
$ cd ethereum-bridge
$ npm install

We’re creating the ethereum-bridge folder next to our oraclize-test as we can re-use it in later projects.

You can run node bridge -a 9 to start ethereum-bridge. The -a 9 argument instructs ethereum-bridge to use the last account created by our local Truffle Testnet node to deploy the Oraclize contract. This address should only be used for Oraclize, no other contract is meant to use it.

The Truffle Testnet node creates 10 accounts for you to work with, as their index is 0-based, we’re using the index of 9.

Go on, try it:

$ node bridge -a 9

Whoops: oraclize node bridge error

As you can see, we’ve ran into an error. If you read the ERROR line closely, you can see ethereum-bridge is trying to connect to the wrong host:port combination (http://localhost:8545).

This combination should reflect the combination you wrote down in the previous step. In my case that’s http://localhost:9545. Be sure to double-check this as older Truffle versions used to use port 8545.

To resolve this, start ethereum-bridge telling it to use the right host (-H) & port (-p argument). Mind the flags, they’re case-sensitive!

$ node bridge -a 9 -H 127.0.0.1 -p 9545 --dev

The result should look like this:

oraclize node bridge result

Look for the line that looks like: OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)

If you’re using a different mnemonic than the standard Truffle one, the ETH address shown in between the round brackets will be different.

Make sure you write down (copy paste) the complete OAR line, so we can use it in the constructor of our contract later. Again, leave your terminal running.

At this point you should have 2 active terminal windows:

  • - Your Truffle develop testnet
  • - Your ethereum-bridge

Write the Solidity Smart Contract

Let’s get started with a sample Smart Contract. Look for the contracts folder in the oraclize-test folder and add a new file OraclizeTest.sol. This will become the Smart Contract that sends transactions to the Oracle to fetch API data. Copy paste the following gist into the file:

Note: Make sure you replace the OAR = OraclizeAddrResolverI(0x...); line with the one you wrote down in the previous step.

Don’t forget to remove this OAR variable from your constructor before production, this is just for testing, in production it will automatically fetch the OAR depending on the chain you’re running it, currently the Mainnet, Ropsten, and browser-solidity VM environment are supported.

Upon contract creation, theOraclizeTest() constructor is being run, which sets the owner to the address deploying the contract and initialises the Oracle. Afterwards, it calls the update() function once to fetch the current ETH price from the Coinbase API.

The update() function checks if the contract holds enough funds to create an URL request, and continues to make the request to Oraclize if it has.

The __callback() function is being called by Oraclize as soon as the request has completed, you can use JSONPATH to slice the response. See documentation here.

We can use the first parameter id in the __callback() function to handle different requests. We’ll be skipping this, as this is only a basic example.

Compile the code

Look for the contracts folder in oraclize-test and delete ConvertLib.sol and MetaCoin.sol. These are example files, we won’t be needing them.

Copy paste the contract code mentioned above into OraclizeTest.sol and compile the code using

$ truffle compile

If it compiled successfully, you should see a new folder in oraclize-test called build. This folder contains the compiled version of your Smart Contracts. In it, you’ll find some *,json files that contain the bytecode that will be deployed by Truffle

Now, let’s prepare Truffle to deploy our code to our development testnet..


Update Truffle config

Open truffle.js in your oraclize-test folder and add your development environment:

Here, we’re defining the development network (=environment), and setting the port number.


Update Truffle migrations

Open oraclize-test/migrations/2_deploy_contracts.js and edit it to resemble this snippet:

In this gist we’re importing the compiled version of OraclizeTest.sol contract and instructing Truffle migrations how to migrate the contract.

If we wouldn’t do this, Truffle wouldn’t know which files to deploy. It’s pretty standard stuff, look into Truffle migrations if you’re interested.

We’re funding the Smart Contract with 0.5 ETH (500000000000000000 wei) so we’re able to talk to Oraclize. We need ETH to be able to pay for the gas when sending transactions.

Run truffle migrate --develop --reset to deploy your contract to the testnet. You should see something resembling this:

Successful Truffle development testnet migration

This will run all migrations located within your project’s migrations directory. At their simplest, migrations are simply a set of managed deployment scripts. If your migrations were previously run successfully, truffle migrate will start execution from the last migration that was ran, running only newly created migrations. If no new migrations exists, truffle migrate won't perform any action at all. You can use the --reset option to run all your migrations from the beginning.

As you can see in the screenshot, Truffle deployed the contract to this address:

0x572309f98e9085f9122fbec9de20a00e19a0476a7cde7e7f84b5a7d168a7520e

Note: If, like me, you’re seeing gas-related errors when trying to run your Truffle migrations, try to edit the gas amount mentioned in the migration.

If you want to have a better estimation, head to your Truffle Development testnet terminal and enter eth.getBlock("pending").gasLimit. Use the number returned to resolve the issue.

Truffle development testnet Terminal estimating gasLimit


Create a front-end

Open the app folder and edit index.html to resemble this snippet:

No real shocker there, I’m assuming everything is clear regarding the HTML file.

Edit javascripts/app.js to look like this:

I’ve deliberately kept the JavaScript simple. The comments should be sufficient for a basic understanding of what’s happening.

and edit stylesheets/app.css to look like this:

Again, Basic stuff. I assume this is pretty clear.


Almost There…

If you’d like to see your DApp, go ahead and spin up the front-end:

$ truffle compile
$ truffle migrate --development --reset 
$ npm run dev

Your contract needs to be compiled & deployed to your local development testnet. Make sure to re-compile & re-migrate when you make changes to the Contract. Truffle-webpack will automatically reload your front-end when it detects changes to the contract. Neat!

Open http://localhost:8080 and you should see the HTML file showing the Smart Contract balance, and it’s value in USD after a few seconds. The values will update automatically until the Smart Contract runs out of funds. Don’t forget that we need to pay for our Oraclize communication ;).

If everything went smooth, you should see your front-end showing the balance of the Smart Contract in ETH and in USD using Oraclize and Solidity Events:

DApp Tutorial End Result

Oraclize uses the Coinbase API to fetch the current ETH/USD spot price and return it to the contract. The front-end values will keep updating until the Smart Contract runs out of funds.


Reference Project

I’ve uploaded a reference project to GitHub in case you run into trouble

https://github.com/WWWillems/medium-02-truffle-oraclize-api

Interesting Links

Tools


Thanks for reading!

I’d love to hear from you and learn how you feel about my article. Please let me know if you think anything’s missing.

If you’d like to keep in touch, respond to this post below, follow me on Twitter or sign up to my newsletter using the form below.

Subscribe to our newsletter

The latest jobs, news, and articles sent to your inbox weekly.

© 2020 Defihut.com - All rights reserved.