Are You an Ambitious Entrepreneur Aspiring to Launch a World-Class Web3 Project? GRAB your WEB3 EXPERT CONSULTATION!
Book a Session!

Ethereum Programming Basics

36

Ethereum is a multi-purpose platform designed to solve a number of tasks. In the following article, we will outline the basics of Ethereum programming, its functionality, and its features. Below, you will find an Ethereum programming tutorial explaining the easy steps of smart-contract and DApp deployment.

The Ethereum platform is a creation of Vitalik Buterin. Its intention is to provide an alternative platform to the existing Bitcoin blockchain in order to:

  • build DApps (decentralized applications)
  • provide a new set of tradeoffs matching a variety of dApps
  • increase the speed of deployment
  • ensure higher security, even for small and rarely-used applications
  • advance efficient interactions

To provide these solutions, Ethereum has built an ultimate basic layer. This is a new blockchain with a native Turing-complete coding language. It enables developers and programmers to write smart contracts for numerous decentralized applications. One can easily set unique arbitral ownership rules and conditions as well as a variety of transaction modes and state functions.

Ethereum provides greater capacity than offered by Bitcoin. Hence, with Ethereum implementation, one can build and execute currency and reputation system protocols in various ways. In addition, developers can create smart contracts on top of the Ethereum platform. Due to the platform’s capacity, SCs can contain a particular value, and can be executed only under precise conditions. Additional power is provided by:

  • Turing-complete coding
  • value perception
  • blockchain recognition
  • state

Ethereum is currently solving a range of problems, while Bitcoin originally emerged as a digital cryptocurrency only.

Ethereum vs. Bitcoin comparison

Ethereum Functionality

Ethereum functions according to the following principles:

1. Simplicity. One of Ethereum’s distinctive features is protocol simplicity. It is very simple and convenient to use by any programmer. Ideally, any developer can implement the protocol and realize its full potential according to specification. In order to avoid complexity, one should not add certain optimizations unless absolutely necessary.

2. Universality. Another Ethereum trait is that it doesn’t have specific “features.” Instead, the platform functions on a native Turing-complete coding language. Any developer can use this language to write smart contracts and mathematically define all types of transactions. With Ethereum, one can create his/her own cryptocurrency, use it in smart contracts, set up scalable platforms and applications, etc.

3. Modularity. Ethereum protocol can be divided into multiple parts and modules. During the development process, the user is able to design a program and submit further modifications. It is significant that even with changes and edits, the application stack will continue functioning. This is beneficial for various upgrades, innovations, etc.

4. Agility. Ethereum protocol is fast and flexible, as its requirements aren’t set in stone. Keep in mind, though, that Ethereum is strict about relatively high-level construct modifications. If any modifications occur during testing that can further increase the protocol’s scalability or security issues, Ethereum elaborates on them.

5. Non-discrimination and non-censorship. Ethereum protocol doesn’t commonly place any restrictions or usage limitations. The regulatory mechanisms are meant to support various applications as long as they are not harmful.

In the basics section, we outline the general workflow during Ethereum programming. Let’s consider the main features and components:

Cryptography

Public-key cryptography is one of Ethereum’s distinctive features. The user usually has a public and a private key to create digital signatures. User A creates a signature with the private key. User B can verify this signature by using user’s A public key. While creating personal wallets, one has to make sure to store these keys somewhere. In case of loss, there is the threat of losing the funds forever.

Peer-to-Peer Network

Ethereum functions in a decentralized manner. It presents all nodes (computers) as peers in a distributed network ledger. The main advantage is that there is no dependence on a centralized server.

Ethereum Blockchain

The Ethereum ledger provides database storage of all active accounts enabled by a Patricia tree database. The latter is a specialized derivative of a Merkle tree storing various keys and values. It has a “root hash,” according to which it is impossible to change the tree content unless the root hash is modified. Each account includes stored data of its nonce, balance, code hash, and storage root.

Ethereum VM

The Ethereum blockchain functions with a native coding language. It also uses a consensus-based VM (virtual machine), executed worldwide. EVM is a protocol handling internal states and computational processes. EVM is similar to a large computational machine. It maintains a high number of accounts that interact with each other in a decentralized manner.

Two account types are available:

Ethereum VM Account Types

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.
ContractThis is an account that has its own code, and it is controlled by a code.

