How to write Smart Contracts for Decentralized Application(DApps)?

             


         Solidity is the contract oriented, high-level language influenced by python, C++, and javascript for implementing smart contracts which are designed for the Ethereum Virtual Machine(EVM). Ethereum is the platform and solidity is the language to build DAPPs. It supports libraries, types, inheritance targeted to run at EVM. Solidity has many plugins and extensions for the editors such as Visual Studio, VSCode, Atom, and more. This will be used to build your own DAPPs which are suitable for the applications that automate the direct interaction between peers or facilitate the group of action across the network.

             A smart contract is a code that handles the transaction between two parties without the need for third parties. You can add many rules as you wish in your smart contract and the code will handle your affairs. For ex, when you deposit a cryptocurrency into a smart contract, it will execute the contract once the conditions are met which puts full control of the transaction and automate it. Ethereum is a programmable blockchain that offers peer-to-peer transactions that are safe and proven across the network. Each node in the chain runs EVM where all your contracts are executed. EVM maintains consensus across the network and isolated from the file system or processes. You can install the solidity compiler using solidity document,  then find the Docker and make sure to install all the items needed based on your environment, binary packages, and compiler in your local environment. Feel free to install the Integrations for your editor like Sublime Text, Atom, Visual Studio etc., If you just want to work on the basics in solidity, the Remix can compile and run your solidity code.

Solidity Basics:  First thing, you need is to import the solidity by doing the keyword pragma which means we load this only once and then the version number. Once the solidity file is imported, you can import any other file by import command, then set up your contract. Solidity contracts are similar to classes in an object-oriented language. The state variables, functions, events, struct types, and enum types are written inside the contract. So, declare the state variable that means the current status of the variable. First, declare the type and name the variable to store data. Ehtereum has an address data type that is really useful at all times. They usually called wallets or wallets addresses.  The datatypes in solidity are,

1. The enum data type helps to define user types like buyer and seller.

2.  Mappings are dictionaries in other languages that have key values in public or private.

3. The special variables in solidity are messages and transactions. Basically, the messages are what is sent. So, you can access the sender, value, and the particular message or data. It can be described as msg.sender, msg.value, and msg.data. 

4. When the transaction is done, you can access the particular information by the variable called tx.origin.       

          The modifiers are the condition of the function or condition before we run the function. It has been declared as the modifier keyword and the name of the modifier. Then, set the conditional for the modifier by require statement that contains information about what does it require and use the syntax underscore, semicolon to close the modifier. The modifier usually needs a function that is similar to other languages such as function and function name with the type of parameters (public and private). The body of the function contains what is going to happen in the function. Basically, the modifier will check before it runs the function that condition is met, then it will execute the function. The last thing is the event. It is basically javascript events. Basically, the events expecting the address. When the events are initiated, it expects the things and will do something afterward.

Functions and Conditionals in Solidity: The functions take input as parameters (uses underscore parameter) like most programming languages, but it differs to return multiple outputs. The keywords to use when you do your function is public or private. If you do a private function that will be accessible within the contract and a function will not be accessible outside of the contract. If you want a function that should be accessible outside of the function, make it to be public. You can use the word pure means interacting with constants that don't change and put the return statement with return type in the second line. Solidity has conditional statements of if, for loop, but the switch, goto is not available. The conditionals are very similar to other programming languages.

Writing a Smart Contract:   Once you know the basics of solidity, you can start writing the smart contract.  Initially, we split up the project into 2 directories like Truffle and web. It is good to follow these steps when you write the code inside the contract,

Step 1: Setting up the initial variables:

                     Let's take an example of sending ether with the approval process by a third party. So, create the contract ApprovalContract, then create the variables, modifiers, and functions. Here, the variable type address will represent the sender, receiver, and for the approver, set it equal to value.

Step 2: Add the modifiers:

             We are not adding any separate modifiers for the approval process. So, we directly write the function to handle the deposit.             

Step 3: Finalize the Functions:

             The deposit function takes the address where the money will be sent to and make it external

