Basics of Ethereum Programming

Ethereum is a multi-purpose platform that may be used to do a variety of things. We'll go through the fundamentals of Ethereum programming, as well as its functionality and capabilities, in the next post. An Ethereum programming tutorial describing the simple processes of smart-contract and DApp deployment may be found below


Vitalik Buterin is the creator of the Ethereum platform. Its goal is to build a platform that is different from the Bitcoin blockchain in order to:

create DApps (decentralised applications) offer a new set of tradeoffs that are compatible with a wide range of dApps

boost deployment speed, especially for small and infrequently used applications, assure stronger security, and advance efficient interactions


Ethereum has created an ultimate fundamental layer to supply these solutions. This is a brand-new blockchain with a Turing-complete native coding language. It allows programmers and developers to create smart contracts for a variety of decentralised applications. Unique arbitral ownership rules and conditions, as well as a number of transaction modes and state functions, can be easily set.


Ethereum has a larger storage capacity than Bitcoin. As a result, with Ethereum, one can create and execute currency and reputation system protocols in a variety of ways. On top of the Ethereum platform, developers may also design smart contracts. SCs can have a certain value and can only be executed under specific conditions according to the platform's capacity. The following sources of additional power:

  • Value perception

  • Turing-complete coding

  • State

blockchain recognition

Ethereum is now tackling a variety of problems, whereas Bitcoin was created solely as a digital currency.


Ethereum's Usability

Ethereum works on the basis of the following principles:


1. Ease of use Protocol simplicity is one of Ethereum's distinguishing characteristics. Any coder can use it because it is very simple and convenient. Any developer, in theory, should be able to build the protocol and fulfil its full potential in accordance with the specifications. If you want to keep things simple, don't add optimizations until they're really necessary.


2. The concept of universality. Another property of Ethereum is that it lacks distinct "features." Instead, the platform uses a Turing-complete coding language specific to the platform. This language allows any developer to construct smart contracts and mathematically specify any type of transaction. Ethereum allows users to create their own currencies, utilise it in smart contracts, and build scalable platforms and applications, among other things.


3. The ability to be modular. The Ethereum protocol is made up of several pieces and modules. The user can design a software and propose additional changes during the development process. It's important to note that the application stack will continue to work even if changes and edits are made. This is advantageous for a variety of updates, inventions, and other purposes.


4. Adaptability. Because its needs aren't fixed in stone, the Ethereum protocol is quick and adaptable. Keep in mind, though, that Ethereum is very stringent about making changes to rather high-level constructs. Ethereum elaborates on any changes made during testing that could significantly exacerbate the protocol's scalability or security vulnerabilities.


5. Non-discrimination and non-censorship. The Ethereum protocol does not typically impose any constraints or limitations on its use. The regulatory systems are designed to support a wide range of applications as long as they do not cause harm.


The usual procedure during Ethereum programming is outlined in the basics section. Consider the following key features and components:


Cryptography

One of Ethereum's distinguishing features is public-key cryptography. To create digital signatures, the user normally possesses a public and private key. With the private key, User A makes a signature. Using user A's public key, user B can validate this signature. When making personal wallets, it's important to remember to keep these keys somewhere safe. In the event of a loss, the funds could be lost forever.


Peer-to-Peer Network (P2P) is a type of peer-to-peer

Ethereum is a decentralised cryptocurrency. In a distributed network ledger, it portrays all nodes (computers) as peers. The key benefit is the lack of reliance on a centralised server.


Ethereum Blockchain is a distributed ledger.

The Ethereum ledger uses a Patricia tree database to store all active accounts in a database. The latter is a customised Merkle tree that stores a variety of keys and values. It has a "root hash," which states that changing the tree content is impossible until the root hash is changed. Each account has nonce, balance, code hash, and storage root data saved in it.


Ethereum Virtual Machine

A native code language is used to run the Ethereum blockchain. It also employs a consensus-based VM (virtual machine) that is deployed globally. EVM is a protocol for dealing with internal states and computations. The EVM resembles a big computing machine. It maintains a large number of decentralised accounts that interact with one another.