Ethereum’s execution environment is dispirited, meaning that nothing can happen and the account state will remain as it is. However, it is possible to trigger actions by sending external transactions to motion the process. For instance, if you need to execute a transaction to another EOA, you can transfer some Ethers to do so. However, if the transaction needs to appear in a contract, this contract will activate and run the code by itself. Codes can read and write according to their internal storage. They can read incoming messages and send them between contracts to trigger a reverse-execution process. Once the activity stops, the process of execution ceases, as well, until awakened by further transactions.

The purpose of the contracts is to:

  • manage data storage for contracts and external sources
  • function as an external account. This means providing complex access by forwarding incoming messages between destinations
  • maintain current contracts and user relationships, such as escrow or various insurance types
  • function as a library by providing software functions to contracts

Interaction between contracts happens due to calling activity and message-sending. These messages include details on Ether quantity, data byte-array, and participant addresses. As the contract receives these details, it can return specific information and functions exactly like a function call.

Nodes

Nodes are used in order to read and write on the blockchain, which one has to download entirely in advance. For this, nodes commonly use the VM. Nodes receive information, conduct certain operations with it, and then provide an output.

Miners

Ethereum miners are network nodes that mine (create and process) new blocks on the chain. Miners verify transactions within blocks to add them to the public blockchain ledger. They have to reach the consensus relative to the history of transactions. Consensus prevents fraud and deceitful behavior like double spending, for instance.

In detail, it is necessary to run specific header metadata of a block with a hash function. This function provides a fixed string of random-looking numbers and letters. If the nonce value shows changes, there can be an impact on the output value of the hash.

If miners spot a hash matching the intended target, they receive an Ether reward. Then, they can broadcast the block for validation. If another miner detects a matching hash, the first one stops working on the block and continues with the next one.

Proof of Work

Proof of Work is an algorithm that enables miners to solve a block’s problems. They receive the above-mentioned ETH rewards for a solution. Due to this algorithm, all miners receive incentives to validate block data and ensure trust in the blockchain.

Proof of work in Ethereum blockchain

Gas

In order to process transactions on the Ethereum blockchain, participants have to pay fees. They are determined in Ethers. Fees are charged for computational actions called by participants in order to execute transactions. These fees are called “gas.” Therefore, any transaction on the blockchain not only includes the necessary data, it also states the gas price and startGas value. Here’s how it works:

Ethereum VM Account Types

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.
ContractThis is an account that has its own code, and it is controlled by a code.

Ethereum Programming Language

It is possible to use a number of coding languages to develop smart contracts on the Ethereum platform:

Ethereum Programming Languages

SoliditySimilar to JavaScript, using .sol as a file extension.
SerpentSerpent is an assembly language that compiles to EVM code, which is extended with various high-level features. It can be useful for writing code that requires low-level opcode manipulation as well as access to high-level primitives, like ABI. Serpent was pretty popular a while ago, but is no longer recommended by Ethereum.
PythonPyethapp is a Python-based client implementing the Ethereum crypto economic state machine. It can be used with extension .se, but it doesn’t receive updates as of today, and it is not recommended for use.
LLL (Lisp-like Language)Lisp-like Language (LLL) is a low-level language similar to Assembly. It is meant to be very simple and minimalistic: essentially, just a tiny wrapper over coding in EVM directly. You can use LLL if you prefer close-to-the-metal optimizations.
ViperViper is a smart-contract development language built with the goals of providing increased security, language and compiler simplicity, and auditability.
Viper is still experimental, though Ethereum recommends it if you like Viper’s features.

In practice, Solidity is the most widespread programming language for Ethereum smart contracts. It is Ethereum’s native and was specially designed for this platform. Although there are several other official recommendations, like LLL or Viper, they are limited to particular preferences. In other words, why look for challenges? Just choose Solidity, as it is for Ethereum programming.

When writing in Solidity, make sure to double-check your codes. Run tests, use official security checks and audit to avoid possible smart-contract mistakes.

When you write a Solidity contract, derive the compiler you prefer from the public library. You can use solc., Cosmo, or other compilers. Track the updates to choose the best one. After compiling the contract, you can send it to the network and call it with web3.js API. When that is done, it is possible to create web applications in order to interact with your contracts.

Ethereum Programming Course: Smart-Contract Deployment

Before creating a new smart contract, it is better to set up the Truffle framework. This will enable you to test and compile the written SC. Smart contracts require compiling and deployment, which can be complex due to long transaction generation. Truffle simplifies these processes with the use of simple commands.