that allows being called outside of the contract. The modifier payable allows taking the ether. When these functions are called, the special variable messages contain the data include the sender(msg.sender) who is sending the money and the value(msg.value) that is being sent. Write the require that the message value greater than zero to deposit the ether. Then, set the message sender equal to msg.sender. This is going to be saved in the smart contract and will be written to the blockchain. Also, set the receiver as well. 

         The ViewApprover function going to be external and pure. It's a lightweight call that does not cost the gas which will return the approver address. 

        Finally, the approve function will release the money and send it to the receiver which is an external and payable function. The approval is possible when the address of the sender that matches the approver and the transfer function will be used to send the money or you can use the send method which will return false or true if it passes. The transfer function called where the money is being sent to and gets the address of the contract with the balance so that to return the balance stored in the contract and send it to the recipient. The solidity is like javascript, but it is a deeper language that needs lot of best practices.


Step 4:Compile and Migration: 

        Once the solidity code is compiled successfully by the command "truffle compile" in your truffle directory, you can migrate that build which is stored in the build directory by migration script. So, you need to set up the Truffle configuration file(truffle.js) by just uncommenting the development network. You need to create 2_deploy_contract.js in migrations and create a variable of ApprovalContract to deploy the contract. You can just enter the command "Truffle develop" in cmd which will give the truffle prompt. When the truffle prompt is active, just enter the command " truffle migrate development" in another command line. Now the contracts are deployed to the network.


Step 5:  Test your contract with Truffle: 

          The smart contract needs to be fully tested before deploying to the mainnet because of the immutable nature of the blockchain and cryptocurrencies are working on financial transactions. The Truffle allows writing some test javascript to ensure things are working correctly.   

     The test javascript in the Truffle server test directory

(ApprovalContract.js) will be compiled by the command "truffle test" in the truffle development environment. If it is successful, you can see the ApprovalContract, initiates the contract, and 1 passing message in the command line.

      

Basics of Web3.js:  Web3.js is a javascript library to interact from client-side applications to

Ethereum network. You can install it using the node or CDN (web3.min.js) and save it to your project web directory. This will help you to send Ether, get transaction details, get balances, interact with a smart contract, add a signature to transfer etc.,  The web3.eth will used to interact with ethereum blockchain and ethereum smart contract. You can check other packages for the Dapp development. Now, we can plug web3 into Dapp. First, add web3.js script in Dapp and create another script block. Create the instance of web3 and pass HTTP web3.providers, 9545 is the address of the truffle server. If you enable the interaction with metamask, metamask will inject its own web3. So, the code will be written for the current provider to use web3.

Building a Dapp:  We will use the Visual Studio Code to build and run the Dapp. Once you have

connected to the smart contract, write the script to verify the people entered the correct ethereum address. So, you need to override the submit function of the form's(contract-form) default action and test the functionality that you want. The web3.utils package's isAddress function will help to validate the Ethreum address. Then, you can check out the balance by the package web3.eth.getBalance(contract address). You can get the contract address when the truffle development server is running with the command "truffle migrate --reset".

Working with Smart Contract: The power of Dapp is the smart contract which is our back-end interact with UI. So, the first thing we need is to get the ABI(Application Binary Interface). It is a JSON encoding of smart contract that can be used as a client stub in a web service. You can get ABI in many ways. Those are,

1. Get the ABI property from Etherscan: If you go to contract in Etherscan, you can see the ABI and copy it directly

2. Using Remix to get ABI: Remix output an ABI that you can grab and paste it in your project

3. Get ABI from Truffle Build Directory: In Truffle's build directory, you can see the contract and the <contract name>.json and you can see the ABI.

        So, copy the abi and put this script directly into contractABI.js file with a var abi in your project directory and write the included script in the index.html file. Now, you can interact with a smart contract.

      First, you need to create an instance of the contract that will use ABI. So, create the

ApprovalContract variable and call new Web3.eth.contract and pass the ABI and address. Once, you set up, run the dapp and make sure it is using the abi in the debug console. Once you validated, you can use the ApprovalContract methods and call on deposit and pass toaddress. The send function will be used to send ether. After the object is created, write a function to check for error and return the transaction Id if it is successful. 




Comments