Ethereum ÐApps Programming Distilled — Part 5

Publishing a DApp: using Truffle to deploy on either the Ropsten testnet or on the mainnet, and deploying the frontend on GitHub Pages with CloudFront on top.

Marco Bellinaso
8 min readMar 6, 2018

This is a multi-part article. Here are the links to the other parts:

So far we’ve worked with a local private blockchain, and a frontend running on a local webserver. Let’s see what it takes to publish it “live”, so that it’s usable by other people.

Backend

Publishing a Smart Contract to a public blockchain is the same regardless of whether it’s a testnet (I used Ropsten) or mainnet (besides the price of course — it’s free on testnet, it’s not free on mainnet). The “pure” approach would be to use the geth client to download the entire blockchain on your machine, then deploy to it (using geth, Mist or Truffle) and have the transaction broadcasted from your machine to the closest nodes and then to the entire network. I gave it a try but, honestly, I failed: geth kept finding only 1 or 2 nodes to downloaded data from, they dropped very often, and for that reason or unknown others geth was always getting stuck indefinitely. After a Saturday of attempts I gave up and looked at alternatives.

Turns out there is a very easy one, which is sending the transactions to the public nodes hosted by Infura.io rather than using a local node! Just sign up on their website for free and you’ll be given the url of a node that you can use rather than using localhost. You save time and plenty of space on your hdd. Once you have that, install the truffle-hdwallet-provider library on your machine, and finally edit the truffle.js file as follows to configure the Ropsten network (see here for a full step-by-step guide):

var HDWalletProvider = require("truffle-hdwallet-provider");var Web3 = require("web3");
var web3 = new Web3();
var mnemonicRopsten = "...find these on the MetaMask popup...";module.exports = {
networks: {
development: {
host: "localhost",
port: 9545,
network_id: "*" // Match any network id
},
ropsten: {
provider: function() {
return new HDWalletProvider(mnemonicRopsten,
"https://ropsten.infura.io/[your token here]")
},
network_id: 3,
gas: 4600000,
gasPrice: web3.toWei("20", "gwei")
}
}
};

Now execute “truffle migrate — network ropsten” from the command-line, and that will hopefully deploy your contract on the Ropsten testnet, giving you a feedback similar to the following:

Using network 'ropsten'.Running migration: 1_initial_migration.js
Deploying Migrations...
... 0x6cd4f49d0c04a3d976c63d04c766ba50f9813a5cd72265e4a4adf527d04d4791
Migrations: 0x7076dff8039206819f0c0ab7158457e8ee615ae5
Saving successful migration to network...
... 0xa8eb0ac1f5967338744a491eb74d20fbc652e49b112b30c66a48b43462ca0778
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying MessageStorage...
... 0x338eecf2260437d7aa45dc348dc8e675aea1d132ba18c94af0a2fa34bc34f766
MessageStorage: 0x765c19b73379dec5d851f66d937e053c865f9960
Saving successful migration to network...
... 0xda762551e6931e1d34e85418d3b467da4aa22501875ec3302a6d6e2aad680dec
Saving artifacts...

The address in bold is the transaction that actually deployed the contract on the Ropsten testnet, which you can search on ropsten.etherscan.io to see all details about it. For example it’s very interesting to see that the transaction costed 0.03454534 ETH…which is 0 USD on the testnet, but would have been around 30$ on the mainnet, at the current valuation of 1ETH=865USD. That is for a contract of around 200 lines + 800 lines for helper libraries; the cost would of course go up according to how big your contract and dependencies are! That is one of the reasons why you’ll really want to deploy when you’re confident that everything is ok, there are no bugs, etc.

Note: if you get “out of gas” errors when trying to run the migration, check from MetaMask that the first account in the Ropsten network has some Ether (HDWalletProvider uses the first one, you can’t make it use a different one). If you need some, just click “Buy” from MetaMask and it will send you to a webpage where you can get some from a free “faucet”.

As said, publishing to the mainnet would follow the same approach: you’d just use a different url from Infura for the truffle.js file, and you’d need some real Ether in your account.

Frontend

Running Truffle to deploy on the public blockchain does of course create a new ABI file (eg. ../build/contracts/MessageStorage.json), with the address of where the contract is available on that network. Just include that file in your project, by replacing the one used during development that was pointing to the private chain, and you’re done. You can test the frontend on the same http://localhost:3000 url that you’ve used before, to ensure everything is still ok, and then finally move it all online on an externally-reachable webserver.

That only thing I had to fix was about showing a “loading overlay” after sending a transaction to create a message, and hiding it when that completed. Transactions sent to the private blockchain are instantaneous so I hadn’t noticed I needed that. Transacting on Ropsten has instead a latency of quite a few seconds, which makes it necessary to show some feedback to the user in the meantime. This is why a real decentralised testnet is much more realistic than a completely private setup.

Since my app’s frontend is just static html and js files, I didn’t need a hosting that supports Node.js, PHP, ASP.NET or any other server-side framework. Therefore, the free GitHub Pages is perfectly capable of hosting my frontend. The nice thing about this option (besides the price being zero) is that to publish a new version of the files you just do a git commit/push.

