Build a step-by-step, decentralized application (Ethereum Blockchain Dapp) in more than 128 words – Part 3

This article follows the first two articles on the subject:

The first 2 articles provide a better understanding of the concept of blockchain and decentralized application.

Creating the project

A directory is created for the voting application project on songs.

mkdir vote-song-dapp

To accelerate development we will use a "truffle box": https://www.trufflesuite.com/boxes

It's sort of a template, an application canvas that allows you to focus on the Dapp by having a structure already created.

I will base my explanation on the pet-shop box available here: https://www.trufflesuite.com/tutorials/pet-shop. This is one of the first truffle tutorials to create a Dapp.

This truffle box includes the basic structure of the project as well as the user interface code.

Use the truffle unbox command:

truffle unbox pet-shop

As a reminder the installation of truffle is possible via the order:

npm install -g truffle

If you open the vote-chason-dapp folder with vscode then you get the following tree:

Dapp app project tree example (based on truffle pet-shop)
  • contract: storage of the application's smart contract
  • migration: Migrations allow smart contracts to be transferred to the Ethereum blockchain (local test or mainnet). Migrations also allow you to link smart contracts with other smart contracts and start them.
  • node_modules: The node_modules folder contains libraries downloaded from npm.
  • src: Front-end application directory (customer)
  • test: Storage of tests for the application
  • truffle-config.js: Javascript file that can execute any code needed to create your configuration.

Creating the smart contract

As a reminder we are developing an application that allows to elect the favorite song of voters.

We will first create the part that allows to create a vote for the best song based on 3 eligible songs.

The contract written in solidity is as follows:

TopChanson contract
        struct Song
        uint ID;
        title string;
        uint counter;
    }
    uint public counterDeChansons;
    mapping (uint - Song) public songs;

    function addChansonElligible (string memory nomChanson) private
        CounterDeChansons;
        songs -[compteurDeChansons] Song (CounterDeChansons, NameChanson, 0);
    }

    TopChansons(public) function
        addChansonElligible ("Moonlight");
        addChansonElligible ("Mom the little boats");
        addChansonElligible ("Ah! Crocodiles");
    }

}

Note the use of "mapping (uint – Song) public songs;"

Related: https://solidity.readthedocs.io/en/v0.6.6/types.html#mapping-types

This data structure will allow us to store the titles of eligible songs like a hash table. That is, a table that takes as an access key in our case a uint that is the song ID and allows to recover the value that is a structured song type.

The Song type is structured, see solidity documentation: https://solidity.readthedocs.io/en/v0.6.6/types.html#structs

Here there is a special case on the feature addChansonElligible, it takes into argument the name of the song which is a string character chain. If you don't add the keyword "memory" you get the following error:

TypeError: Data location must be "storage" or "memory" for parameter in function, but none was given.

For function settings and return variables, the location of the data must be explained for all type variables (struct, mapping, thong).

The contract is migrated via the order:

truffle migrate --reset

We then get:

Compiling your contracts...
===========================
Compiling ./contracts/Migrations.sol
Compiling ./contracts/TopChanson.sol

To follow …

Build a step-by-step, decentralized application (Ethereum Blockchain Dapp) in more than 128 words – Part 2

This article follows the first article on the subject: http://128mots.com/index.php/2020/03/30/construire-une-application-decentralisee-full-stack-pas-a-pas-ethereum-blockchain-dapp-en-plus-de-128-mots-partie-1/

Example of decentralized voting application (Dapp)

The user of the decentralized application needs a wallet that contains Ether. As stated in the first article it is possible to easily create a wallet on https://metamask.io/.

First we will use the ropsten network. Ropsten Ethereum, also known as the "Ethereum Testnet", is, as the name suggests, a test network that performs the same protocol as Ethereum and is used for testing purposes before deploying on the main network (Mainnet). https://ropsten.etherscan.io/

The use will allow us to create and use our app for free before eventually broadcasting it on Ethereum's main network.

When the user connects to our application and the network he sends his vote and has to pay a few fees via his wallet in order to write his transaction in the Blockchain (called "Gas", this term refers to the fees to complete a transaction or execute a contract on the Ethereum blockchain).

Dapp app architecture

The application architecture consists of a front-end that will be in HTML and Javascript. This Frontend will engage directly with the local ethereum blockchain that we will install.

DAPP app architecture

As stated in the first article the business rules and logic will be coded in a Smart Contract. The Smart Contract is written with the solidity programming language: https://solidity.readthedocs.io

Creation of the Front-End

The front-end will be simple it allows you to display the result of the vote for your favorite song in the form of a list and to choose from a drop-down list the song for which you wish to vote.

Check node installation

node -v

If node is not installed you can refer to my article on angular: http://128mots.com/index.php/2020/02/27/angular-en-plus-de-128-mots-partie-1/

