Ethereum blockchain development tutorial

By | Saturday, February 27, 2021

Navigation

  • Build a Zombie Army
  • A practical Ethereum and MultiChain blockchain tutorial
  • Ethereum Developer Certification Course
  • What is a Smart Contract?
  • Build a Zombie Army

    Maintain a data store representing something which is useful to either other contracts or to the outside world; one example of this is a contract that simulates a currency, and another is a contract that records membership in a particular organization. More complex forwarding contracts have different conditions based on the nature of the message sent; the simplest use case for this functionality is a withdrawal limit that is overrideable via some more complicated access procedure.

    Manage an ongoing contract or relationship between multiple users. Examples of this include a financial contract, an escrow with some particular set of mediators, or some kind of insurance. One can also have an open contract that one party leaves open for any other party to engage with at any time; one example of this is a contract that automatically pays a bounty to whoever submits a valid solution to some mathematical problem, or proves that it is providing some computational resource.

    When a contract receives a message it has the option of returning some data, which the original sender of the message can then immediately use. In this way, sending a message is exactly like calling a function.

    Because contracts can play such different roles, we expect that contracts will be interacting with each other. However, Alice is very security-conscious, and as her primary account uses a forwarding contract which only sends messages with the approval of two out of three private keys. We can show the relationships between the accounts thus:.

    We can see these steps in the following diagram:. Computation in the EVM is done using a stack-based bytecode language that is like a cross between Bitcoin Script, traditional assembly and Lisp the Lisp part being due to the recursive message-sending functionality.

    A program in EVM is a sequence of opcodes, like this:. The purpose of this particular contract is to serve as a name registry; anyone can send a message containing 64 bytes of data, 32 for the key and 32 for the value. The contract checks if the key has already been registered in storage, and if it has not been then the contract registers the value at that key. At the start of execution, memory and stack are empty and the PC is zero.

    The instruction at position 0 is PUSH1, which pushes a one-byte value onto the stack and jumps two steps in the code. Thus, we have:. Recall that the first 32 bytes here encode SLOAD pops one from the stack and checks if there is a value in storage for the key popped from the stack.

    If so, it pushes the value into the stack at the current index. Since the contract is used for the first time, the storage is empty and no value is found for the popped key.

    The JUMPI instruction pops 2 values and jumps to the instruction designated by the first only if the second is nonzero. Here, the second is nonzero, so we jump. In order to do this, we'll need to create a new file in the migrations directory.

    From your project root, create a new file from the command line like this:. Notice that we number all of our files inside the migrations directory with numbers so that Truffle knows which order to execute them in.

    Let's create a new migration to deploy the contract like this:. First, we require the contract we've created, and assign it to a variable called "Election". Next, we add it to the manifest of deployed contracts to ensure that it gets deployed when we run the migrations.

    Now let's run our migrations from the command line like this:. Now that we have successfully migrated our smart contract to the local Ethereum blockchain, let's open the console to interact with the smart contract. You can open the truffle console from the command line like this:. Now that we're inside the console, let's get an instance of our deployed smart contract and see if we can read the candidate's name from the contract.

    From the console, run this code:. Here Election is the name of the variable that we created in the migration file. We retrieved a deployed instance of the contract with the deployed function, and assigned it to an app variable inside the promise's callback function.

    This might look a little confusing at first, but you can reference the console demonstration in the video at for further explanation.

    You've just written your first smart contract, deployed to the blockchain, and retrieved some of its data. Now that everything is set up properly, let's continue building out the smart contact by listing out the candidates that will run in the election.

    We need a way to store multiple candidates, and store multiple attributes about each candidate. We want to keep track of a candidate's id, name, and vote count. Here is how we will model the candidate:. We have modeled the candidate with a Solidity Struct.

    Solidity allows us to create our own structure types as we've done for our candidate here. We specified that this struct has an id of unsigned integer type, name of string type, and voteCount of unsigned integer type. Simply declaring this struct won't actually give us a candidate.

    We need to instantiate it and assign it to a variable before we can write it to storage. The next thing we need is a place to store the candidates. We need a place to store one of the structure types that we've just created. We can do this with a Solidity mapping. A mapping in Solidity is like an associative array or a hash, that associates key-value pairs. We can create this mapping like this:.

    In this case, the key to the mapping is an unsigned integer , and the value is a Candidate structure type that we just defined. This essentially gives us an id-based look up for each candidate. Since this mapping is assigned to a state variable, we will write data to the blockchain anytime we assign new key-value pairs to it. Next, we set this mapping's visibility to public in order to get a getter function, just like we did with the candidate name in the smoke test.

    Next, we keep track of how many candidates exist in the election with a counter cache state variable like this:. In Solidity, there is no way to determine the size of a mapping, and no way to iterate over it, either. That's because any key in a mapping that hasn't been assigned a value yet will return a default value an empty candidate in this case. For example, if we only had 2 candidates in this election, and we try to look up candidate 99, then the mapping will return an empty Candidate structure.

    This behavior makes it impossible to know how many candidates exist, and therefore we must use a counter cache. We've declared the function addCandidate that takes one argument of string type that represents the candidate's name. Inside the function, we increment the candidate counter cache to denote that a new candidate has been added.

    Then we update the mapping with a new Candidate struct, using the current candidate count as the key.

    This Candidate struct is initialized with the candidate id from the current candidate count, the name from the function argument, and the initial vote count to 0. Note that this function's visibility is private because we only want to call it inside the contract. Now we can add two candidates to our election by calling the "addCandidate" function twice inside the constructor function like this:.

    This migration will execute when we deploy the contract to the blockchain, and populate our election with two candidates. At this point, your complete contract code should look like this:.

    Now try to interact with the candidates inside the console. You can follow along with me as I demonstrate this in the video at I'll leave that to you as an exercise. Now let's write some tests to ensure that our smart contract is initialized correctly. First, let me explain why testing is so important when you're developing smart contracts. We want to ensure that the contracts are bug free for a few reasons:.

    All of the code on the Ethereum blockchain is immutable; it cannot change. If the contract contains any bugs, we must disable it and deploy a new copy. This new copy will not have the same state as the old contract, and it will have a different address. Deploying contracts costs gas because it creates a transaction and writes data to the blockchain. This costs Ether, and we want to minimize the amount of Ether we ever have to pay.

    If any of our contract functions that write to the blockchain contain bugs, the account who is calling this function could potentially waste Ether, and it might not behave the way they expect. Now let's write some tests. Make sure you have Ganache running first. Then, create a new test file in the command line from the root of your project like this:. We'll write all our tests in Javascript inside this file with the Mocha testing framework and the Chai assertion library.

    These come bundled with the Truffle framework. We'll write all these tests in Javascript to simulate client-side interaction with our smart contract, much like we did in the console. Here is all the code for the tests:. First, we require the require the contract and assign it to a variable, like we did in the migration file. Next, we call the "contract" function, and write all our tests within the callback function.

    This callback function provides an "accounts" variable that represents all the accounts on our blockchain, provided by Ganache. The first test checks that the contract was initialized with the correct number of candidates by checking the candidates count is equal to 2. The next test inspects the values of each candidate in the election, ensuring that each candidate has the correct id, name, and vote count.

    Yay, they pass! Now let's start building out the client-side application that will talk to our smart contract. We'll use this existing code to get started. Let's also take note of a few other things that came with the Truffle Pet Shop box like the Bootstrap framework that will keep us from having to write any CSS in this tutorial.

    We also got lite-server , which will serve our assets for development purposes. You do not have to be a front-end expert to follow along with this part of the tutorial. I have intentionally kept the HTML and Javascript code very simple, and we will not spend much time focusing on it.

    I want to stay focused on developing the smart contract portion of our dApp! You can watch me explain this code more in depth in the video at Now let's view the client-side application in the browser. Ether can be transferred between accounts for compensating participant mining nodes for the computations they have performed. As an altcoin, ether has slowly carved a niche for itself in the blockchain domain.

    Flexibility being at its core, ether is a cryptocurrency that needs no introduction. Wherever there is a need to establish a channel between, participating nodes in a blockchain transaction, ether is your go-to cryptocurrency. Also, Ethereum provides a decentralized virtual machine, the Ethereum Virtual Machine EVM , which can be leveraged to execute scripts using an international network of public nodes.

    Moreover, within Ethereum, there is a second type of token that is used to pay miners fees for including transactions in their block. Every smart contract execution on Ethereum requires a certain amount of gas to be sent along with it to entice miners to put it in the blockchain. Any service which is centralized initially can be decentralized using Ethereum. From services like loans to their intermediary counterparts, Ethereum can revolutionize thousands of processes that exist across different industries and verticals.

    Now think, if all of them get decentralized, how secure and efficient would every aspect of human existence become. Ethereum can also be used to build decentralized autonomous organizations DAOs.

    Fully autonomous, and decentralized organizations with no single leader, DAOs are operated by programming codes, on a collection of smart contracts written on the Ethereum blockchain. A DAO is owned by everyone who purchases tokens. However, instead of each token equating to equity shares and ownership, they act as contributions that give people voting rights for a consensus. Ethereum has recently created a new standard.

    Ethereum blockchain development tutorial

    Light mode. Search No results for your search "". Search away! Ethereum Development Tutorials Welcome to our curated list of community tutorials.

    Using WebSockets beginner. Create and deploy a DeFi App intermediate. Waffle: Dynamic mocking and testing contract calls intermediate. Sending Transactions Using Web3 and Alchemy beginner. Waffle say hello world tutorial with hardhat and ethers basic. Testing smart contracts with Waffle intermediate. A Python developer's introduction to Ethereum, part 1 beginner. Smart contract security checklist intermediate. A guide to smart contract security tools intermediate. Smart contract security guidelines intermediate.

    The Graph: Fixing Web3 data querying intermediate. Token integration checklist intermediate. Downsizing contracts to fight the contract size limit intermediate. How to run a light node with Geth intermediate. How to use Slither to find smart contract bugs advanced. Solidity and Truffle continuous integration setup intermediate. How to mock Solidity smart contracts for testing intermediate.

    If you want a more complete understanding of blockchain before diving into this tutorial, you might start with the bitcoin white paper , ethereum yellow paper , and multichain white paper. There are also many existing blockchain tutorials which describe the underlying architecture of blockchain see, for example, this one.

    The Ethereum website also provides a nice list of tutorials , which we found especially useful and clear. Just briefly, a blockchain is a data structure stored in a network of computers. The network is decentralized and distributed to avoid single point of failure, and each node stores a copy of the chain. Nodes in the network can be lost without compromising the integrity of the network or the data due to the redundancy. The blockchain data structure itself logs information about network accounts and transactions.

    Above is a simple sketch illustrating a blockchain network, but of course this is an oversimplification. If you want to think about this more deeply, please consult the tutorials and white papers linked above. If you are interested in learning how to develop smart contracts, you should consult other tutorials. In this one, we will provide a very simple smart contract and explain how to deploy and interact with it. We have tried two different methods for doing this, and have found Method 2 to be more successful.

    But we will describe both methods below. But first, after configuring this private blockchain test network we ultimately want to be able to deploy and interact with a smart contract. Smart contracts can do any number of things, but we will use this simple one for setting and getting a value. Configure your smart contract as follows:.

    This is the smart contract we will be deploying and interacting with on a private Ethereum test network. This will open the Geth JavaScript console, from which you can manage user accounts and deploy smart contracts.

    The basic test network configuration is ready! Now for deploying and interacting with the SetGet smart contract. Make sure you have the solidity compiler installed by following these instructions in the official solidity documentation. Open a third terminal tab and navigate to the directory containing SetGet.

    Run the following command to generate the application binary interface abi of the SetGet contract: solcjs --abi SetGet. For a detailed explanation of the abi, see the solidity docs. Run the following command to generate the binary file of the contract: solcjs --bin SetGet.

    Also, it highlights ether, and the Ethereum blockchain size. An open-source, public, and blockchain-based distributed computing platform and operating system featuring a smart contract functionality, Ethereum enables distributed applications to be built and executed without any downtime, fraud, control, or interference from a third-party entity. Ethereum is not just a platform but also a Turing-complete programming language running on a Blockchain that helps developers publish distributed applications.

    Ethereum Blockchain Size depends solely on implementation. However, it is far from the only application. Not only being meant to transfer funds on blockchains, but Ethereum also has a plethora of applications. Ether is a cryptocurrency whose blockchain is generated in the Ethereum platform. Ether can be transferred between accounts for compensating participant mining nodes for the computations they have performed.

    As an altcoin, ether has slowly carved a niche for itself in the blockchain domain. Flexibility being at its core, ether is a cryptocurrency that needs no introduction.

    Wherever there is a need to establish a channel between, participating nodes in a blockchain transaction, ether is your go-to cryptocurrency. Also, Ethereum provides a decentralized virtual machine, the Ethereum Virtual Machine EVM , which can be leveraged to execute scripts using an international network of public nodes. Moreover, within Ethereum, there is a second type of token that is used to pay miners fees for including transactions in their block. Every smart contract execution on Ethereum requires a certain amount of gas to be sent along with it to entice miners to put it in the blockchain.

    Any service which is centralized initially can be decentralized using Ethereum.

    A practical Ethereum and MultiChain blockchain tutorial

    Flexibility being at its core, ether is a cryptocurrency that needs no introduction. Wherever there is a need to establish a channel between, participating nodes in a blockchain transaction, ether is your go-to cryptocurrency. Also, Ethereum provides a decentralized virtual machine, the Ethereum Virtual Machine EVM , which can be leveraged to execute scripts using an international network of public nodes.

    Moreover, within Ethereum, there is a second type of token that is used to pay miners fees for including transactions in their block. Every smart contract execution on Ethereum requires a certain amount of gas to be sent along with it to entice miners to put it in the blockchain.

    Any service which is centralized initially can be decentralized using Ethereum. From services like loans to their intermediary counterparts, Ethereum can revolutionize thousands of processes that exist across different industries and verticals. Now think, if all of them get decentralized, how secure and efficient would every aspect of human existence become.

    Ethereum can also be used to build decentralized autonomous organizations DAOs. Fully autonomous, and decentralized organizations with no single leader, DAOs are operated by programming codes, on a collection of smart contracts written on the Ethereum blockchain.

    A DAO is owned by everyone who purchases tokens. However, instead of each token equating to equity shares and ownership, they act as contributions that give people voting rights for a consensus. Ethereum has recently created a new standard. Termed as the ERC token, this standard is used for tracking unique digital assets. A major use case for these tokens is digital collectibles.

    But first, after configuring this private blockchain test network we ultimately want to be able to deploy and interact with a smart contract.

    Smart contracts can do any number of things, but we will use this simple one for setting and getting a value. Configure your smart contract as follows:.

    This is the smart contract we will be deploying and interacting with on a private Ethereum test network. This will open the Geth JavaScript console, from which you can manage user accounts and deploy smart contracts. The basic test network configuration is ready! Now for deploying and interacting with the SetGet smart contract. Make sure you have the solidity compiler installed by following these instructions in the official solidity documentation.

    Open a third terminal tab and navigate to the directory containing SetGet. Run the following command to generate the application binary interface abi of the SetGet contract: solcjs --abi SetGet. For a detailed explanation of the abi, see the solidity docs. Run the following command to generate the binary file of the contract: solcjs --bin SetGet.

    This will output the hex-encoded binary to be provided with the transaction request. Return to the second terminal tab, the one with the geth javacsript console. Run personal , and you should see there are no existing accounts. Run personal. Make sure your new account is unlocked enter the password you set in step 12 when prompted :. Method 1 is fine, but requires several steps to deploy the contract and when deployment is unsuccessful, the error messages and documentation can be difficult to decipher.

    Deployment with Truffle is a useful alternative. Truffle is an ethereum development tool which is great for testing, and can be used to deploy smart contracts easily. Install Truffle. Follow these instructions on the official truffle documentation. At the same level of the myBlockchain dir, mkdir truffle.

    This will configure a set of directories:. From the truffle dir, run truffle console. Further lessons 1 released each week will add more functionality to your game, like the ability to battle other people's zombies! After completing all lessons and deploying your DApp, pit your zombie army against other players' zombies in one of the world's first blockchain-based games!

    Half code-school, half MMO crypto-collectible strategy game. What are you waiting for? Click the button below to dive into lesson 1 and build your first DApp.

    It's free! Powered by Loom Network - a platform for building commerical scale apps on Ethereum. Perfect for absolute beginners, we walk you through basic concepts all the way to building your first DApp.

    Ethereum Developer Certification Course

    Ethereum blockchain development tutorial

    But we will describe both methods below. But first, after configuring this private blockchain test network we ultimately want to be able to deploy and interact with a smart contract. Smart contracts can do any number of things, but we will use this simple one for setting and getting a value. Configure your smart contract as follows:. This is the smart contract we will be deploying and interacting with on a private Ethereum test network.

    This will open the Geth JavaScript console, from which you can manage user accounts and deploy smart contracts. The basic test network configuration is ready! Now for deploying and interacting with the SetGet smart contract.

    Make sure you have the solidity compiler installed by following these instructions in the official solidity documentation. Open a third terminal tab and navigate to the directory containing SetGet. Run the following command to generate the application binary interface abi of the SetGet contract: solcjs --abi SetGet.

    For a detailed explanation of the abi, see the solidity docs. Run the following command to generate the binary file of the contract: solcjs --bin SetGet. This will output the hex-encoded binary to be provided with the transaction request. Return to the second terminal tab, the one with the geth javacsript console. Run personal , and you should see there are no existing accounts. Run personal. Make sure your new account is unlocked enter the password you set in step 12 when prompted :.

    Method 1 is fine, but requires several steps to deploy the contract and when deployment is unsuccessful, the error messages and documentation can be difficult to decipher. Deployment with Truffle is a useful alternative. Truffle is an ethereum development tool which is great for testing, and can be used to deploy smart contracts easily. Install Truffle.

    Follow these instructions on the official truffle documentation. At the same level of the myBlockchain dir, mkdir truffle. This will configure a set of directories:. From the truffle dir, run truffle console. This will open a JavaScript console from which you can manage user accounts and deploy smart contracts.

    The basic test network configuration is now ready! Now you can deploy and interact with the SetGet smart contract via Truffle. In the truffle console, enter migrate. Interact with the contract: instance. These are two ways to deploy a smart contract to a private geth test network using the geth console method 1 or truffle method 2!

    These methods should be very useful when developing and testing a smart contract. Though the smart contract we used was very simple, you can write contracts to perform a number of tasks.

    Ethereum is a popular option for blockchain development because it uses smart contracts. But, there are other platforms such as MultiChain that can also be used to run private blockchains. MultiChain does not support smart contracts, but it does have a built-in stream feature, which can be used for key:value retrieval of data.

    Here we will go the steps to configure and run a private MultiChain. We'll write tests against the smart contract, deploy it to the Ethereum blockchain, and develop a client-side application that allows accounts to cast votes. We'll also examine key concepts like "what is a blockchain? You can watch me build the full decentralized application in the 2-hour video above. I'll also guide you through the step-by-step instructions in this tutorial.

    Before we start building our dApp, let's examine some key concepts. If you are eager to start coding, feel free to skip ahead to the next part of the tutorial. You can also download all the video content to the full 2-hour video tutorial here for free 🎉. Normally when you interact with a web application, you use a web browser to connect to a central server over a network.

    All the code of this web application lives on this central server, and all the data lives in a central database. Anytime you transact with your application, must communicate with this central server on the web. We want to build it on the blockchain where anyone connected to the network can participate in the election.

    We want to ensure that their votes are counted, and that they are only counted once. Instead of having a network, a central server, and a database, the blockchain is a network and a database all in one. A blockchain is a peer-to-peer network of computers, called nodes, that share all the data and the code in the network.

    You now have a copy of all the data and the code on the blockchain. There are no more central servers. Just a bunch of computers that talk to one another on the same network. Instead of a centralized database, all the transaction data that is shared across the nodes in the blockchain is contained in bundles of records called blocks, which are chained together to create the public ledger.

    This public ledger represents all the data in the blockchain. All the data in the public ledger is secured by cryptographic hashing, and validated by a consensus algorithm. Nodes on the network participate to ensure that all copies of the data distributed across the network are the same. What would it look like for a user of our application to vote on the blockchain?

    Well, for starters, the user needs an account with a wallet address with some Ether, Ethereum's cryptocurrency. Once they connect to the network, they cast their vote and pay a small transaction fee to write this transaction to the blockchain. Whenever the vote is cast, some of the nodes on the network, called miners, compete to complete this transaction. The miner who completes this transaction is awarded the Ether that we paid to vote.

    As a recap, when I vote, I pay a gas price to vote, and when my vote gets recorded, one of the computers on the network gets paid the my Ether fee. I in turn am confident my vote was recorded accurately forever.

    Well, the Ethereum blockchain allows us to execute code with the Ethereum Virtual Machine EVM on the blockchain with something called a smart contract. Smart contracts are where all the business logic of our application lives. Smart contracts are in charge of reading and writing data to the blockchain, as well as executing business logic.

    Smart contacts are written in a programming language called Solidity , which looks a lot like Javascript. The function of smart contracts on the blockchain is very similar to a microservice on the web. If the public ledger represents the database layer of the blockchain, then smart contracts are where all the business logic that transacts with that data lives.

    Also, they're called smart contracts because they represent a covenant or agreement. In the case of our voting dApp, it is an agreement that my vote will count, that other votes are only counted once, and that the candidate with the most votes will actually win the election.

    Now let's jump in and start programming! We'll build a client-side application that will talk to our smart contract on the blockchain. This client-side application will have a table of candidates that lists each candidate's id, name, and vote count. It will have a form where we can cast a vote for our desired candidate. It also shows the account we're connected to the blockchain with under "your account". The accompanying video footage for this portion of the tutorial begins at You can see if you have node already installed by going to your terminal and typing:.

    The next dependency is the Truffle Framework , which allows us to build decentralized applications on the Ethereum blockchain. It provides a suite of tools that allow us to write smart contacts with the Solidity programming language.

    It also enables us to test our smart contracts and deploy them to the blockchain. It also gives us a place to develop our client-side application. The next dependency is Ganache , a local in-memory blockchain. You can install Ganache by downloading it from the Truffle Framework website. It will give us 10 external accounts with addresses on our local Ethereum blockchain. Each account is preloaded with fake ether. The next dependency is the Metamask extension for Google Chrome.

    In order to use the blockchain, we must connect to it remember, I said the block chain is a network. Reference the video walk through if you get stuck! The dependency is optional, but recommended. I recommend installing syntax highlighting for the Solidity programming language.

    You can download the code for this portion of the tutorial here. Feel free to use these as a reference point if you get stuck! First, find where you downloaded Ganache , and open it. Now that Ganache has booted, you have a local blockchain running. Ganache gave us 10 accounts preloaded with fake Ether this isn't worth anything on the main Ethereum network.

    Each account has a unique address and a private key. Each account address will serve as a unique identifier for each voter in our election. Now that we're inside our project, we can get up and running fast with a Truffle box. We'll be using the Pet Shop box for this tutorial. From within your project directory, install the pet shop box from the command line like this:.

    Now let's start writing our smart contract! This smart contract will contain all the business logic of our dApp. It will be in charge reading from and write to the Ethereum blockchain. It will allow us to list the candidates that will run in the election, and keep track of all the votes and voters. It will also govern all of the rules of the election, like enforcing accounts to only vote once. From the root of your project, go ahead and create a new contract file in the contracts directory like this:.

    Let's start by creating a "smoke test" that will ensure that we've set up our project properly, and that we can deploy the contract to the blockchain successfully.

    Open the file and start with the following code:. Let me explain this code. We start by declaring the solidity version with the pragma solidity statement.

    Next, we declare the smart contract with the "contract" keyword, followed by the contract name. Next, we declare a state variable that will store the value of the candidate name. State variables allow us to write data to the blockchain. We have declared that this variable will be a string, and we have set its visibility to public.

    Because it is public, solidity will give us a getter function for free that will allow us to access this value outside of our contract. We'll see that in action later in the console! Then, we create a constructor function that will get called whenever we deploy the smart contract to the blockchain.

    This is where we'll set the value of the candidate state variable that will get stored to the blockchain upon migration. Notice that the constructor function has the same name as the smart contract. This is how Solidity knows that the function is a constructor.

    Now that we've created the foundation for the smart contract, let's see if we can deploy it to the blockchain. In order to do this, we'll need to create a new file in the migrations directory. From your project root, create a new file from the command line like this:. Notice that we number all of our files inside the migrations directory with numbers so that Truffle knows which order to execute them in.

    Let's create a new migration to deploy the contract like this:. First, we require the contract we've created, and assign it to a variable called "Election". Next, we add it to the manifest of deployed contracts to ensure that it gets deployed when we run the migrations. Now let's run our migrations from the command line like this:.

    Now that we have successfully migrated our smart contract to the local Ethereum blockchain, let's open the console to interact with the smart contract. You can open the truffle console from the command line like this:. Now that we're inside the console, let's get an instance of our deployed smart contract and see if we can read the candidate's name from the contract. From the console, run this code:. Here Election is the name of the variable that we created in the migration file.

    We retrieved a deployed instance of the contract with the deployed function, and assigned it to an app variable inside the promise's callback function.

    This might look a little confusing at first, but you can reference the console demonstration in the video at for further explanation. You've just written your first smart contract, deployed to the blockchain, and retrieved some of its data. Now that everything is set up properly, let's continue building out the smart contact by listing out the candidates that will run in the election.

    We need a way to store multiple candidates, and store multiple attributes about each candidate. We want to keep track of a candidate's id, name, and vote count. Here is how we will model the candidate:. We have modeled the candidate with a Solidity Struct. Solidity allows us to create our own structure types as we've done for our candidate here. We specified that this struct has an id of unsigned integer type, name of string type, and voteCount of unsigned integer type.

    Simply declaring this struct won't actually give us a candidate. We need to instantiate it and assign it to a variable before we can write it to storage. The next thing we need is a place to store the candidates. We need a place to store one of the structure types that we've just created. We can do this with a Solidity mapping.

    A mapping in Solidity is like an associative array or a hash, that associates key-value pairs. We can create this mapping like this:. In this case, the key to the mapping is an unsigned integer , and the value is a Candidate structure type that we just defined. This essentially gives us an id-based look up for each candidate. Since this mapping is assigned to a state variable, we will write data to the blockchain anytime we assign new key-value pairs to it.

    Next, we set this mapping's visibility to public in order to get a getter function, just like we did with the candidate name in the smoke test.

    What is a Smart Contract?

    We can do this with a Solidity mapping. A mapping in Solidity is like an associative array or a hash, that associates key-value pairs. We can create this mapping like this:. In this case, the key to the mapping is an unsigned integer , and the value is a Candidate structure type that we just defined. This essentially gives us an id-based look up for each candidate.

    Since this mapping is assigned to a state variable, we will write data to the blockchain anytime we assign new key-value pairs to it. Next, we set this mapping's visibility to public in order to get a getter function, just like we did with the candidate name in the smoke test. Next, we keep track of how many candidates exist in the election with a counter cache state variable like this:. In Solidity, there is no way to determine the size of a mapping, and no way to iterate over it, either.

    That's because any key in a mapping that hasn't been assigned a value yet will return a default value an empty candidate in this case. For example, if we only had 2 candidates in this election, and we try to look up candidate 99, then the mapping will return an empty Candidate structure. This behavior makes it impossible to know how many candidates exist, and therefore we must use a counter cache.

    We've declared the function addCandidate that takes one argument of string type that represents the candidate's name. Inside the function, we increment the candidate counter cache to denote that a new candidate has been added. Then we update the mapping with a new Candidate struct, using the current candidate count as the key. This Candidate struct is initialized with the candidate id from the current candidate count, the name from the function argument, and the initial vote count to 0.

    Note that this function's visibility is private because we only want to call it inside the contract. Now we can add two candidates to our election by calling the "addCandidate" function twice inside the constructor function like this:.

    This migration will execute when we deploy the contract to the blockchain, and populate our election with two candidates. At this point, your complete contract code should look like this:. Now try to interact with the candidates inside the console. You can follow along with me as I demonstrate this in the video at I'll leave that to you as an exercise.

    Now let's write some tests to ensure that our smart contract is initialized correctly. First, let me explain why testing is so important when you're developing smart contracts. We want to ensure that the contracts are bug free for a few reasons:. All of the code on the Ethereum blockchain is immutable; it cannot change.

    If the contract contains any bugs, we must disable it and deploy a new copy. This new copy will not have the same state as the old contract, and it will have a different address. Deploying contracts costs gas because it creates a transaction and writes data to the blockchain.

    This costs Ether, and we want to minimize the amount of Ether we ever have to pay. If any of our contract functions that write to the blockchain contain bugs, the account who is calling this function could potentially waste Ether, and it might not behave the way they expect. Now let's write some tests. Make sure you have Ganache running first. Then, create a new test file in the command line from the root of your project like this:.

    We'll write all our tests in Javascript inside this file with the Mocha testing framework and the Chai assertion library. These come bundled with the Truffle framework. We'll write all these tests in Javascript to simulate client-side interaction with our smart contract, much like we did in the console. Here is all the code for the tests:. First, we require the require the contract and assign it to a variable, like we did in the migration file.

    Next, we call the "contract" function, and write all our tests within the callback function. This callback function provides an "accounts" variable that represents all the accounts on our blockchain, provided by Ganache. The first test checks that the contract was initialized with the correct number of candidates by checking the candidates count is equal to 2. The next test inspects the values of each candidate in the election, ensuring that each candidate has the correct id, name, and vote count.

    Yay, they pass! Now let's start building out the client-side application that will talk to our smart contract. We'll use this existing code to get started. Let's also take note of a few other things that came with the Truffle Pet Shop box like the Bootstrap framework that will keep us from having to write any CSS in this tutorial. We also got lite-server , which will serve our assets for development purposes. You do not have to be a front-end expert to follow along with this part of the tutorial.

    I have intentionally kept the HTML and Javascript code very simple, and we will not spend much time focusing on it. I want to stay focused on developing the smart contract portion of our dApp! You can watch me explain this code more in depth in the video at Now let's view the client-side application in the browser. First, make sure that you've migrated your contracts like this:. Notice that your application says "Loading That's because we're not logged in to the blockchain yet!

    In order to connect to the blockchain, we need to import one of the accounts from Ganache into Metamask. You can watch me set up Metamask in the video at Now let's add the ability to cast votes in the election. Let's define a "voters" mapping to the smart contract to keep track of the accounts that have voted in the election like this:. Let's look at a few other things that it does:. Watch me explain voting in depth at You can also watch me demonstrate voting in the console at Next we can write a few test for our function's requirements.

    Let's write a test to ensure that our vote function throws an exception for double voting:. We can assert that the transaction failed and that an error message is returned. We can dig into this error message to ensure that the error message contains the "revert" substring.

    Then we can ensure that our contract's state was unaltered by ensuring that the candidates did not receive any votes. First, we'll set up a test scenario with a fresh account that hasn't voted yet. Then we'll cast a vote on their behalf.

    Then we'll try to vote again. We'll assert that an error has occurred here. We can inspect the error message, and ensure that no candidates received votes, just like the previous test.

    Now let's update our app. First we list all the candidates from the smart contract inside the form's select element. Then we'll hide the form on the page once the account has voted. We'll update the render function to look like this:.

    First, we query for the candidateId in the form. When we call the vote function from our smart contract, we pass in this id, and we provide the current account with the function's "from" metadata. Every Zombie you create will have randomly generated DNA and have his own unique appearance. Further lessons 1 released each week will add more functionality to your game, like the ability to battle other people's zombies! After completing all lessons and deploying your DApp, pit your zombie army against other players' zombies in one of the world's first blockchain-based games!

    Half code-school, half MMO crypto-collectible strategy game. What are you waiting for? Click the button below to dive into lesson 1 and build your first DApp. It's free! Powered by Loom Network - a platform for building commerical scale apps on Ethereum.

    Yet, blockchain technology is more general than bitcoin, and can be used in a variety of contexts beyond cryptocurrency, from music sharing to food distribution to genomic data transactions. Blockchains can be public, like bitcoin, where anyone in the world can access the network and engage in transactions, or private, where only permissioned individuals can access the network.

    Today, many are interested in using private blockchains to bring security and immutability to different kinds of transactions. For example, we have experimented with using a private MultiChain network to store and share individual genomic data securely. In this tutorial we will focus on the practical steps to getting a private blockchain up and running in Ethereum and MultiChain. If you want a more complete understanding of blockchain before diving into this tutorial, you might start with the bitcoin white paper , ethereum yellow paper , and multichain white paper.

    There are also many existing blockchain tutorials which describe the underlying architecture of blockchain see, for example, this one. The Ethereum website also provides a nice list of tutorials , which we found especially useful and clear. Just briefly, a blockchain is a data structure stored in a network of computers. The network is decentralized and distributed to avoid single point of failure, and each node stores a copy of the chain.

    Nodes in the network can be lost without compromising the integrity of the network or the data due to the redundancy. The blockchain data structure itself logs information about network accounts and transactions. Above is a simple sketch illustrating a blockchain network, but of course this is an oversimplification.

    If you want to think about this more deeply, please consult the tutorials and white papers linked above. If you are interested in learning how to develop smart contracts, you should consult other tutorials. In this one, we will provide a very simple smart contract and explain how to deploy and interact with it.

    We have tried two different methods for doing this, and have found Method 2 to be more successful. But we will describe both methods below. But first, after configuring this private blockchain test network we ultimately want to be able to deploy and interact with a smart contract. Smart contracts can do any number of things, but we will use this simple one for setting and getting a value. Configure your smart contract as follows:. This is the smart contract we will be deploying and interacting with on a private Ethereum test network.

    This will open the Geth JavaScript console, from which you can manage user accounts and deploy smart contracts. The basic test network configuration is ready!

    Now for deploying and interacting with the SetGet smart contract.

    Ether is a cryptocurrency whose blockchain is generated in the Ethereum platform. Ether can be transferred between accounts for compensating participant mining nodes for the computations they have performed. As an altcoin, ether has slowly carved a niche for itself in the blockchain domain.

    Flexibility being at its core, ether is a cryptocurrency that needs no introduction. Wherever there is a need to establish a channel between, participating nodes in a blockchain transaction, ether is your go-to cryptocurrency.

    Also, Ethereum provides a decentralized virtual machine, the Ethereum Virtual Machine EVM , which can be leveraged to execute scripts using an international network of public nodes. Moreover, within Ethereum, there is a second type of token that is used to pay miners fees for including transactions in their block.

    Every smart contract execution on Ethereum requires a certain amount of gas to be sent along with it to entice miners to put it in the blockchain.

    Any service which is centralized initially can be decentralized using Ethereum. From services like loans to their intermediary counterparts, Ethereum can revolutionize thousands of processes that exist across different industries and verticals.

    Now think, if all of them get decentralized, how secure and efficient would every aspect of human existence become. Ethereum can also be used to build decentralized autonomous organizations DAOs. Fully autonomous, and decentralized organizations with no single leader, DAOs are operated by programming codes, on a collection of smart contracts written on the Ethereum blockchain.

    A DAO is owned by everyone who purchases tokens. However, instead of each token equating to equity shares and ownership, they act as contributions that give people voting rights for a consensus.

    Ethereum has recently created a new standard. Termed as the ERC token, this standard is used for tracking unique digital assets. A major use case for these tokens is digital collectibles. The infrastructure of these tokens allows people to prove ownership of scarce digital goods.

    No doubt, Ethereum will continue to prove its mantle in the marketplace as it has been doing since it first came to public sight. Next, find out the Blockchain training offer from Intellipaat.

    Get certified to excel in your career. I truly appreciate this post. If you want to think about this more deeply, please consult the tutorials and white papers linked above. If you are interested in learning how to develop smart contracts, you should consult other tutorials. In this one, we will provide a very simple smart contract and explain how to deploy and interact with it.

    We have tried two different methods for doing this, and have found Method 2 to be more successful. But we will describe both methods below. But first, after configuring this private blockchain test network we ultimately want to be able to deploy and interact with a smart contract. Smart contracts can do any number of things, but we will use this simple one for setting and getting a value.

    Configure your smart contract as follows:. This is the smart contract we will be deploying and interacting with on a private Ethereum test network.

    This will open the Geth JavaScript console, from which you can manage user accounts and deploy smart contracts. The basic test network configuration is ready! Now for deploying and interacting with the SetGet smart contract. Make sure you have the solidity compiler installed by following these instructions in the official solidity documentation.

    Open a third terminal tab and navigate to the directory containing SetGet. Run the following command to generate the application binary interface abi of the SetGet contract: solcjs --abi SetGet. For a detailed explanation of the abi, see the solidity docs. Run the following command to generate the binary file of the contract: solcjs --bin SetGet. This will output the hex-encoded binary to be provided with the transaction request. Return to the second terminal tab, the one with the geth javacsript console.

    Run personal , and you should see there are no existing accounts. Run personal. Make sure your new account is unlocked enter the password you set in step 12 when prompted :. Method 1 is fine, but requires several steps to deploy the contract and when deployment is unsuccessful, the error messages and documentation can be difficult to decipher.

    Deployment with Truffle is a useful alternative. Truffle is an ethereum development tool which is great for testing, and can be used to deploy smart contracts easily. Install Truffle. Follow these instructions on the official truffle documentation. At the same level of the myBlockchain dir, mkdir truffle. This will configure a set of directories:. From the truffle dir, run truffle console. This will open a JavaScript console from which you can manage user accounts and deploy smart contracts.

    The basic test network configuration is now ready! Now you can deploy and interact with the SetGet smart contract via Truffle. In the truffle console, enter migrate. Interact with the contract: instance. These are two ways to deploy a smart contract to a private geth test network using the geth console method 1 or truffle method 2! These methods should be very useful when developing and testing a smart contract.

    Though the smart contract we used was very simple, you can write contracts to perform a number of tasks.

    Leave a Reply

    Your email address will not be published. Required fields are marked *