A Guide to Building Your First Decentralized Application

Demo - We'll build a decentralized voting app. No need to trust anyone if the tallied votes are not modified!

But first, what happened to the Web?

The Web started off 'decentralized'. Everyone who wanted a website bought their own server and hosted their own data on it. But After the Dot-Com bubble, data started to become centralized.

alt text

This is bad. Real bad.

  • It's shrinking the economy
  • Too much concentrated power.
  • We have no say in how our data is used.
  • We should get paid for our data.

alt text

Decentralized vs Centralized vs Distributed. What's the difference?

alt text

Centralized

Centralized systems directly control the operation of the individual units and flow of information from a single center. All individuals are directly dependent on the central power to send and receive information, and to be commanded.

  • single server
  • easy to publish
  • difficult to scale
  • single point of failure

Examples (Google, Facebook, Amazon, etc.)

Distributed

Distributed systems spread computation across multiple nodes instead of just one. Google for example has adopted a distributed architecture internally to speed up computing and data latency. This means that a system can be both centralized and distributed.

Examples (Google, Facebook, Amazon, etc.)

Decentralized

Decentralized systems are ones where no node is telling any other node what to do. Bitcoin is both distributed because its timestamped public ledger, the blockchain, resides on multiple computer and decentralized because if one node goes down, the network is still able to operate.

  • Multiple Servers
  • Demand and Failures better handled

Examples (Bitcoin, Ethereum, Steemit)

So does a profitable decentralized app look like?

alt text

Feature 1 - its open source

alt text

If we delve into the traditional business models, all of them require the product or service for sale to be better than that of the competitor. Open sourcing your product would mean that any competitor could take all of your work, white label it, and sell it as their own.

Having the app be open source allowed the network the transparency it needed to improve itself with developer contributions and grow trust amongst its users to give its coins real world value. Open sourcing your dapp will gain the trust of potential users. Anyone can fork your dapp, but they can’t fork your development team. Users want to get behind the people best suited to maintain the dapp, and those tend to be the original developers.

Feature 2: Use of Cryptocurrency

alt text

Traditional modes of monetization

  • transaction fees
  • advertising revenues
  • referral commissions
  • access rights to user data
  • subscription services.

Cryptocurrency way

  • Allocate scarce resources in the network using a scarce token
  • Users need this appcoin to use the network.
  • Owners of scarce resources get paid in appcoins.

Example 1 (Bitcoin) - The owners (miners) of the scarce resources (computing power) get paid with transaction fees directly from the users so that they can use the service. Because the network grew to include more users and there were a fixed amount of coins from the output, the values of the coins grew as well.

Example 2 (FileCoin) - Miners of the scarce resource (storage space) get paid in filecoin. More people using the service to store files, more the value of filecoin rises.

We can apply this model to any kind of dapps. Scarce resources could be storage space, trades, images, videos, texts, ads, etc.

Feature 3: Decentralized Consensus

alt text

  • The Use of a proof algorithm to maintain consensus (like proof of work)
  • Distributed Hash Table to store data
  • Blockchain for app level constructs (usernames, status updates, high scores, timestamps)
  • DHT + Blockchain since blockchain solves the major security issue of DHTs (not forcing nodes to trust each other on the validity of data
  • Smart Contracts (cryptoeconomically secured code)
if (user.sendsMoney(customerID))
{
runContract();
}

func runContract()
{
 println('hello world');
}

Feature 4: No central point of failure

Use IPFS

alt text

alt text

alt text

These technologies are ways of building more autonomous software

alt text

Where value generation and capital generation are more closely aligned

Alright lets get to our voting dapp demo...

Step 1 - Setting up Environment

Step 2 - Creating Voting Smart Contract

Step 3 - Interacting with the Contract via the Nodejs Console

Step 4 - Creating GUI interface

alt text

Step 1 - Setting up Environment

Instead of developing the app against the live Ethereum blockchain, we will use an in-memory blockchain (think of it as a blockchain simulator) called testrpc.

npm install ethereumjs-testrpc web3

testrpc creates 10 test accounts to play with automatically. These accounts come preloaded with 100 (fake) ethers.

Step 2 - Creating Voting Smart Contract

  • We'll use Ethereum's solidity programming language to write our contract
  • Our contract (think of contract as a class) is called Voting with a constructor which initializes an array of candidates
  • 2 functions, one to return the total votes a candidate has received & another to increment vote count for a candidate.
  • Deployed contracts are immutable. If any changes, we just make a new one.

Let's install the solidity compiler via npm

npm install solc

After writing our smart contract, we'll use Web3js to deploy our app and interact with it

siraj:~/hello_world_voting$ node
> Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

Then ensure Web3js is initalized and can query all accounts on the blockchain

> web3.eth.accounts

Lastly, compile the contract by loading the code from Voting.sol in to a string variable and compiling it

> code = fs.readFileSync('Voting.sol').toString()
> solc = require('solc')
> compiledCode = solc.compile(code)

Deploy the contract!

  • dCode.contracts[‘:Voting’].bytecode: bytecode which will be deployed to the blockchain.
  • compiledCode.contracts[‘:Voting’].interface: interface of the contract (called abi) which tells the contract user what methods are available in the contract.
> abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)
> VotingContract = web3.eth.contract(abiDefinition)
> byteCode = compiledCode.contracts[':Voting'].bytecode
> deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
> deployedContract.address
> contractInstance = VotingContract.at(deployedContract.address)
  • deployedContract.address. When you have to interact with your contract, you need this deployed address and abi definition we talked about earlier.

Step 3 - Interacting with the Contract via the Nodejs Console

> contractInstance.totalVotesFor.call('Rama')
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53'
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0x02c054d238038d68b65d55770fabfca592a5cf6590229ab91bbe7cd72da46de9'
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0x3da069a09577514f2baaa11bc3015a16edf26aad28dffbcd126bde2e71f2b76f'
> contractInstance.totalVotesFor.call('Rama').toLocaleString()
'3'

Step 4 - Creating GUI interface

Let's use our HTML + JS client side skills w00t!