There are two types of accounts available:


Types of Ethereum Virtual Machine Accounts


Externally-owned account (EOAs)

This is an account controlled by a private key, and if you own the private key associated with the EOA, you have the ability to send Ether and messages from it.


Contract

This is an account that has its own code, and it is controlled by a code.


Because Ethereum's execution environment is stifled, nothing can happen and the account state will remain unchanged. However, actions can be triggered by sending external transactions to set the process in motion. For example, if you need to send Ethers to another EOA, you can do so by transferring some Ethers. If the transaction is required to appear in a contract, the contract will automatically activate and run the code. Codes have the ability to read and write data based on their internal storage. They have the ability to read incoming messages and send them between contracts to initiate a reverse-execution process. When an activity comes to a halt, the execution process comes to a halt as well, until it is reawakened by new transactions.


The contracts' main goal is to:


Manage contract and external source data storage and act as an external account. This entails allowing complicated access by routing incoming messages to different destinations.

maintain current contracts and user interactions, such as escrow or different types of insurance, operate as a library by giving software services to contracts

Calling and message-sending actions cause interaction between contracts. The Ether quantity, data byte-array, and participant addresses are all included in these messages. As soon as the contract receives these specifications, it can respond with specified data and functions, much like a function call.


Nodes

Nodes are used to read and write on the blockchain, which must be downloaded completely ahead of time. Nodes typically use the VM for this. Nodes accept data, perform specified operations on it, and then output the results.


Ethereum miners are nodes on the Ethereum network that mine (produce and process) new blocks for the chain. To add transactions to the public blockchain record, miners verify transactions within blocks. They must come to an agreement based on the transaction history. Consensus helps to prevent fraud and deception, such as double spending.


In detail, a hash function must be used to run specific header metadata of a block. This function returns a fixed string of numbers and letters that appear to be random. If the nonce value changes, it may have an effect on the hash's output value.


Miners

Miners receive Ether if they find a hash that matches the intended target. The block can then be broadcast for validation. If a matching hash is found by another miner, the first one quits working on the block and moves on to the next.


Proof of Work

Proof of Work is a mining technique that allows miners to solve the challenges in a block. For a solution, they receive the ETH prizes indicated above. Because of this mechanism, all miners are rewarded for validating block contents and ensuring blockchain trust.




Gas

Participants must pay fees in order to perform transactions on the Ethereum blockchain. Ethers are used to determine them. Participants pay fees for computational tasks that must be performed in order to complete transactions. These charges are referred to as "gas." As a result, all transaction on the blockchain not only contains the required information, but also the gas price and startGas value. The following is how it works:


Ethereum VM Account Types

Ethereum Programming Language

Ethereum Programming Languages


Smart-Contract Deployment in Ethereum Programming

It is preferable to set up the Truffle framework before generating a new smart contract. This will allow you to test and build the SC that has been written. Smart contracts necessitate compilation and deployment, which can be time-consuming due to the large number of transactions generated. Truffle makes these tasks easier by using simple instructions.


Consider the following phases in the creation of a smart contract:


Constructing Smart Contracts

Let's start by creating a new contract, which will be referred to as "contract1."


pragma solidity ^0.4.4;
contract contract1 {
    address contract1Admin;
    mapping ( bytes32 => notarizedImage) notarizedImages; // this allows to look up notarized Images by their SHA256notaryHash
    bytes32[] imagesByNotaryHash; // this is like whitepages of all images, by SHA256notaryHash
    mapping ( address => User ) Users; // this allows to look up Users by their ethereum address
    address[] usersByAddress; // this is like whitepages of all users, by ethereum address
    struct notarizedImage {
        string imageURL;
        uint timeStamp;
    }
    struct User {
        string handle;
        bytes32 city;
        bytes32 state;
        bytes32 country;
        bytes32[] myImages;
    }
}

Mapping is a type of storage that allows users to create and track various things based on their addresses. Mapping efficiently saves data and instantly delivers details on it. Because it's difficult to recreate, the code includes an array usersByAddress that contains all of the system's user addresses.


