# Solidity foundation - 1 Introduction to Solidity & Ethereum

By [Risky](https://paragraph.com/@risky) · 2023-02-24

---

What is blockchain
------------------

*   A blockchain is a **public database** that is updated and shared across many computers in a network. **Block** refers to **data** and **state** being stored in consecutive groups known as **blocks**.
    
*   If you send ETH to someone else, the **transaction** data needs to be added to a **block** to be successful. **Chain** refers to the fact that each **block** cryptographically references its parent.
    
*   In other words, blocks get chained together.
    
*   The data in a block cannot change without changing all subsequent blocks, which would require the **consensus** of the entire network.
    
*   At its core, a blockchain is a **replicated deterministic state machine**
    
    *   **Explanation**
        
        A state machine is a computer science concept whereby a machine can have multiple states, but only one at any given time. There is a state, which describes the current state of the system, and transactions, that trigger state transitions.
        
*   Each **block** added to the **chain** updates the **state** based on the **transactions** it includes.
    
*   The initial **state** of a blockchain is defined by the **Genesis Block**.
    
*   Every computer in the network must **agree** upon each new block and
    
*   the chain as a whole. These computers are known as **nodes**.
    
*   **Nodes** ensure everyone interacting with the blockchain has the **same data**. To accomplish this distributed agreement, blockchains need a **consensus mechanism**.
    
*   The reason is that most of the complications (mining, hashing, elliptic-curve cryptography, peer-to-peer networks, etc.) are just there to provide a certain set of features and promises for the platform.
    
*   Once you **accept these features as given**, you do not have to worry about the underlying technology.
    

Transactions
------------

A blockchain is a **globally shared**, **transactional database**.

This means that everyone can **read** entries in the database just by participating in the network.

If you want to change something in the database, you have to create a so-called **transaction** which has to be accepted by all others **nodes**.

The word transaction implies that the change you want to make is either **not done at all** or **completely applied**.

Furthermore, while your transaction is being applied to the database, no other transaction can alter it.

If a transfer from one account to another is requested, the transactional nature of the database **ensures** that, if the amount is subtracted from one account, then it is always added to the other account.

If due to whatever reason, adding the amount to the target account is not possible, the source account is also **not modified**.

Furthermore, a transaction is always **cryptographically signed** by the sender (creator).

This makes it straightforward to guard access to specific modifications of the database.

Furthermore, a transaction is always **cryptographically signed** by the sender (creator).

This makes it straightforward to guard access to specific modifications of the database.

Blocks
------

One major obstacle to overcome is what (in Bitcoin terms) is called a “**double-spend attack**”.

What happens if two transactions exist in the network that both want to empty an account? Only one of the transactions can be valid, typically the one that is **accepted first**.

The problem is that “first” is not an objective term in a peer-to-peer network.

So, how to solve that?

The abstract answer to this is that **you do not have to care**.

A globally accepted order of the transactions **will be selected for you**, solving the conflict.

The transactions will be bundled into what is called a “**block**” and the they will be executed and distributed among all participating **nodes**.

If two transactions contradict each other, the one that ends up being second will be **rejected** and not become part of the **block**.

These blocks form a linear sequence in time and that is where the word “**blockchain**” derives from.

As part of the “**order selection mechanism**” (which is called “**mining**” or “**validation**”) it may happen that blocks are reverted from time to time, but only at the “**tip**” of the chain.

The more blocks are added on top of a particular block, the less likely this block will be reverted. So it might be that your transactions are reverted and even removed from the blockchain, but the longer you wait, the less likely it will be (also known as finality).

What is ethereum
----------------

**Ethereum** currently uses a **proof-of-stake-based** consensus mechanism.

Anyone who wants to add new blocks to the chain must stake at least 32 **ETH** (Ethereum’s **network token**) into the **deposit contract** and run **validator software**.

They then can be **randomly selected** to propose **blocks** that other **validators** check and add to the **blockchain**.

In this model, there is usually only **one chain**, but network **latency** and **dishonest behavior** can cause **multiple blocks** to exist at the same position near the **head** of the chain.

To resolve this, a **fork-choice algorithm** selects one **canonical set** of blocks.

The blocks selected are the ones that form the **heaviest possible chain**, where **'heavy'** refers to the **number of validators** that have endorsed the blocks (weighted by the **ETH** they have staked).

There is a system of **rewards** and **penalties** that strongly **incentivize** participants to be honest and online as much as possible. **Practical example - Etherscan （**[https://etherscan.io/](https://etherscan.io/)**）**

Ether
-----

**Ether** (**ETH**) is the **native cryptocurrency** of **Ethereum**. The purpose of

**ETH** is to allow for a **market for computation**.

Such a market provides an **economic incentive** for participants to **verify and execute transaction requests** and **provide computational resources** to the network.

Any participant who broadcasts a **transaction request** must also offer some amount of **ETH** to the network as a bounty.

The network will award this bounty to whoever eventually does the work of **verifying** the transaction, **executing it**, **committing it** to the blockchain, and **broadcasting** it to the network.

The amount of **ETH** paid corresponds to the **resources required** to do the computation.

These bounties also **prevent** malicious participants from intentionally **clogging** the network by requesting the execution of infinite computation or other resource-intensive scripts, as these participants must pay for computation resources.

**ETH** is also used to provide **crypto-economic security** to the network in

three main ways:

1.  it is used as a means to **reward validators** who propose blocks or call out dishonest behavior by other validators;
    
2.  It is staked by validators, acting as **collateral** against dishonest behavior — if validators attempt to misbehave their ETH can be destroyed;
    
3.  it is used to **weight 'votes'** for newly proposed blocks, feeding into the fork-choice part of the **consensus mechanism**.
    

Accounts
--------

There are two kinds of **accounts** in Ethereum which share the same address space: **External Accounts** that are controlled by public-private key pairs (i.e. humans) and **Contract Accounts** which are controlled by the code stored together with the account.

The **address** of an external account is determined from the **public key** while the address of a contract is determined **at the time** the contract is created (it is derived from the creator address and the number of transactions sent from that address, the so-called “nonce”).

EVM
---

Ethereum is a blockchain with a **computer embedded** in it. It is the foundation for building apps and organizations in a **decentralized**, **permissionless**, **censorship-resistant** way.

In the Ethereum universe, there is a single, canonical computer (called the **Ethereum Virtual Machine**, or **EVM**) whose state everyone on the Ethereum network agrees on.

Everyone who participates in the Ethereum network keeps a copy of the **state** of this computer.

Additionally, any participant can broadcast a **request** for this computer to perform **arbitrary computation**.

Whenever such a request is broadcast, other participants on the network **verify**, **validate**, and **carry out** ("execute") the computation.

This execution causes a **state change** in the **EVM**, which is **committed** and **propagated** throughout the entire network.

Requests for computation are called **transaction requests**

Cryptographic mechanisms ensure that once transactions are verified as valid and added to the blockchain, they can't be tampered with later on.

The same mechanisms also ensure that all transactions are **signed** and **executed** with appropriate "**permissions**".

Smart contracts
---------------

In practice, participants don't write new code every time they want to request a computation on the EVM.

Rather, application developers upload **programs** into **EVM state**, and users make **requests** to **execute** these programs with varying **parameters**. We call the programs uploaded to and executed by the network **Smart Contracts**.

At a very basic level, you can think of a smart contract like a sort of **vending machine**: a script that, when called with certain parameters, performs some actions or computation if certain conditions are satisfied.

For example, a simple vendor smart contract could create and assign **ownership** of a digital asset if the caller sends **ETH** to a specific recipient.

Any developer can create a smart contract and make it **public** to the network, using the blockchain as its **data layer**, for a fee paid to the network.

Any user can then **call** the smart contract to **execute** its code, again for a fee paid to the network.

Thus, with smart contracts, developers can **build** and **deploy** arbitrarily complex user-facing apps and services such as: marketplaces, financial instruments, games, etc.

### Gas

Upon creation, each transaction is charged with a certain amount of **gas** that has to be paid for by the **originator** of the transaction.

While the EVM executes the transaction, the gas is **gradually depleted** according to specific rules.

If the gas is used up at any point, an out-of-gas exception is triggered, which ends execution and reverts all modifications made to the state in the current call frame.

This mechanism incentivizes **economical use** of EVM execution time and also compensates EVM executors (i.e. miners / stakers) for their work.

Since each ethereum block has a **maximum amount of gas**, it also limits the amount of work needed to validate a block.

The **gas price** is a value set by the **originator** of the transaction, who has to pay \[_gas\_price_ \* _gas_\] **up front** to the EVM executor. If some gas is left after execution, it is **refunded** to the transaction originator.

In case of an exception that reverts changes, already used up gas is **not refunded**.

Since EVM executors **can choose** to include a transaction or not, transaction senders cannot abuse the system by setting a low gas price.

The **more you pay** per gas, **higher the chance** of your transaction to be included in the next block.

What is smart contract
----------------------

Smart contracts - Tokens
------------------------

### What is a token?

Tokens can represent virtually anything in Ethereum:

*   reputation points in an online platform
    
*   skills of a character in a game
    
*   lottery tickets
    
*   financial assets like a share in a company
    
*   a fiat currency like USD
    
*   an ounce of gold
    
*   and more...
    

### Tokens standards

Many Ethereum **development standards** focus on token interfaces.

These standards help ensure smart contracts remain composable.

For example: when a new project **issues a token**, following the standard grants that it remains **compatible** with existing **decentralized exchanges**.

**ERC-20** - A standard interface for **fungible** (interchangeable) tokens, like voting tokens, staking tokens or virtual currencies.

**ERC-721** - A standard interface for **non-fungible** tokens, like a deed for artwork or a song.

**ERC-1155** - Token standard that allows for creating both **fungible** and **non-fungible** Tokens like CryptoPunks. This standard allows for more efficient trades and bundling of transactions – thus saving gas costs.

ERC20 tokens
------------

The **ERC-20** introduces a standard for **Fungible Tokens**, in other words, they have a property that makes each Token be **exactly the same** (in type and value) as another Token.

For example, an **ERC-20 Token** acts just like the **ETH** in Ethereum network, meaning that 1 Token is and will always be equal to all the other Tokens.

### ERC20 Tokens - Standard

The **ERC-20** token standard, proposed by Fabian Vogelsteller in November 2015, is a Token Standard that implements an API for tokens within Smart Contracts.

Example functionalities ERC-20 provides:

*   **transfer** tokens from one account to another
    
*   get the current **token balance** of an account
    
*   get the **total supply** of the token available on the network
    
*   **approve** whether an amount of token from an account can be spent by a third-party account
    

If a Smart Contract **implements** all the standard methods and events, it can be called an **ERC-20 Token Contract**.

Once deployed, it will be responsible to keep track of the created tokens on the blockchain.

ERC721 tokens
-------------

A **Non-Fungible Token** (**NFT**) is used to identify something or someone in a unique way.

This type of Token is perfect to be used on platforms that offer collectible items, access keys, lottery tickets, numbered seats for concerts and sports matches, etc.

This special type of Token has amazing possibilities so it deserves a proper Standard, the ERC-721 came to solve that!

The ERC-721 introduces a standard for NFT, in other words, this type of Token is unique and can have different value than another Token from the same Smart Contract, maybe due to its age, rarity or even something else like its visual.

All **NFT**s have a numerical variable called **_tokenId_**, so for any **ERC-721** Contract, the pair contract address, the **tokenId** must be **globally unique**.

That said, a dapp can have a "**converter**" that uses the _tokenId_ as **input** and **outputs an image** of something cool, like zombies, weapons, skills or amazing kitties!

Standard
--------

The **ERC-721** token standard, proposed by William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs in January 2018, is a Non-Fungible Token Standard that implements an API for tokens within Smart Contracts.

It provides functionalities like to **transfer** tokens from one account to another, to get the current **token balance** of an account, to get the **owner** of a specific token and also the **total supply** of the token available on the network.

Besides these it also has some other functionalities like to **approve** that an amount of token from an account can be moved by a third party account.

If a Smart Contract implements all the standard methods and events it can be called an **ERC-721 Non-Fungible Token Contract**.

Once deployed, it will be responsible to keep track of the created tokens on the blockchain.

---

*Originally published on [Risky](https://paragraph.com/@risky/solidity-foundation-1-introduction-to-solidity-ethereum)*
