<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Zastrin - Medium]]></title>
        <description><![CDATA[Learn blockchain programming building real-world projects #buidl - Medium]]></description>
        <link>https://medium.com/zastrin?source=rss----cb7771de5c9c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Zastrin - Medium</title>
            <link>https://medium.com/zastrin?source=rss----cb7771de5c9c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 02:30:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/zastrin" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build an Ethereum dapp using ethers.js]]></title>
            <link>https://medium.com/zastrin/build-an-ethereum-dapp-using-ethers-js-c561f9c4dd2f?source=rss----cb7771de5c9c---4</link>
            <guid isPermaLink="false">https://medium.com/p/c561f9c4dd2f</guid>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Mahesh Murthy]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 03:52:02 GMT</pubDate>
            <atom:updated>2019-03-07T21:48:30.761Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have built dapps on Ethereum, you most likely have used <a href="https://github.com/ethereum/web3.js/">Web3.js</a> to build your javascript frontend. <a href="https://github.com/ethers-io/ethers.js/">Ethers.js</a> is a lightweight javascript library which can be used as an alternative to Web3.js to build your javascript frontend and interact with the Ethereum blockchain. I had a chance to tinker with Ethers.js recently and was impressed with it. In this post/tutorial, I show how you can use Ethers.js to build a simple dapp. I hope this helps you evaluate and get started using Ethers.js for your next project.</p><p>In this tutorial, we will create a simple Voting dapp (very similar to our popular ‘<a href="https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2">Hello world voting dapp</a>’ many of you might know!). The Solidity contract will be the same but we will use Ethers.js instead of Web3.js for the frontend. The application is extremely simple, all it does is initialize a set of candidates, let anyone vote for those candidates and display the total votes received by each candidate.</p><p><em>If you are new to Ethereum, here are some </em><a href="https://www.zastrin.com/#courses"><em>courses</em></a><em> that can help you get started.</em></p><p>The goal of this tutorial is to:</p><p>1. Set up the development environment<br>2. Learn the process of writing a contract, compiling it and deploying it in your development environment<br>3. Interact with the contract using ethers.js through a nodejs console<br>4. Interact with the contract using ethers.js in a simple web page to display the vote counts and vote for candidates through the page</p><p>If you have already worked through the ‘<a href="https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2">Hello world voting dapp</a>’, you can skip to Step 3.</p><p>This is how I would visualize this application we are going to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*UIBTOluIJ2iVkwkSOmaT1A.png" /></figure><h3>1. Setting up the development environment</h3><p>Instead of developing the app against the live blockchain, we will use an in- memory blockchain (think of it as a blockchain simulator) called ganache. Below are the steps to install ganache, ethersjs, solc (to compile our contract) and start the test blockchain on a macos. The exact same instructions work on linux as well.</p><pre>zastrin@macbook$ brew update<br>zastrin@macbook$ brew install nodejs<br>zastrin@macbook$ mkdir -p ethereum_voting_dapp/chapter1-ethersjs<br>zastrin@macbook$ cd ethereum_voting_dapp/chapter1-ethersjs<br>zastrin@macbook$ npm install ganache-cli ethers solc@0.5.3<br>zastrin@macbook$ node_modules/.bin/ganache-cli</pre><pre>Ganache CLI v6.0.3 (ganache-core: 2.0.2)</pre><pre>Available Accounts</pre><pre>==================</pre><pre>(0) 0x5c252a0c0475f9711b56ab160a1999729eccce97<br>(1) 0x353d310bed379b2d1df3b727645e200997016ba3<br>(2) 0xa3ddc09b5e49d654a43e161cae3f865261cabd23<br>(3) 0xa8a188c6d97ec8cf905cc1dd1cd318e887249ec5<br>(4) 0xc0aa5f8b79db71335dacc7cd116f357d7ecd2798<br>(5) 0xda695959ff85f0581ca924e549567390a0034058<br>(6) 0xd4ee63452555a87048dcfe2a039208d113323790<br>(7) 0xc60c8a7b752d38e35e0359e25a2e0f6692b10d14<br>(8) 0xba7ec95286334e8634e89760fab8d2ec1226bf42<br>(9) 0x208e02303fe29be3698732e92ca32b88d80a2d36</pre><pre>Private Keys</pre><pre>==================</pre><pre>(0) a6de9563d3db157ed9926a993559dc177be74a23fd88ff5776ff0505d21fed2b<br>(1) 17f71d31360fbafbc90cad906723430e9694daed3c24e1e9e186b4e3ccf4d603<br>(2) ad2b90ce116945c11eaf081f60976d5d1d52f721e659887fcebce5c81ee6ce99<br>(3) 68e2288df55cbc3a13a2953508c8e0457e1e71cd8ae62f0c78c3a5c929f35430<br>(4) 9753b05bd606e2ffc65a190420524f2efc8b16edb8489e734a607f589f0b67a8<br>(5) 6e8e8c468cf75fd4de0406a1a32819036b9fa64163e8be5bb6f7914ac71251cc<br>(6) c287c82e2040d271b9a4e071190715d40c0b861eb248d5a671874f3ca6d978a9<br>(7) cec41ef9ccf6cb3007c759bf3fce8ca485239af1092065aa52b703fd04803c9d<br>(8) c890580206f0bbea67542246d09ab4bef7eeaa22c3448dcb7253ac2414a5362a<br>(9) eb8841a5ae34ff3f4248586e73fcb274a7f5dd2dc07b352d2c4b71132b3c73f</pre><pre>HD Wallet</pre><pre>==================<br>Mnemonic: cancel better shock lady capable main crunch alcohol derive alarm duck umbrella<br>Base HD Path: m/44&#39;/60&#39;/0&#39;/0/{account_index}<br>Listening on localhost:8545</pre><p>Notice that the ganache-cli creates 10 test accounts to play with automatically. These accounts come preloaded with 100 (fake) ethers.</p><h3>2. Simple voting contract</h3><p>We are going to use the solidity programming language to write our contract. If you are familiar with object oriented programming, learning to write solidity contracts should be a breeze. We will write a contract (think of contract as a class in your favorite OOP language) called Voting with a constructor which initializes an array of candidates. We will write 2 methods, one to return the total votes a candidate has received and another method to increment vote count for a candidate.</p><p>Note: The constructor is invoked once and only once when you deploy the contract to the blockchain. Unlike in the web world where every deploy of your code overwrites the old code, deployed code in the blockchain is immutable. i.e, If you update your contract and deploy again, the old contract will still be in the blockchain untouched along with all the data stored in it, the new deployment will create a new instance of the contract.</p><p>Below is the voting contract code with inline comment explanation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/444a9eca014380fdfaac2095c48e4bd0/href">https://medium.com/media/444a9eca014380fdfaac2095c48e4bd0/href</a></iframe><p>Copy the above code to a file named Voting.sol in the ethereum_voting_dapp/chapter1-ethersjs directory. Now let’s compile the code and deploy it to ganache blockchain. Follow the commands below to compile the contract.</p><pre>zastrin@macbook$ node_modules/.bin/solcjs — bin — abi Voting.sol<br>zastrin@macbook$ ls<br>Voting.sol Voting_sol_Voting.abi Voting_sol_Voting.bin</pre><p>When you compile the code successfully using the command above, the compiler outputs 2 files that are important to understand:</p><p>1. Voting_sol_Voting.bin: This is the bytecode you get when the source code in Voting.sol is compiled. This is the code which will be deployed to the blockchain.<br>2. Voting_sol_Voting.abi: This is an interface or template of the contract (called abi) which tells the contract user what methods are available in the contract. Whenever you have to interact with the contract in the future, you will need this abi definition. You can read more details about ABI <a href="https://solidity.readthedocs.io/en/develop/abi-spec.html">here</a></p><p>We will now use ethersjs library to deploy our application and interact with it.</p><p>First, run the ‘node’ command in your terminal to get in to the node console and initialize the ethers object. All the code snippets below need to be typed in the node console. To compile the contract, load the bytecode and abi from the file system in to a string like shown below</p><pre>zastrin@macbook$ node<br>&gt; ethers = require(‘ethers’)<br>&gt; bytecode = fs.readFileSync(‘Voting_sol_Voting.bin’).toString()<br>&gt; abi = JSON.parse(fs.readFileSync(‘Voting_sol_Voting.abi’).toString())</pre><p>Next is to initialize the provider which is a generic interface to connect to the blockchain. Since we are running the blockchain locally, we will use the JsonRPCProvider to connect to it. If you wanted to connect to a real blockchain, you have many other <a href="https://docs.ethers.io/ethers.js/html/api-providers.html">provider</a> options. Once connected, you can test the connection by querying ganache and listing all the accounts. Running the below commands in your nodejs console should list 10 accounts.</p><pre>&gt; provider = new ethers.providers.JsonRpcProvider()<br>&gt; provider.listAccounts().then(result =&gt; console.log(result))</pre><p>The next step is to initialize the signer which is used to sign the transactions. We can select which account we want to use (we have 10 accounts ganache in setup) by passing the index to getSigner as shown below. Once the wallet is intialized, create a contract factory and deploy the contract as shown. The deploy function takes an array of arguments that is passed to the constructor of the contract. In our case, we pass in the names of the candidates. We have to explicitly convert string to bytes32 because our contract takes bytes32 as argument.</p><pre>&gt; signer = provider.getSigner(0)<br>&gt; factory = new ethers.ContractFactory(abi, bytecode, signer)<br>&gt; contract = null<br>&gt; factory.deploy([ethers.utils.formatBytes32String(‘Rama’), ethers.utils.formatBytes32String(‘Nick’), ethers.utils.formatBytes32String(‘Jose’)]).then(© =&gt; { contract = c})</pre><p>If you successfully deployed the contract, your contract object should have all the details of the deployed contract. There are hundreds of thousands of contracts deployed on the blockchain. So, how do you identify your contract in that blockchain? Answer: contract.address. When you have to interact with your contract, you need this deployed address and abi definition we talked about earlier.</p><h3>3. Interact with the contract in the nodejs console</h3><pre>&gt; contract.totalVotesFor(ethers.utils.formatBytes32String(‘Rama’)).then((f) =&gt; console.log(f.toNumber()))<br>&gt; contract.voteForCandidate(ethers.utils.formatBytes32String(‘Rama’)).then((f) =&gt; console.log(f))<br>&gt; contract.totalVotesFor(ethers.utils.formatBytes32String(‘Rama’)).then((f) =&gt; console.log(f.toNumber()))</pre><p>Try the above commands in your node console and you should see the vote count increment. Every time you vote for a candidate, you get back a transaction id: Example: ‘0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53’ above). This transaction id is the proof that this transaction occurred and you can refer back to this at any time in the future. This transaction is immutable. This immutability is one of the big advantages of blockchains such as Ethereum.</p><h3>4. Webpage to connect to the blockchain and vote</h3><p>Now that most of the work is done, all we have to do now is create a simple html file with candidate names and invoke the voting commands (which we already tried and tested in the nodejs console) in a js file. Below you can find the html code and the js file. Drop both of them in the ethereum_voting_dapp/chapter1-ethersjs directory and open the index.html in your browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/686bc1f7b65ba0828870ccde19101b50/href">https://medium.com/media/686bc1f7b65ba0828870ccde19101b50/href</a></iframe><p>You should now see the vote counts and you should also be able to vote for candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCZhyqS9iCOoIVzsDzS5IA.png" /></figure><p>If you are using a wallet like Metamask, you will need to use a Web3 provider instead of JsonRPCProvider we used earlier. To do that, simply change the provider in your index.js to:</p><p>provider = new ethers.providers.Web3Provider(web3.currentProvider);</p><p>If you want to interact through Metamask, you can’t just open index.html and interact in your browser anymore. You have to server the file through a server. So, install a simple webserver and start like below</p><pre>zastrin@macbook$ npm install http-server<br>zastrin@macbook$ http-server</pre><p>You can now go to localhost:8080 and interact with your application. Below is a quick demo which includes loading test ether account into metamask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*brgwWBEkzSMfAxpI5Ei9EA.gif" /></figure><p>I hope you were able to follow along and get the application working.</p><p>If you run into issues getting the application working, feel free to DM me on twitter <a href="https://twitter.com/zastrinlab">@zastrinlab</a> or email <a href="/service/mailto:mahesh@zastrin.com">mahesh@zastrin.com</a>.</p><p>Thanks to <a href="https://twitter.com/ricmoo">Richard</a> for the feedback.</p><p><strong>If you liked this tutorial, check out more interesting real-world </strong><a href="http://www.zastrin.com/#courses"><strong>project based courses</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c561f9c4dd2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zastrin/build-an-ethereum-dapp-using-ethers-js-c561f9c4dd2f">Build an Ethereum dapp using ethers.js</a> was originally published in <a href="https://medium.com/zastrin">Zastrin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zastrin course licenses as NFTs]]></title>
            <link>https://medium.com/zastrin/zastrin-course-licenses-as-nfts-9b80e3554406?source=rss----cb7771de5c9c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b80e3554406</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[tokenization]]></category>
            <dc:creator><![CDATA[Mahesh Murthy]]></dc:creator>
            <pubDate>Tue, 08 Jan 2019 18:38:44 GMT</pubDate>
            <atom:updated>2019-01-08T18:38:43.904Z</atom:updated>
            <content:encoded><![CDATA[<h4>Experiment to tokenize courses</h4><p>At <a href="http://www.zastrin.com/">Zastrin</a>, we focus on creating the best online courses possible to help developers learn blockchain programming. Our courses are self-paced and hands-on where you learn by building an end to end real-world product.</p><p>We are also constantly thinking how blockchain can be leveraged in the education space. One of the common use cases some companies are tackling is certification (issuing certificates on the blockchain). We believe there are many more areas where blockchain can be used effectively. At <a href="http://www.zastrin.com/">Zastrin</a>, we wanted to explore the use case related to licensing the courses as Non Fungible Tokens (NFT). The following section explains our experiment, thought process, what we hope to learn from this experiment and our implementation details.</p><p><em>This article assumes that you know what Non Fungible Tokens are. If not, here is a quick </em><a href="https://hackernoon.com/an-overview-of-non-fungible-tokens-5f140c32a70a"><em>primer</em></a><em> or we have a </em><a href="http://www.zastrin.com/#courses"><em>complete developer’s guide course</em></a><em> that teaches you NFTs in depth and implementing an NFT application.</em></p><h4>Problem description</h4><p>When you purchase a (paper) book, you can hold on to it forever, gift it to someone or resell it in a marketplace like eBay, Amazon etc. You can also borrow books from a library for certain duration. Why can’t ebooks (online courses in our case) be bought and sold similarly in an open market? There are a number of edtech companies where you buy a course and you own it for the lifetime. Majority of the people don’t go back to the course once they have completed it. Wouldn’t it be nice if you could just resell it or gift it to someone?</p><p>It doesn’t make much sense to just copy the offline world to the online world because they are fundamentally different. It doesn’t take much additional resources to create multiple copies of the ebook/course. You should do it only if there are additional things you can do online (course software license) which you could never do offline (books). Few such use cases are:</p><ol><li><strong>Compensating the author</strong>: Every time the license changes hands, the course author should earn some commission. It is impossible to do this with books.</li><li><strong>Resale price</strong>: When you buy a second hand book, the price is mostly based on the condition of the book (new, good, acceptable etc). What if someone has done a really good job of highlighting important content, taken notes and want to sell all of it? That can’t be done with books but can definitely be done with online content.</li></ol><p><em>What other benefits can you think of? (Please let me know in the comments).</em></p><p>We wanted to see what would happen if these features are enabled for Zastrin courses. Would people start reselling their tokens, would they gift it, would they trade their Zastrin courses for Cryptokitties :) or would they just hold on to it forever? The next section explains how we used NFTs to accomplish this.</p><h4>How Zastrin NFTs work?</h4><p>To enable trading of Zastrin courses, we tokenized the course licenses using NFTs. What that means is, each course license is represented by a Non Fungible Token. If you own one of these tokens, you have the right to access that particular course on Zastrin. You can see all our courses on <a href="http://www.zastrin.com/#courses">our website</a> and you can see a few corresponding NFTs minted and listed on <a href="https://medium.com/u/b7346f3882bb">OpenSea</a> NFT marketplace <a href="https://opensea.io/assets/zastrincourses">https://opensea.io/assets/zastrincourses</a>.</p><p>Anyone who owns one of these NFTs can visit the link <a href="https://www.zastrin.com/courses/redeem">https://www.zastrin.com/courses/redeem</a> on a web3 enabled browser and get access to the course. There are a number of Ethereum wallets in the market that support NFTs. You can easily transfer it to another address or use OpenSea to transfer your token. If at some point you transfer your NFT to another user, you will lose access to the course as soon as they redeem the NFT.</p><h4>Why do you need Blockchain/NFT for this?</h4><p>If you understand how Zastrin NFTs work, I hope your next question is, why do you need blockchain/NFTs to implement these features? It could have been implemented with in the Zastrin webapp and it would work without any friction.</p><p>Here is why we feel it was worth tokenizing the courses:</p><ol><li>Once the course license is tokenized, any Ethereum wallet can automatically handle the license. License can be sent and received seamlessly since the token adheres to ERC721 standard. You only need to rely on zastrin website for accessing the course and not for trading.</li><li>There are many NFT exchanges and course licenses can be listed on all of them without any additional work (Our NFTs are currently listed on <a href="https://opensea.io/">OpenSea</a> and it was a smooth process). This will help with discovery and act as a new distribution channel.</li><li>Most of these exchanges allow you to set commission on sale. So the author gets compensated for every trade.</li><li>You can bundle multiple NFTs (courses) and innovate in pricing.</li><li>We plan to add highlighting and notes feature that will be associated with a license. NFTs will be priced differently based on these properties.</li></ol><p>Outside of these benefits, we believe this will be a good way to introduce people to the world of crypto and NFTs.</p><p>As mentioned in the beginning, this is an experiment. It might succeed or it might fail, we hope to learn from this experiment. If you can think of ways to improve, please let us know. Also, if you are an author who is interested in tokenizing your content, you can reach out to us at nft@zastrin.com.</p><p><strong>You can buy some courses for yourself or gift it to others by purchasing tokens at </strong><a href="https://opensea.io/assets/zastrincourses"><strong>https://opensea.io/assets/zastrincourses</strong></a></p><p>Happy #buidling!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b80e3554406" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zastrin/zastrin-course-licenses-as-nfts-9b80e3554406">Zastrin course licenses as NFTs</a> was originally published in <a href="https://medium.com/zastrin">Zastrin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to save your Ethereum Dapp users from paying gas for transactions]]></title>
            <link>https://medium.com/zastrin/how-to-save-your-ethereum-dapp-users-from-paying-gas-for-transactions-abd72f15e14d?source=rss----cb7771de5c9c---4</link>
            <guid isPermaLink="false">https://medium.com/p/abd72f15e14d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Mahesh Murthy]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 11:20:07 GMT</pubDate>
            <atom:updated>2018-05-10T11:20:35.698Z</atom:updated>
            <content:encoded><![CDATA[<h4>And instead you as a dapp owner pay for it</h4><p>One of the friction points for Ethereum dapp adoption is that the users have to pay gas(txn fee) to get their transactions recorded on the blockchain. For example, I have a simple <a href="https://www.zastrin.com/simple-ethereum-voting-dapp.html">voting dapp</a> that lets anyone vote for candidates and the votes are stored on the blockchain. A user who wants to record her vote on the blockchain has to pay a transaction/gas fee. This is not ideal because as a dapp owner, you are expecting your application users to have Ether to pay for gas when all they want to do is perform a simple action which has nothing to do with transferring money. But if the transaction needs to be executed on the blockchain, there is no other option but to pay the fee. What if there was a way for users to execute transactions securely (vote for a candidate in our example) and let someone else (potentially contract owner) record the transaction on the blockchain and pay for it?</p><p>Thanks to this tweet from <a href="https://medium.com/u/846ca283a13c">John Backus</a> which had just enough information to help me implement such a solution for my voting dapp.</p><h3>John Backus on Twitter</h3><p>Ethereum dApps will probably move to users signing blobs of data using private keys that don&#39;t actually hold any funds. dApp operators will submit txs including these signatures, proving the end user gave the 👍. Lets business pay for gas, deal with nonces, retry TXs, etc.</p><p>The entire working code is here: <a href="https://github.com/maheshmurthy/ethereum_voting_dapp/tree/master/chapter4">https://github.com/maheshmurthy/ethereum_voting_dapp/tree/master/chapter4</a></p><p>The demo application is here: <a href="https://www.zastrin.com/voting-dapp-without-paying-gas.html">https://www.zastrin.com/voting-dapp-without-paying-gas.html</a></p><p>I wanted to share details on how I implemented this solution for my simple dapp so more people can adopt this technique in their own dapps and could hopefully improve upon it. This post covers the following:</p><ol><li>A very high level overview of the public key cryptography and digital signatures which are key to understanding this solution</li><li>The solution details and the new application flow</li><li>Implementation details (frontend js and Solidity contract code)</li><li>Discuss potential issues and enhancements</li></ol><h3>Digital Signatures</h3><p>For this solution to make sense, you will need a basic understanding of how digital signatures work in cryptography. Feel free to skip this section if you know public key cryptography. I will try to explain the concept of public/private keys and digital signatures at a very high level but I highly recommend learning more in detail - <a href="https://en.wikipedia.org/wiki/Public-key_cryptography">wikipedia</a> is a good place to <a href="https://en.wikipedia.org/wiki/Digital_signature">start</a>.</p><p>Public key cryptography is a cryptographic system where you have 2 keys — public key (Pu) and a private key(Pr). You give out your public key to the entire world and keep the private key to yourself. Ex: You Ethereum address is a public key (It’s actually derived from Public key but for this exercise, let’s just think of it as public key) and your private key is stored either in your browser or on your phone/computer. As you know, for someone to send you Ether, they just need to know your public (account) address. However, only you can access the funds you own because you are the only one who knows your private key.</p><p>Public key cryptography has algorithms that let you encrypt, decrypt, sign and verify messages using your pair of keys.</p><p>Let’s see what signing and verifying a message means through an example. Let’s say user Kim has a pair of public/private keys</p><p>Pu = “0x44ac12c1e3dfd8edaf83b6f65918229d5279a6f5”</p><p>Pr = “dbc226043e390cf39280e5edfd418d7ad61931c76509270867d300f110c46506”</p><p>To sign a message, Kim executes a function sign(“Vote for Alice”, Pr) which outputs an alpha-numeric string</p><p>signature = 0x9127112de0033555c7f6508d963d484965a953844dfcff092712102c236467a25af57edc53b63880ea39af8ce7334f6d77a8206e805305e7c6ad919d12bfae5c1b</p><p>This is the digital signature of the message “Vote for Alice” signed by Kim using her private key Pr.</p><p>Now anyone can verify that message “Vote for Alice” was signed by Kim by executing the verify function, verify(“Vote for Alice”, signature) which outputs “0x44ac12c1e3dfd8edaf83b6f65918229d5279a6f5”. If you notice, that output is Kim’s public key Pu (remember, everyone knows it’s Kim’s public key) which means the message was definitely signed by Kim. If you tamper with the signature or message (by say changing even one character), the verify algorithm outputs a completely different public key and you will know that the message was tampered because the public key will be different from Pu.</p><h3><strong>Solution Details</strong></h3><p>If you understand digital signatures, the solution is extremely trivial. Let’s see how it can be used in our voting application to save users from paying gas fee without compromising their vote. You can see below all the users of dapp and the actions they perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*UdOleYl7ot02KidjG_Kd8A.png" /></figure><ol><li>A voter indicates their intention to vote for a candidate by signing a message using their private key. They won’t submit their transaction to the blockchain, so no txn fee is paid. The message queue in the diagram above is just an off chain location where all the vote details are stored.</li><li>Anyone willing to pay txn fee (usually the contract owner) takes the signature, candidate name and voter’s account address and submits them to the blockchain.</li><li>The smart contract uses the verify function to derive the public key (Ethereum account address) based on the candidate name and signature. If the derived public key matches the address of the user who signed the message, it records the vote or else fails the transaction.</li></ol><h3><strong>Implementation Details</strong></h3><p>Let’s now look at the actual implementation and how all the pieces fit together.</p><p><strong>Step 1: Sign the message</strong></p><p>The first step is to sign the message as a voter. We will use eth_signTypedData function to sign our message. This function has been implemented in Metamask which makes it really easy to sign messages. You can find more details and discussion about this proposal here: <a href="https://github.com/ethereum/EIPs/pull/712">https://github.com/ethereum/EIPs/pull/712</a>. You can find the code to sign the message below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a1bf2f5f06410852dc729813418ea8/href">https://medium.com/media/c5a1bf2f5f06410852dc729813418ea8/href</a></iframe><p>One really important thing to note is, internally <strong>eth_signTypedData</strong> hashes the message and the hashed message is what gets signed. You can refer to <strong>typedSignatureHash</strong> function <a href="https://github.com/MetaMask/eth-sig-util/blob/master/index.js">here</a> for more details on hashing.</p><p><strong>Step 2: Submit the signed vote to the blockchain</strong></p><p>Since this is just a demo application, we don’t store the signature and other details anywhere. It is directly displayed on the page after the message is signed. Anyone can take these details and submit to the blockchain. Here is the code that submits the vote to the blockchain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c410d1edfb2c2e7b8843b4186745dfc3/href">https://medium.com/media/c410d1edfb2c2e7b8843b4186745dfc3/href</a></iframe><p><strong>Step 3: Verify the vote details in the smart contract</strong></p><p>We now verify in the smart contract if the submitted vote info is valid and record the vote.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85dcc561f54d04fba971e46b01159459/href">https://medium.com/media/85dcc561f54d04fba971e46b01159459/href</a></iframe><p>Zeppelin has a <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ECRecovery.sol">handy library</a> called <strong>ECRecovery</strong> we use to verify the signed message. The <strong>voteForCandidate</strong> function verifies the signed message (recover function) and updates the vote count if the verification succeeds.</p><p>If you remember, I mentioned earlier that <strong>eth_signTypedData</strong> hashes the message (“Vote for Alice”) before signing it? The solidity recover function doesn’t have any knowledge of the hashing function used within <strong>eth_signTypedData</strong> and so it can’t verify the message “Vote for Alice”. It has to generate the hash of the message “Vote for Alice” and then verify it. Instead of generating the hash inside the contract, we pre-hash all the messages beforehand and pass it in the constructor so it is easy to lookup when verifying. The code to generate the hash is in the migration file below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b50cb1ba1c583f8af01a5de45b05b2c5/href">https://medium.com/media/b50cb1ba1c583f8af01a5de45b05b2c5/href</a></iframe><p>That is all the code you need to get the new application working!</p><p>I created a quick demo to show how this application works</p><p>The entire working code is here: <a href="https://github.com/maheshmurthy/ethereum_voting_dapp/tree/master/chapter4">https://github.com/maheshmurthy/ethereum_voting_dapp/tree/master/chapter4</a></p><p>The demo application is here: <a href="https://www.zastrin.com/voting-dapp-without-paying-gas.html">https://www.zastrin.com/voting-dapp-without-paying-gas.html</a></p><h3>Potential issues to address</h3><p>There are a few issues to consider when building a real dapp using this technique. Some of them are listed below:</p><ol><li>Where are the signed messages stored? You can use some kind of a queuing system to store these messages.</li><li>What is the guarantee that the signed message eventually is submitted to the blockchain?</li><li>Storing the hash of all the messages in the blockchain is not ideal, so what is the best solution for it?</li></ol><p>If you have thoughts on how to address these issues or if you see any flaws in this solution, please leave a comment!</p><p><strong>Note: Apparently, eth_signTypedData API is still not stable and has been implemented by only metamask. Please beware of this if you are planning to use this technique in mainnet/production.</strong></p><p>Further Reading</p><p><a href="https://en.wikipedia.org/wiki/Public-key_cryptography">https://en.wikipedia.org/wiki/Public-key_cryptography</a></p><p><a href="https://en.wikipedia.org/wiki/Digital_signature">https://en.wikipedia.org/wiki/Digital_signature</a></p><p><a href="https://github.com/danfinlay/js-eth-personal-sign-examples/">https://github.com/danfinlay/js-eth-personal-sign-examples/</a></p><p><a href="https://danfinlay.github.io/js-eth-personal-sign-examples/">https://danfinlay.github.io/js-eth-personal-sign-examples/</a></p><p><a href="https://github.com/ethereum/EIPs/pull/712">https://github.com/ethereum/EIPs/pull/712</a></p><p>Thanks <a href="https://medium.com/u/acd535aa0a46">Chris Whinfrey</a> and <a href="https://medium.com/u/75a616711f4e">Febin John James</a> for reviewing drafts of this article.</p><h3><strong>Learn More</strong></h3><p><strong>If you are interested in learning to build Ethereum decentralized applications, I have a few interesting courses at </strong><a href="http://www.zastrin.com/"><strong>www.zastrin.com</strong></a></p><p>If you would like to get notified when I write more tutorials, you can <a href="https://www.zastrin.com/home/subscribe">subscribe here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fupscri.be%2F5bb1c8%2F&amp;src=https%3A%2F%2Fupscri.be%2F5bb1c8%3Fas_embed%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/776e9a38f12013cde37bedc5d396f16b/href">https://medium.com/media/776e9a38f12013cde37bedc5d396f16b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd72f15e14d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zastrin/how-to-save-your-ethereum-dapp-users-from-paying-gas-for-transactions-abd72f15e14d">How to save your Ethereum Dapp users from paying gas for transactions</a> was originally published in <a href="https://medium.com/zastrin">Zastrin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello, World!]]></title>
            <link>https://medium.com/zastrin/hello-world-bc510926bf20?source=rss----cb7771de5c9c---4</link>
            <guid isPermaLink="false">https://medium.com/p/bc510926bf20</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[zastrin]]></category>
            <category><![CDATA[project-based-learning]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Mahesh Murthy]]></dc:creator>
            <pubDate>Fri, 23 Feb 2018 14:37:22 GMT</pubDate>
            <atom:updated>2018-02-26T23:36:36.869Z</atom:updated>
            <content:encoded><![CDATA[<p>Every software developer’s first program is usually to print a simple ‘hello, world!’. This is how the journey begins, in to the beautiful world of programming. You then go on to build bigger, more complex things to improve the world we live in (right?!). The ‘hello, world’ moment for me with Ethereum was about 15 months ago when I started learning Solidity and building smart contracts and Dapps. I have been hooked since then.</p><p>Blockchain is so fascinating and revolutionary that I wanted to do my part in helping this technology go mainstream. What better way to do that than bring more developers in to this space and help them learn and build products and solutions?! That was the reason I started <a href="http://www.zastrin.com/">Zastrin</a>. If I can help one developer learn this and she goes on to create a decentralized bank and brings 1,000,000 unbanked in to the system, I would have indirectly helped 1,000,000 people!</p><p>I have always believed that you best learn new technologies by tinkering and building projects. This is what I am trying to emulate at <a href="http://www.zastrin.com/">Zastrin</a>. I want this to be a place where people learn, build and share their projects. The response and support I have received since I started Zastrin has far exceeded my expectations. I hope to continue creating more courses and trying new things. I want Zastrin to be more than just offer courses. I want to run more blockchain experiments and share the lessons here. I have many projects in the works. So stay tuned!</p><p>Many people have asked, what does Zastrin mean? It means ‘Armed with knowledge’ in Sanskrit — an ancient Indian language. So, arm yourself with knowledge and go #buidl something!</p><p>If you want to learn more about my thoughts and ideas, you can reach me at mahesh@zastrin.com.</p><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc510926bf20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zastrin/hello-world-bc510926bf20">Hello, World!</a> was originally published in <a href="https://medium.com/zastrin">Zastrin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>