Let’s consider the basic steps of smart-contract writing:

Smart-Contract Creation

To begin with, let’s create a new contract, which will later 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 functions as storage that enables users to create various objects and track them by address. Mapping stores data efficiently and provides details on it quickly. Considering that it isn’t easy to replicate, the code provides an array usersByAddress holding all user addresses in the system.

The notarizedImages enable image object creation. One can later track them in storage.

It is also necessary to add a new user to the system. User structure contains basic data:

  • handle
  • city
  • state
  • country

This structure also keeps data concerning the user’s notarized images.

Next, add the following functions to the code:

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
    }
}

Next, add the addImageToUser function:

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 function is similar to the previous one. It finds your account by sending the address and verifying the registration. After this has been completed, you can add new images to the user’s entry.

The final step is to create the getUsers function. It enables the viewing of all users and images as well as procurement of white-page listings. The data, according to this function, returns instantly, but only in the “read” regime.

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

Basically, we have now written the smart contract. Before its deployment to the network, it has to be tested and compiled. As mentioned above, the Truffle framework is one of the best matches. It uses simple commands to test your smart contract.

First, create a local Ethereum node to run your test-outs. Ethereum TestRPC works as a fake node, according to a program pretending to be a node and responding as such. It tests the solidity contract, runs its codes, and provides the responses. What’s beneficial about this testing mode is that it works really fast. You don’t need to spend as much time as on the real network.

Next, run testing in the Truffle framework:

Truffle smart contract testing

While testing, specify the contract name and call the “truffle compile” command. If any errors occur, work around them and eliminate. Then, call the “truffle migrate” command. This deploys your contract in test mode. The output can look like this:

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...

Now, you can start the first real testing to set the SC interaction. Run the truffle console to ensure that everything functions. Later, you’ll be able to add new users and images:

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('0x6c3e007e281f6948b37c511a11e43c8026d2a16a8a45fed4e83379b66b0ab927');})

After you’ve finished testing, your smart contract is ready! Check out another simple way to create smart contracts easily!

Ready? Next step is to create an appealing UI (user interface). You’ll need it to enable user interaction with the smart contract on the Ethereum blockchain.

Ethereum Programming Course: DApp Development

Decentralized application creation allows other users to interact with your SC via their browser. DApps can be created with a particular Web3.js javascript module.

First, install the web3 module:

import Web3 from ‘web3’;

or, in ES6 javascript

var Web3 = require(‘web3’);

Provide web3 with specific details concerning your node and smart contract. You should get the following output:

// 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){})

Further, you’ll need to connect your DApp to the Ethereum main network. In order to enable mainnet interaction, most users today choose the Metamask plugin. This plugin ensures connection to a full node without charging any fees. We should stress, however, that this option works only with the Chrome browser.

Consider the following list of tools best-matched to DApp deployment:

MIST/ Ethereum WalletUsed for digital asset storage, transactions, and payment performance
Geth Helps set up your own node
Truffle Provides development tools for compiling, testing, and deploying a DApp
Web3.jsAn interface used for blockchain interaction
Solc Translates a smart-contract code into a bytecode
BlockApps Provides API endpoints
ZeppelinA library for smart-contract functionality

The following web3 code changes automatically to the customary client via Metamask:

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'));
    }
}

In order to start DApp functioning, you’ll be required to pay a certain amount of gas. You’ll get notified. Further, you can choose various users in your user interface and browse data about them.

Conclusion

Ethereum is a multi-functional, decentralized platform that solves an array of tasks and problems. Its functionality is proven by its speed, scalability, cryptography, and other notable features. Its main purpose is to serve as a platform for smart-contract development, with Solidity being the native coding language. We have provided this basic Ethereum programming course to quickly deploy your smart contract and create a DApp for it.

Do you have any questions? Would you like to specify certain details? Find out more about Applicature’s expert team and Contact us today! 

Insights from our Consulting Department

December 3, 2024
Dec 03, 24, Weekly: Crypto’s Establishment Takeover: Risks and Opportunities in the Evolving Blockchain Landscape
November 26, 2024
Nov 26, 24, Weekly: Crypto Market Surges as Musk Hints at Major Development

Leave a Reply

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

+1-209-813-2474 |  25 Belle Avenue, San Rafael