Metamask installation: Installing https://metamask.io/ as an extension of your browser

Installation of the truffle framework: Truffle is a development environment, a testing framework and an asset pipeline for Ethereum, aimed at making your life easier as an Ethereum developer. It provides tools that allow us to write intelligent contacts with the Solidity programming language.

It will also be used to develop the front-end of the application.

npm install -g truffle

Ganache installation:

Ganache is a personal blockchain for Ethereum development that you can use to deploy contracts, develop your applications and run tests.

https://www.trufflesuite.com/ganache

This will allow you to have a local blockchain with 10 accounts that are powered with fake Ether.

I started the app and clicked Quick Start

We see the different accounts of our local blockchain.

Build a step-by-step, decentralized application (Ethereum Blockchain Dapp) in more than 128 words – Part 1

This article aims to explain the key concepts of blockchain, dapp (decentralized app), smart contract and tokenization.

Blockchain

A blockchain is a decentralized database, it is shared between several nodes that has a copy of that database.

Block

A request for a user to add data to the database is a transaction. Transactions are grouped and added to a block in the blockchain.

Note that all data in this shared register, the blockchain, is secured by cryptographic hash and validated by an algorithm that is a consensus among network users.

Block concept in a blockchain

Minor

Minors are network users who use a program to validate new transactions and record them on the blockchain.

Example of a miner's farm equipped to calculate transactions on the blockchain (via complex mathematical and cryptographic problem solving), miners receive a "reward" for their work.

Blockchain Ethereum

Ethereum is an open source platform that uses blockchain technology to run decentralized applications (dapps).

This platform is based on the creation of Smart Contract, it is a program that contains data and functions called by applications.

Based on the blockchain there is no centralized database but a register shared and maintained in peer to peer by users.

This technology can be used to exchange currencies or to create decentralized applications that call smart contracts and store their data in blocks of the blockchain.

Public Blockchain

In a public blockchain there is no permission, everyone can join the blockchain network, which means they can read, write or participate with a public blockchain.

Public Blockchains are decentralized, no one has control over the network and they remain secure because the data cannot be changed once validated on the block chain.

Public blockchain platforms such as Bitcoin, Ethereum, Litecoin are un authorized blockchain platforms, striving to increase and protect the anonymity of the user.

Private Blockchain

In a private blockchain there are restrictions to filter who is allowed to participate in the network and what transactions.

Private blockchains tend to be associated with identity management tools or a modular architecture on which you can plug in your own identity management solution.

This may be an OAuth solution service provider that uses Facebook, LinkedIn, for example,…

Token Ethereum

Ethereum tokens or tokens are digital assets that are built from the Ethereum blockchain. These are tokens that attest that you have a value (economic for example). These tokens are based on Ethereum's existing infrastructure.

To store, receive, send ether (cryptocurrency on the blockchain ethereum) or tokens (which are tokens that are digital assets), you need at least one account. The easiest way to create an account is:

It is possible to create its own token to create its decentralized application that uses the public blockchain ethereum.

Tokenisation of financial assets

Tokenization is a method that converts the rights of an asset (financial, real estate …) into digital tokens (tokens).

Example for a 400,000 Euro apartment. Tokenizing it consists of turning it into 400,000 tokens (the number is arbitrary, the Issue can be 4 million or 100 chips).

Tokens are issued on a kind of platform that supports intelligent contracts, for example on Ethereum. The goal is for tokens to be freely exchanged.

When you buy a token, you actually buy a share of the ownership of the asset (from the apartment of 400,000 euros).

Buy 200,000 chips and you own half the assets. The Blockchain is shared register that is immutable, it ensures that once you buy tokens, no one can delete your property.

Decentralized application

Decentralized applications are applications that communicate with the blockchain. The decentralized application interface is similar to any website or mobile application.

The Smart Contract represents the central logic of decentralized application.

Illustration of a DApp that uses a blockchain with smart contracts combined with the looters of Swarm and Whisper.
Source: Ethereum Stack exchange

Smart Contract

Smart Contracts contain all the business logic of a DApp. They are responsible for reading and writing data in the blockchain, so they execute business logic.

Intelligent contacts are written in a programming language called SOLIDITY https://solidity.readthedocs.io, similar to Javascript.

To read on the subject:

ANGULAR in less than 128 words – TypeScript – Angular Part 8

This article follows the first seven on the subject ANGULAR and deals with the language TypeScript:

Templates and interpolation

Interpolation is the incorporation of expressions into marked text. By default, interpolation uses double braces, 'and 'a' as a delimiter.

<h3>Customer Number: 'numbereroClient'</h3>

Example of a directive with iteration:

<li *ngfor="let client of listeClients">'customer.name'</li>

Services:

The services allow to decouple the component of the call to a service, they are thus reusable.

ng generate customer service
import - Injectable - from '@angular/core';