The generation of image objects is enabled by the notarizedImages. They can be tracked in storage later.


In addition, a new user must be added to the system. Basic information about the user can be found in the user structure:

  • handle

  • city

  • state

  • country

This structure also contains information on the user's notarized images.


Then, in the code, add the following functions:

function registerNewUser(string handle, bytes32 city, bytes32 state, bytes32 country) returns (bool success) {
    address thisNewAddress = msg.sender;
    // don't overwrite existing entries, and make sure handle isn't null
    if(bytes(Users[msg.sender].handle).length == 0 && bytes(handle).length != 0){
        Users[thisNewAddress].handle = handle;
        Users[thisNewAddress].city = city;
        Users[thisNewAddress].state = state;
        Users[thisNewAddress].country = country;
        usersByAddress.push(thisNewAddress); // adds an entry for this user to the user 'whitepages'
        return true;
    } else {
        return false; // either handle was null, or a user with this handle already existed
    }
}

Add the following code after that: addImageToUser


function addImageToUser(string imageURL, bytes32 SHA256notaryHash) returns (bool success) {
    address thisNewAddress = msg.sender;
    if (bytes(Users[thisNewAddress].handle).length != 0) { // make sure this user has created an account first
        if (bytes(imageURL).length != 0) {
            // prevent users from fighting over sha->image listings in the whitepages, but still allow them to add a personal ref to any sha
            if(bytes(notarizedImages[SHA256notaryHash].imageURL).length == 0) {
                imagesByNotaryHash.push(SHA256notaryHash); // adds entry for this image to our image whitepages
            }
            notarizedImages[SHA256notaryHash].imageURL = imageURL;
            notarizedImages[SHA256notaryHash].timeStamp = block.timestamp; // note that updating an image also updates the timestamp
            Users[thisNewAddress].myImages.push(SHA256notaryHash); // add the image hash to this users .myImages array
            return true;
        } else {
            return false; // either imageURL or SHA256notaryHash was null, couldn't store image
        }
        return true;
    } else {
        return false; // user didn't have an account yet, couldn't store image
    }
}

This method is very similar to the one before it. By transmitting the address and verifying the registration, it locates your account. You can now add additional images to the user's entry when this has been completed.


The getUsers function must be written last. It allows you to see all users and photographs, as well as purchase white-page listings. The data is returned instantly by this function, but only in the "read" mode.


function getUsers() constant returns (address[]) {
    return usersByAddress;
}
function getUser(address userAddress) constant returns (string,bytes32,bytes32,bytes32,bytes32[]) {
    return (
        Users[userAddress].handle,
        Users[userAddress].city,
        Users[userAddress].state,
        Users[userAddress].country,
        Users[userAddress].myImages
    );
}
function getAllImages() constant returns (bytes32[]) { return imagesByNotaryHash; }
function getUserImages(address userAddress) constant returns (bytes32[]) { return Users[userAddress].myImages; }
function getImage(bytes32 SHA256notaryHash) constant returns (string,uint) {
    return (
        notarizedImages[SHA256notaryHash].imageURL,
        notarizedImages[SHA256notaryHash].timeStamp
    );
}

Smart-Contract Testing

Smart-Contract Testing is a method of determining whether or not a contract

Essentially, we've completed the smart contract. It must be tested and compiled before being deployed to the network. The Truffle framework, as previously said, is one of the finest matches. It tests your smart contract with easy commands.


To begin, set up a local Ethereum node on which to conduct your tests. Ethereum TestRPC functions as a spoof node, i.e., a software that pretends to be a node and responds as one. It puts the solidity contract to the test, runs the scripts, and returns the results. This testing mode has the advantage of being extremely quick. You don't have to devote as much time to the virtual network as you would to the real one.


Then, using the Truffle framework, run the following tests:





Specify the contract name and run the "truffle compile" command while testing. If any errors occur, work around them and eliminate them as soon as possible. Then run the command "truffle migrate." This activates the test mode for your contract. This is an example of the output:


Running migration: 1_initial_migration.js
Deploying Migrations...
Migrations: 0xd06a1935230c5bae8c7ecf75fbf4f17a04564ed8
Saving successful migration to network...
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying Contract1...
Contract1: 0xe70ff0fa937a25d5dd4172318fa1593baba5a027
Saving successful migration to network...
Saving artifacts...

You can now begin the first actual testing to establish the SC interface. To make that everything is working, run the truffle console. You'll be able to add new users and images later on:


truffle console
> Contract1= Contract1.deployed()
> Contract1.then(function(instance){return JSON.stringify(instance.abi);})
> Contract1.then(function(instance){return instance.registerNewUser("Tectract","Denver","CO","USA");})
> Contract1.then(function(instance){return instance.addImageToUser('www.myimageURL.com','0x6c3e007e281f6948b37c511a11e43c8026d2a16a8a45fed4e83379b66b0ab927');})
> Contract1.then(function(instance){return instance.getUser('0x0ac21f1a6fe22241ccd3af85477e5358ac5847c2');}) 
> Contract1.then(function(instance){return instance.getUsers();})
> Contract1.then(function(instance){return instance.getImages();})
> Contract1.then(function(instance){return instance.getImage('0x6c3e007e281f6948b37c511

Your smart contract will be ready once you've finished testing it. Check out yet another easy way to make smart contracts!


Ready? The next step is to design an appealing user interface. It'll be required to allow users to interact with the Ethereum blockchain's smart contract.


DApp Development is a topic covered in the Ethereum Programming Course.

Other users can interact with your SC via their browser thanks to decentralised application creation. A specific Web3.js javascript module can be used to create DApps.


Install the web3 module first:

import Web3 from ‘web3’;

or, in ES6 javascript

var Web3 = require(‘web3’);

Give web3 precise information about your node and smart contract. You should receive something like this:

// this line specificies our localhost node IP:port settings
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// our smart-contract address, from above
var Contract1Address = '0xe70ff0fa937a25d5dd4172318fa1593baba5a027';
// our smart-contract ABI, as raw javascript object, not quoted string!
var Contract1ABI = [{"constant": true,"inputs":[],"name":"getUsers","outputs":[{"name": "..."}]}
// this loads the smart-contract into our web3 object
Contract1Contract = web3.eth.contract(Contract1ABI).at(Contract1Address);
// this finds the default account listed for the node connection (account 0 from TestRPC above)
defaultAccount = web3.eth.accounts[0];
// Here are some lines that demonstrate read-only functions interfacing with our smart contract via web3:
// the below function is activated when the page loads, to get the "white-pages" of all known user addresses
Contract1Contract.getUsers(function(err,usersResult){})
// the below function grabs an image as needed, and stores them in browser memory...
Contract1Contract.getImage(imageHash,function(err,imageResult){})

You'll also need to link your DApp to Ethereum's main network. Most users nowadays utilise the Metamask plugin to enable mainnet interaction. This plugin assures that you can connect to a full node without having to pay anything. However, it is important to note that this feature is only available on Chrome.


Consider the following tools, which are most suited for DApp deployment:



The following web3 code, when run using Metamask, switches to the default client:

function loadWeb3() {
    let web3Injected = window.web3;
    if (typeof web3Injected !== 'undefined') {
        console.log('saw injected web3!');
        web3 = new Web3(web3Injected.currentProvider);
    } else {
        console.log('did not see web3 injected!');
        web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
    }
}

You'll need to purchase a set quantity of petrol to get your DApp up and running. You'll be alerted. In addition, in your user interface, you can select different users and explore info about them.


Conclusion

Ethereum is a multi-purpose, decentralised platform that may be used to handle a variety of jobs and issues. Its speed, scalability, cryptography, and other significant qualities demonstrate its functionality. Its primary function is to serve as a platform for smart-contract creation, with Solidity as the primary programming language. This simple Ethereum programming course will let you launch your smart contract and construct a DApp for it rapidly.


Do you have any other inquiries? Would you like to provide any further information? Learn more about Cryptoauxiliary's experienced staff and get in touch with us today!


1 view0 comments