If you deploy the contract only on the mainnet, or maybe only on the Ropsten testnet while it’s in beta, you’ll want to write a few lines of javascript to check that the user is on the correct network, otherwise the page wouldn’t work because the contract wouldn’t be found. Here’s a snippet that logs the current network and displays an error if the user is not on Ropsten:

web3.version.getNetwork((err, netId) => {
switch (netId) {
case '1':
console.log('This is mainnet');
break;
case '2':
console.log('This is the deprecated Morden test network.');
break;
case '3':
console.log('This is the ropsten test network.');
break;
default:
console.log('This is an unknown/private network.');
}
if (netId != '3') {
alert('You must be on the Ropsten testnet!');
}
});

I put CloudFlare in front of my files on GitHub Pages, as explained here very clearly by Karan Thakkar, to have free SSL, url rewrites (eg: remove www. from www.msgblocks.com/something), CDN caching and html/css/js minification (in case you don’t do it as part of your build process). In order to have your own domain, just purchase it on Namecheap or from somewhere else, make it point to the CloudFlare’s nameservers, let CloudFlare automatically set up the DNS records you need, and do the other few steps explained in the article above to configure redirects and https. It takes like 10 minutes to set up and it’s free…can’t really ask for more!

Your app would now be public, running on a real decentralised blockchain with a web frontend on your own domain, with a CDN (content delivery network) to speed up the page load and protected by SSL.

Sounds good…how do I start my app now?

This is what I’d do if I had to start from scratch now:

  1. Read this article about creating, deploying and debugging a Smart Contract with Truffle. You can set up the environment and follow the guide step by step in one hour or so. The sample contract is of course super simple, but it shows plenty of concepts in practice, and it’s very beneficial.
  2. Install the Ganache GUI to have a nicer and easier way to see what happens on your private blockchain as you keep doing sample transactions with the contract developed in #1.
  3. Read this other article, also by ConsenSys (like everything about Truffle), about creating a more complex Smart Contract but also its web-based frontend with HTML, JS, MetaMask.
  4. Do the interactive CryptoZombies course, created by Matthew Campbell and the Loom Network team. This is really an incredible tool to start from zero with Solidity, and learn how to create a game similar to the popular CryptoKitties step-by-step, with plenty of useful notes and tips along the way. Complete all the lessons and really write the code in their editor, it’s very worth it!
  5. At this point you should know more than enough to start your own original idea! Enjoy!

Conclusions

While it’s no longer early days to become a cryptocurrency investor…it’s definitely very early days to be a blockchain developer and create something new and interesting. If you start now — and even if you only play with simple things — you’ll have an advantage in the future when the technology becomes more mature and there will be frameworks and tools that abstract complexities and provide workarounds for the current constraints, because you’ll have a better understanding of how things work behind the scenes.

Starting out is not difficult, and it’s something that’s probably quite different from everything that you’ve worked on so far, which should make it fun and interesting…so why not?

Other Resources

In addition to all the resources and articles linked above, here are some more resources that I suggest to check out:

  1. How does Ethereum work, anyway? by Preethi Kasireddy, gives a deeper and more visual overview of many concepts of how this blockchain works under the hood.
  2. Ethereum Smart Contract Development Best Practices: the title says it all.
  3. ETH Guide by chris dannen provides plenty of links to tools, articles and various other resources, grouped by category.
  4. Token Economy is a weekly newsletter written by Stefano Bernardi and Yannick Roux that covers more the financial side of things (new projects, market analysis, rumours, technology improvements in the different blockchains, …), but it’s a great resource to see what’s happening in the crypto world as a whole. There’s even too much to follow unless this becomes your priority, but the good thing is that for every article they link they provide a summary and commentary directly in the newsletter…so even reading just that might be enough to get a high-level understanding of what’s new.
  5. Getting Up to Speed on Ethereum by Matt Condon: it talks about some of the things explain in this article as well, plus it gives a quick overview of many other technologies in the ecosystem, such as tokens, ETHPM, the different programming languages (even if you can care about just Solidity at the moment), DAOs, Aragon, IPFS, FileCoin, Augur, Gnosis, Golem, 0xProject, Bancor, Oraclize, BTCRelay, Open Zeppelin, ENS, … (yes, I agree, there are too many things to study! :)

Who am I / what do I do? I proudly work as a Solutions Architect in the Mobile Team @ ASOS.com (iOS app | Android app), and we’re always looking for strong, friendly and talented developers that want to have an impact on how tens of millions of customers shop online. ASOS is the biggest online-only retailer in UK and, let’s be real, the best tech+fashion company in the world. Some of the technologies we use are Swift for iOS, Kotlin for Android, React and Node on the web frontend, .NET and Azure on the backend. If that sounds interesting to you, and you happen to live in beautiful London (or are willing to move here…after all it’s the best city in Europe except for some in Italy!), do get in touch with me!

--

--

Marco Bellinaso

Principal Architect @ASOS.com (and iOS / full-stack dev for fun)