Building your first DApp using SmartPy & React on Tezos

Yash Verma
3 min readJun 1, 2020

--

Deploying the Smart Contract using SmartPy

We will be using a simple Voting Contract with two candidates. Here it goes:

import smartpy as spclass VotingContract(sp.Contract):
def __init__(self):
self.init(votesRecord= sp.map(tkey = sp.TString , tvalue = sp.TInt))

@sp.entry_point
def vote(self,params):
sp.if self.data.votesRecord.contains(params.candidate):
self.data.votesRecord[params.candidate] +=1
sp.else:
self.data.votesRecord[params.candidate] = 1
@sp.add_test(name="Voting test")
def test():
obj = VotingContract()
scenario = sp.test_scenario()
scenario+=obj
scenario+=obj.vote(candidate="Modi")
scenario+=obj.vote(candidate="Kejriwal")
scenario+=obj.vote(candidate="Modi")

Go to https://www.smartpy.io/demo/, paste the code there and run it. The output on the right side will show up.

Now, we need to deploy it to the blockchain using a remote node.

Click on the Michelson Tab and select ‘Deploy Contract’.

Test Network Contract Origination

You will see the following message: A private key is needed — you can use the Tezos Faucet Importer to retrieve one.

  1. Click on the Tezos Faucet Importer link and the Tezos Faucet Importer will open. Now, click on the first step link (Download the data from the Faucet).
  2. You will be redirected to https://faucet.tzalpha.net/ where you can generate your Faucet account. Click on Get Testnet and you will get the credentials of the account. Copy them somewhere so that they can be retrieved later.
  3. Copy the credentials to Tezos Faucet Importer and click on Compute Private Key. Copy your private key to notes so that it can be retrieved later.
  4. Select your node as Cathagenet and click on Activate Account. It will take some time to complete the process and you can see the status on Tzstats links given there.
  5. After the account is activated, click on Reveal Account and wait till you get the output in the text box below.
  6. Go back to Test Network Contract Origination link and paste the private key there and click on “check credentials and compute account public key hash button. Save your Account public key hash to notes so that we can retrieve it later.
  7. Now, you can change the parameters if you want, and then click on Deploy Contract and then click on Open in Explorer.

Test Network Contract Explorer

In the explorer, you can interact with your contract.

  1. As we only have to give one input value (‘Modi’ or ‘Kejriwal’), go to New Operation Builder and enter ‘Modi’ or ‘Kejriwal’ in and click on Build Message. If you get ‘Message OK’, then you’re good to go with the input.
  2. You can also send it as input by selecting Direct Access to Test Networks option, entering credentials and clicking on Send the Transaction.

Now, we can create a frontend react app which will interact with the smart contract.

Getting Started with a blank React Project

Open the command-line in the directory where you want the react project folder to be and execute the following commands:

npm i -g npm
npm i -g create-react-app
create-react-app voting-dapp

Install conseiljs which will help us to interact with the contract:

npm i conseiljs

Building the React Frontend

Open App.js file in voting-dapp/src directory and add the create the frontend skeleton for our React App.

Add 2 buttons: Vote for Modi, Vote for Kejriwal.
I have linked the Github repo at the end of the tutorial.

Here is the code to link the buttons:
Replace the entries marked in bold with the credentials that you have saved.

const tezosNode = 'https://carthagenet.smartpy.io';async function VotingFunction(candidate) {
console.log(candidate);
const keystore = {
publicKey: 'edpktfyA6eVgMSmoTgdm5ojjTdXCdF86N78JrZCuRR5wKyXup5jVFQ',
privateKey: 'edskS6n7PUmKNTdbhQW7NdJvpLoSPvqTy3ocuACAMxwRxd4yK4w4CNsPcB1pgtmnyUH4eWUJmWvQ4dQHgkMq4n3HRMWvkH8X38',
publicKeyHash: 'tz1awWmVReqEZFKho6ZaFLDe7jy8Tpexn4iV',
seed: '',
storeType: 1
};
const contractAddress = 'KT1PVWVCtKm326kKkXoPyLRx1bZRAo4QuExy'; const result = await TezosNodeWriter.sendContractInvocationOperation(tezosNode, keystore, contractAddress, 0, 100000, '', 1000, 750000, undefined, `"${candidate}"`, TezosParameterFormat.Michelson); console.log(`Injected operation group id ${result.operationGroupID}`); return result.operationGroupID;}

Now, we will console.log the Smart Contract storage data to see the changes.
Replace the bold text with your Contract address.

function httpGet() {   let xmlHttp = new XMLHttpRequest();   xmlHttp.open( "GET", 'https://carthagenet.smartpy.io/chains/main/blocks/head/context/contracts/KT1PVWVCtKm326kKkXoPyLRx1bZRAo4QuExy/storage', false ); // false for synchronous request   xmlHttp.send( null );   console.log(JSON.parse(xmlHttp.responseText));}

Here is the Github repo.

For detailed blog series on how to get started with Smartpy, follow this.

For further work:

You can use Smart Contract Storage data to display the Vote count of the two candidates.

--

--