@Injectable
  providedIn: 'root',
})
export class ClientService

  constructor()

}

The logic is then decoupled from the service which is injectable via the addiction injection.

Addiction injection

Example of injection of CustomerService dependency into a CustomerComponent component

import - Component, OnInit - from '@angular/core';

import 'Hero ' from '.. /hero';
import 'HeroService ' from '.. /hero.service';
import 'MessageService ' from '.. /message.service';

@Component
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  StyleUrls:['./heroes.component.css']
})
export class ClientComponent implements OnInit

...

  getClients(): void
    this.clientService.getClients();
  }
}

ANGULAR in less than 128 words – TypeScrip – Angular Part 7

This article follows the first six on the subject ANGULAR and deals with the language TypeScript:

Manufacturer:

The builder is the method called to create the instance of an object

Class Point
    x: number;
    y: number;

    constructor (x: number, y: number)
        this.x x;
        this.y - y;
    }
    add (point: Point)
        return new Point (this.x - point.x, this.y - point.y);
    }
}

var p1 - new Point (30, 5);
var p2 - new Point (14, 21);
var p3 - p1.add (p2);

Optional setting:

If a setting is declared optional then all the parameters declared to its right are optional. Example of the name setting in the manufacturer.

Class Point
    x: number;
    y: number;
    name: string;

    constructor (x: number, y: number, name?:string)
        this.x x;
        this.y - y;
        this.name - name;
    }
}

Visibility:

By default the visibility of the setting is public, you can use "access modifiers" to change it.

Class Point
    private x: number;

Access modifiers can be positioned on methods, variables and properties.

Class Point
...
     private add (point: Point)
        return new Point (this.x - point.x, this.y - point.y);
    }
}
Class Point
...
    constructor (private x: number, private y: number)
...

Adding an access modifier (public/private/protected/reading only) to a builder setting will automatically assign that setting to a field of the same name.

Getter and setter:

TypeScript supports getters/setters as a way to intercept access to a member of an object.

This allows for a finer control over how a member is accessed on each object.

Const lengthMaxDuNom - 10;

Wage class
    private _nomComplet: string;

    get nameComplet(): thong
        return this._nomComplet;
    }

    name setComplet (newName: string)
        if (newName - newNom.length - lengthMaxDuNom)
            throw new Error ("Error Maximum length of the name reached, maximum length allowed - " lengthMaxDuNom);
        }
        
        this._nomComplet - newName;
    }
}

let salarie - new Salarie();
salarie.nameComplet - "Toto Hello";
if (employee.nomComplete)
    console.log (employee.nameComplete);
}

References to read:

ANGULAR in less than 128 words – Angular Components – Part 6

Block application construction

Components are like building blocks in an Angular application.

Components are defined using the @component decorator. A component has a selector, model, style and other properties, using which it specifies the metadata required to process the component.

Example of Angular component block architecture

AppComponent is the root component of our application. This is the base of the Angular application component tree.

https://angular.io/guide/architecture-modules

To generate a component the command is:

ng g component MyComponent

Sample component:

import - Component - from "@angular/core";

@Component
  selector: "articles"
  template: "<h2>Article</h2>"
})
export class ArticlesComponent
}

Note that if you haven't used the component generation control, then you have to manually add the component to the src/app/app.module.ts file in the imports.

import - BrowserModule - from "@angular/platform-browser";
import - NgModule - from "@angular/core";
import - AppComponent - from "./app.component";
import - ArticlesComponent - from "./articles.component";

@NgModule
  declarations: [AppComponent, ArticlesComponent],
  Imports[BrowserModule, ArticlesComponent]:
  Providers[]:
  Bootstrap:[AppComponent]
})
export class AppModule

ANGULAR in less than 128 words – TypeScript – Part 5

This article follows the first four on the subject ANGULAR and deals with the language TypeScript:

Use of classes

As in other languages a class allows to create objects and gathers variables and functions that are strongly related "Highly Related"

Class example

Class Person
  name: string;
  first name: string;

  To be more
    console.log ('My name is'- this.name' - this.prenom);
  }
}

Modules:

Class storage can be done in separate files, in this case it is a module statement.

The modules make the class accessible outside the file. The class must first be exported via "export" to be visible example of person.ts:

export class Person
  name: string;
  first name: string;

  To be more
    console.log ('My name is'- this.name' - this.prenom);
  }
}

example of hand.ts file that imports the Person class:

import - Person - from "./person";

let person - new person();

Note that there are Angular modules that will be imported with the mention @angular example:

import - Component - from '@angular/core';

Read:

https://www.typescriptlang.org/docs/handbook/modules.html

https://www.angularchef.com/recette/50/

ANGULAR in less than 128 words – TypeScript – Part 4

This article follows on from the first three on the subject ANGULAR and deals with the TypeScript language:

