How to create a DApp using Truffle, Oraclize, ethereum-bridge and Webpack
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!
- Writing & deploying a simple Smart Contract
- Setting up a local
ethereum-bridgefor 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
There’s a screenshot of what we’ll be making at the bottom of the article
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 TeamHut, a SaaS to help freelancers and digital teams organise & share their digital content.
- You’re able to clone a
gitrepository & install it’s dependencies via
- 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.
What is an Oracle?
Smart contracts, by their nature, are able to run calculations and store and retrieve data. Because every node runs every calculation, it’s not practical (and presently impossible) to make arbitrary network requests from an Ethereum contract. Oracles fill this void by watching the blockchain for events and responding to them by publishing the results of a query back to the contract. In this way, contracts can interact with the off-chain world.
“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.
First of all, let’s fire up our terminal and install Truffle globally:
$ npm install -g truffle
Create a new Truffle project
Create a new folder for our project, called
$ 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:
- How the second line prints
Truffle Develop started at http://127.0.0.1:9545Write down this host:port combination, you’ll need this in order to start
- 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
installed_contracts. In it, you’ll find the Oraclize contract called
usingOraclize.sol which our Solidity Contract will be inheriting from.
oraclize-test folder now looks like this
Keep the testnet active, and open a new terminal window to install
Create a new folder (next to
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-bridgefolder next to our
oraclize-testas we can re-use it in later projects.
You can run
node bridge -a 9 to start
-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
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:
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
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:
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, the
OraclizeTest() 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.
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.
__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
__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
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
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
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
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.
truffle migrate --develop --reset to deploy your contract to the testnet. You should see something resembling this:
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:
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
Use the number returned to resolve the issue.
Create a front-end
app folder and edit
index.html to resemble this snippet:
No real shocker there, I’m assuming everything is clear regarding the HTML file.
stylesheets/app.css to look like this:
Again, Basic stuff. I assume this is pretty clear.
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!
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:
http://localhost:8080 and you should see the HTML file showing the Oraclize Smart Contract balance, and it’s value in USD. 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.
I’ve uploaded a reference project to GitHub in case you run into trouble
medium-02-truffle-oraclize-api - Reference project for an article I wrote on Medium about using Truffle, Oraclize & the…
- Understanding Oracles (By Oraclize)
- Setting up an Oracle machine on Amazon’s AWS
- How does Oraclize handle the TSLNotary secret?
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.