Concept of "assertion type"

Type assertion is a way to tell the TypeScript compiler what type of variable is. Type assertion is similar to type conversion in other languages, but in TypeScript, it's just a compilation function.

let testComplete: any - "Test Assertion type";
let test -<string>(complete test). substring (0.4);</string>
console.log(s);

Other ratings:

and full test: any - "Test Assertion type";
let test - (testComplete as string).substring (0.4);
console.log(s);

Arrow Function:

The use of function arrow removes the need to use the keyword "function." The settings are switched between brackets <> and the function expression is placed in brackets.

let addition - (a: number, b: number): number
            return a b;
}
addition (1, 2);

In line annotation:

In TypeScript, online type annotations allow you to declare an object for each of the object's properties.

Other use:

let addition - (pairDeNombre - numberA: number,numberB: number' number: number
            return a b;
}

Interface:

Interfaces allow you to name these types and are a powerful way to define contracts in your code as well as contracts with code outside of your project.

Point interface
  x: number,
  y: number
}

Link to TypeScript documentation: https://www.typescriptlang.org/docs/home.html

ANGULAR in less than 128 words – TypeScript – Part 3

TypeScript is a very typed, object-oriented and compiled typed language. TypeScript is a typical JavaScript overset compiled in JavaScript. TypeScript is JavaScript and some additional features.

Typescript documentation is available on this link: https://www.typescriptlang.org/docs/home.html

Installing TypeScript:

sudo npm install -g typescript

Execution of the TypeScript compiler:

tsc --version

Creating a first TypeScript example:

Creating the test.ts file:

function salutation (name)
    console.log ("Hello, " - name);
}

var user name - "John";
greeting (user name);

Compilation of the code:

tsc test.ts

At the end of the order a test.js file is created that can then be viewed:

function salutation (name)
    console.log ("Hello, " - name);
}
var user name - "John";
greeting (user name);

We find that for this example the code is the same in javascript and typescript, we can run:

Node test.js
Good morning, John.

Defining a variable with TypeScript:

It is possible to declare a variable with var that is classic in javascript or with let that is more secure with TypeScript. Declaring a variable with var gives it a global scope i.e. the variable is available throughout the code, the variable's scope limits to the "nearest block"

Example 1: use of var (global scope)

function display (test)
    var counts 1;

    if (test)
        var increase - count -5;
        return increase;
    }

    return increase;
}


display (false);

This code compiles but carries risks because the increase variable has not been declared if the test setting is false.

Example 2: use of less (scope limited to nearest block)

For the next code, the compilation is mistaken due to the limitation of the scope of the variable increase.

function display (test)
    Let counts 1;

    if (test)
        Increase - count - 5;
        return increase;
    }

    Error the variable does not exist
    return increase;
}
display (true);

test.tsc.ts
test.ts:10:12 - error TS2304: Can find name 'increase'.

TypeScript typing:

Let's count 10
'hello' account

The compilation of the code above confirms the strong typing of the language, when compiling the following error is removed:

test.tsc.ts
test.ts:2:1 - error TS2322: Type '"hello" is not assignable to type 'number'.

TypeScript type annotation:

The following types can be annotated in TypeScript:

let a: number; whole and decimal
let b: boolean;
let c: thong;
let's: any;
let's be: numbe[]r;
let f: numb[]er [4, 5, 6]'
let g: an[]y . . [4, 'Hello', true, 6].
const letterA - 'A';
Const green color - 1;

List in TypeScript:

enum Direction
    High -1,
    in Bas - 2,
    aLeft - 3,
    aRight - 4
}

next Direction - Direction.enHaut;

If we look at the code above after compilation by tsc we observe that the TypeScript code is much more comfortable than the one in JavaScript:

Var Direction;
(function (Direction)
    Directio[Direction["enHaut"]n - 1] - "high";
    Directio[Direction["enBas"]n - 2] - "Down";
    Directio[Direction["aGauche"]n - 3] - "Left";
    Directio[Direction["aDroite"]n - 4] - "right";
(Direction) (Direction));
vardirection - Direction.enHaut;

ANGULAR in less than 128 words – Part 2

This article follows the first part: http://128mots.com/index.php/2020/02/27/angular-en-plus-de-128-mots-partie-1/

Structure of an Angular project:

  • e2e: Automated tests end to end
  • node_modules: third-party modules installed for the development project (via npm install command)
  • src: main application file
  • app: Modules and components of the app
  • assests: storage of static elements (images, script …)
  • environments: Contains environmental variables
  • favicon.ico: Icon of the app
  • index.html: the app's main html file
  • hand.ts: app entry point (starts AppModule)
  • polyfills.ts: Adapts javascript to browser
  • style.css: style sheet
  • tsconfig.ts: typescript configuration
  • karma.conf.js: configuration of the test environment