Introduction to Ethereum

In this brief introduction of the Ethereum course we will treat the Key conceptsThey are necessary to learn Solidity.

Altcoin

Ethereum is a Altcoin, which is an English denomination of "Alternative Coin", which refers to cryptocurrencies that are built from the Bitcoin Source Code (Forks) or taking Bitcoin concepts, although some are more similar than others.

Ethereum's popularity is that he proposes A platform to create, compile and deploy Smart ContractsIn a network of blockchain nodes.

Wallets and accounts

To store these Ether tokens are used Wallets (digital wallets). There are several types; Physical, paper, as an extension of the browser, Wallets online, or applications for the computer and smartphone. One of the best known programs for the computer is Exodus, and Coinbase (which gives you free cryptocurrencies)Like Wallet Online.

You can currently use these coinbase invitations to get:
Stellar (Digital Cash)
Compound (Defi)
Band Tokens (Oracles)

These wallets inside have several pairs of public/private keys where Ether is "stored". This is called an external account. The Smart Contracts also have an account that is created at the time the smart contract is displayed.

Ethereum uses elliptical curve cryptography (ECC) to generate these peers. Use 256-bit encryption.
Each account is represented by an Address.

Transaction and call

A transactionIt is a message that is sent from an account (public address of Ethereum) to another account (or a contract). It can include data and Ether. A callIt is a message that does not contain Ether. For example calling a method of a Smart Contract.
To give "good" or "consolidated" a transaction, we should see about 20 confirmations in the blockchain.
These transactions require the transaction to firm the transaction before sending it with its private key.

Consensus algorithm

Each node that is part of an Ethereum network stores its copy of the blockchain. To ensure that no one corrupts that data in their own node and sends it to the network a mechanism is used consensus algorithmthat in Ethereum is the Pow (Proof of Work), a test of work, the famous mining of Ether, which involves a very intensive calculation to consolidate the transactions in a block. This work test serves to verify that a transaction is legitimate and to obtain Ethher (ETH) as a reward when it undermines a block.

Check the Ethereum mining tutorial Before continuing.

Recently this consensus algorithm was changed to the Pos (proof of stake), in this case the miner that consolidates a block of transactions is determined by its amount of Ether in its portfolio. There is usually no reward for block, rather the transactions commissions are obtained.

One of the Current problems with Ethereum is your scalability, because it can reach a few transactions per second using the Pow. The idea is to change this consensus algorithm for a post -type type, where there will be a group of validators that will be the future "miners". In addition to reducing energy expenditure, it is expected to reach a transaction rate per second several orders of magnitude higher than the current one.

Ether units

As we have said, the reward token is called Ether and is divided into several units with proper names. Thus, the smallest unit is called Wei and the largest is called Tether.

Token ERC-20 and ERC-721

Tokens are a specific type of Smart Contract that is usually of several types: ERC-20that is created above the Blockchain of Ethereum. That Smart Contract contains a series of common methods that allow to transfer, and create these tokens. It is the token par excellence that it uses in the ICO (financing models of a project in which users buy tokens in exchange for Ether or Bitcoin).
Another type of token is the ERC-721that allows creating tokens that are not fungible, that is to say that each of them is unique and cannot be exchanged for another.

Many of the popular tokens have been or are ERC-20 such as Eos, Tron, Vechain, ...

Ethereum virtual machine (EVM)

The Smart Contracts They run on a virtual Ethereum machine (EVM)that is shared between all nodes of the network. Each node of the network executes a virtual Ethereum machine.

Transactions have a cost to prevent the network with spam from being flooded and irrelevant and extensive information is stored in the blockchain.
A token is used to measure the computational spending called gas. Then each transaction specifies its gas limit and a commission that will pay for the gas. If the required gas is greater than the established gas limit, the transaction will not be carried out and will be aborted. Each operation allowed in that virtual machine has a fixed cost of gas to be able to calculate the costs.

Customer programs

The most popular Ethereum customers are Gethand Parity

Geth (Go Ethereum) is a client program development on Go to start a node from the Ethereum network. We will find it for several operating systems.
Geth himself provides an API JSON so that other applications can be communicated with him, using HTTP or Websockts. It also provides an interactive JavaScript console where certain APIS can be used.
Geth has several parameters among them the most used are:

  • -Datadir directory
    It is used to specify the folder where the blockchain is stored. If it is not specified by default it is kept in the user's home inside the .Ethereum folder
  • --Networkid num
    It is used to define the network to which we are going to connect. The Mainnet (which is used Ether Real) has value 1, and the 2.3 etc are testnet (which do not use Ether Real).

Private networks

Geth can be used to create a private network for applications development purposes. For this, the flag is used -from

Smart Contracts

The most popular language to develop Smart Contracts is Solidity

Ethereum is a decentralized platform that executes Smart Contracts: applications that are executed exactly as programmed without the possibility of time of inactivity, censorship, fraud or interference of third parties.

Smart contracts are usually programmed with Soliditywhich is a mix of several languages: C ++, Javascript and Python, and it is still a bit limited.

Thanks to Solidityand to several technologies already known as HTML, CSS and JavaScript, they can be created DAPPS(distributed applications). It is possible to think that these applications have part of their backend in a blockchain (either private or public). It is a very interesting paradigm change and is currently a trend.

Ethereum and Solidity are currently evolving rapidly, and some sentences and APIS are obsolete, so you are likely to find many examples on the Internet that no longer work.

The solidity course is composed of a Interactive practical partand another Theoretical part (in the lower area)

To perform SMART Contracts compilation tests with solidity, the following editor can be used. Smart Contracts can be deployed in the test network - Ropsten.

In order to compile and deploy your smart contracts it is necessary to have THT tokens.

If you need ETH in your test account to do the practices, you can use the faucet.

Instructions to use the practical part
  • To be able to edit and compile Smart Contracts you need THT tokens.
  • To see the last mined block or verify that the network node is active to tighten the "see node info button and confirm that connected = True".
  • For compileThe Smart Contract Tighten the "Compile" button.
  • To know the balanceof an account (address) inform the address (public key) and tighten the "balance" button.
  • For deployThe Smart Contract can use an account inMetamSkor inform the Address (which has at least 0.1 Ether) and the private key and tighten the "Smart Contract Smart Using Key ..." button.
  • To see the transaction detailInform the hash TX and tighten the "See Transaction" button.
  • To see the Receipt of the transaction (Smart Contract address)Inform the hash TX and press the "See receipt" button.
  • To see the block detailInform the block and tighten the "See block" button.

Solidity editor


Smart Contract details

     

    Display Smart Contract on the Ethereum Network of Test - Ropsten

    Deployment options

    Ether

      Block and Transactions Explorer

       

      Block detail

      Transaction detail

      Detail of the receipt

      If this solidity course seems useful to you, you can collaborate in tokens ETH, USDT: 0x3699F28291AEAEAEE75A9155239E095F42DE910E4

      Solidity language in detail

      A Smart Contract is located in a concrete direction (Address) within the Ethereum blockchain.

      Smart contracts are executed within a Ethereum virtual machine (EVM). The code that executes does not have access to the network, the file system, or to other processes. It only has limited access to other smart contracts that are located in the blockchain.

      There are two types of accounts: External accountswhich are controlled by key pairs (public/private) and Smart Contract accountsThey are controlled by the Smart Contract source code.
      The account of a Smart Contract is created at the time the smart contract is deployed in the blockchain.
      Each account has a balance in Wei units (Ether) that can be modified by sending transactions that include a value.

      A transactionIt is a message that is sent from one account to another. It can include binary data (payload) and Ether.

      A callIt is a message that does not involve Ether. For example a call to a method of a Smart Contract.

      Each transaction is loaded with an amount of gas, which is consumed during its execution. The creator of the transaction fixes the price of gas, and must pay a TOTAL = GAS PRICE * GAS USEDof his Ether account. If gas is left over when performing the transaction, after the execution it returns.

      Each Smart Contract account has a persistent memory region called "Storage". It also has another region of memory called "Memory" that is created in each message call.

      Message calls are used to invoke Smart Contract from other Smart Contract or to send Ether to accounts that are not Smart Contract. They are similar to transactions.

      Smart Contracts can load dynamic code of another direction. The "Storage", Address and the balance refer to the Smart Contract that makes the call. This makes it possible to implement libraries in Solidity.

      Smart contracts can Save Logsin a special region of the blockchain, and is used in the management of events. The Smart Contracts cannot access the logs after creating them, but these can be seen from outside the blockchain, for example from a "light customer."

      Solidity, the language to program Smart Contracts

      We can think that a smart contract is like in a classIn object -oriented programming.

      The attributeswould be the state variables and propertiesThey would be the functions that can modify these state variables.

      I would also have his builder(One is only allowed) although it is optional.

      To define the version of the compiler of a Smart Contract the sentence is used pragmaWith the solidity version and then Contract

      pragma solidity ^0.4.18;
      
      contract GuardarDato {
        uint dato;
      
        function set(uint x) public {
          dato = x;
        }
      
        function get() public constant returns (uint) {
          return dato;
        }
      }

      This Smart Contract of example does nothing special, it only keeps a fact that is an integer. And anyone could call the Set method to change it.

      Within a Smart Contract we usually define Events, data structures and enums.

      Functions may have ModifiersThey change the behavior. For example visibility: as private or public.

      Variables can also have visibility, thus a private variable is visible by the rest of the blockchain actors, but it is not accessible from the rest of the smart contracts.

      A public variable can be read for the rest of Smart Contracts and actors.

      State variables are permanently stored on the Smart Contract.

      The commentsThey are written with // for a single line or with / * .... * / for several lines.

      Solidity source code files usually have the extension. Pep8 styles guide inherited from python

      Inheritance

      Smart contracts can inheritof each other with the sentence es

      Multiple inheritance is allowed.

      contract micontrato is contratopadre { 
        variables
        funciones 
      }

      New

      A Smart Contract can create another Smart Contract with the sentence New. Ether can be sent when creating the Smart Contract invoking the Value () method after the builder.

      Destruction

      A smart contract can destroyWith the call SelfDesruct (Address), sending the accumulated Ether to that address. It is the only way to eliminate a smart contract from the blockchain. Although it is always advisable to have a state variable to deactivate it that makes Throws be launched when invoking their functions, so the Ether will be returned.
      It is advisable to save the msg.senderin the builder and then spend it as an argument in SelfDesruct

      Abstract contracts

      They are smart contracts that have some functions without implementation. In other words, the name of the function, the entrance and exit parameters, is defined, and ends with a point and coma. These Smart Contracts are not compiled, are used as Smart Base contracts for other Smart Contract that inherit them.

      Interfaces

      The interfaces are similar to the SMART abstract contracts, but cannot have any implemented function. Nor can they inherit from other Smart Contracts or interfaces, they cannot define a builder, or variables, nor structures, nor enums. They are used in the smart contracts that inherit them.

      There is a very complete online compiler:Remix, a cloud solidity compilereitherEthfiddlewhich is another more limited online compiler for solidity.

      END PANEL BODY
      end idcollapse
      End panel

      Solidity is a tipado tipado stan, which means that the type of each variable (state and local) has to be specified in compilation time. Language provides certain types of basic variables, which can be combined to form complex types.

      Types of variables

      bool: Describe a value that can be true or false. (True/False)

      Uint: They describe whole numbers, with a sign or without a sign of various sizes. The smallest is 8 bits (UINT8) and the largest of 256 bits (Uint256). There are definitions for all intermediate sizes by jumping from 8 in 8. This type is also used to amountsand dates(UNIX format).

      Ether units: an amount can have a suffix to determine its measure. Wei, Finney, Szabo, Ether. By default is Wei.

      Time units: An amount can have a suffix to determine time. Seconds, Minute, Hours, Days, Weeks, Years. By default is Seconds.

      Address: It is a special 20 bytes type that stores a Wallet address from Ethereum. This type has 2 properties: balance(To know the balance) and Transfer(To send Ether in Wei units to an address.

      Note: Wei is the smallest unit of Ether. 1 Ether is equivalent to 1018Wei

      msg: Refers to the message received by the Smart Contract. Its properties are Sender(the address of which it sends), value(quantity of Ether in Wei), Data(call data), gas(residual gas).

      Note: If the method is then the MSG.sender will be the creator of the Smart Contract.

      Now: The current date in UNIX format (UINT), is equivalent to Block.timestamp

      Block: Block data. It has the properties Number(current block number), Difficulty(current difficulty of the block), Gaslimit(Block gas limit).

      Storage: Persistent hash storage.

      fixed arrays: They are arrays with fixed length like byte1, byte2, ... byte32 and have the property Lengthwhich shows the length of the array.

      dynamic arrays: They are arrays of variable length such as bytes, string (coded in UTF-8). The literal chains are enclosed in double or simple quotes. They support special escape characters such as \ n and \ unnn. There are also hexadecimal literals defined with hex. Dynamic arrays can be resolved if they are found in the Storage (not in memory) by changing the value of their length property. These aays also have the function Pushwhich serves to add an element at the end of the array. This function returns the new length of the array.

      Enums: They serve to create specific types defined by the user.

      Struct: They are types defined by the developer that group several variables.

      Dictionaries(key/value): They are created withMapping (type of the key => value type)

      This: Refers to the Smart Contract Address, so This.balanceIt is the accumulated balance in the Smart Contract.

      The variables can be initialized or clean with the sentence delete. Puts the values ​​to 0.

      As the content of the variables can be seen in the blockchain, from outside the Smart Contract, you can hide the value using hashing.

      Constants

      State variables can be declared as constants. Therefore, they have to be assigned to a compilation time value. Only numerical values ​​or strings are allowed. And it is also allowed to assign them to hash functions (KECCASK256, SHA256, etc).

      Persistence

      Complex variables, such as Arrays and Structs, have an extra modifier to indicate whether we want to save it in memory (Memory) or in storage (Storage). By default it is in memory for the arguments of the functions and their return, instead for the state variables the default value is a storage.

      Functions in Solidity are specified as follows:

      function () {Internal | External} [Pure | Constant | View | Payable] [Returns (Returns (

      They can be internal or external. Return types cannot be empty. But nothing returns, not specify the Returns sentence.

      The functions can return more than one parameter, each specified within the "Returns" sentence.

      By default the functions are internal, which usually omits this modifier. The internal ones are only visible on the current Smart Contract and those who inherit from it.

      Visibility

      Functions can be external, internal, private or public. By default are public.

      external:

      External functions are part of the Smart Contract interface and can be called from other Smart Contracts and via transactions. They cannot be called internally.

      public:

      Public functions are part of the smart contract interface and can be called internally or via messages. For public state variables a getter function is automatically generated.

      internal:

      Internal state functions and variables can only be accessed internally (from the current Smart Contract or Smart Contracts that derive from this) without USA This.

      Private:

      Private state functions and variables are only visible on the Smart Contract in which they are defined, and not in Smart Contracts inherited.

      Overload

      A Smart Contract can have several functions with the same name but with different arguments. This also applies to inherited functions of another smart contract.

      Modifiers

      The modifierConstantIndicates that the function cannot change the variable. It runs locally, not in the blockchain. Its use is depreciated in favor of Pure or View.

      The modifierViewIndicates that the function does not modify the State.

      Note: It is considered to modify the state: Write the value of the variable, shoot an event, create another smart contract, use selfddstruct, send Ether traveled, invoke another function other than pure or view, use low -level calls, use assembly code that contains certain options.

      The modifierpureeIndicates that the function does not change a variable or read it.

      Note: It is considered reading: Read the value of a state variable, access this.balance, or address.balance, access block, TX, or MSG methods, except msg.sig and msg.

      The modifierPayableIndicates that the function can receive Ether.

      Custom modifiers can be created for functions with the sentence Modifier. For example, this is one that is valid for only the creator of the smart contract:

      modifier soloCreador {
        if (msg.sender == owner)
        _
      } 

      You can call the functions of other smart contracts with external calls, in that case the value of Wei and gas sent with the methods can be indicated .VALUE (V) .GAS (G)

      These calls can launch exceptions if there is no Smart Contract, or the external method launches an exception.

      A failure function is usually defined, in case incorrect data is sent, or Ether is sent without data:

      function () {
        throw;
      }

      To receive Ether, it must be marked as Payable, but there is no Ether to Smart Contract through transactions. Except in the case of being the fate of a coinbase transaction (a mining reward) or a selfddstruct destination.

      Flow control structures

      The majority of control sentences used in JavaScript is allowed except Switch and Goto. So we can use: if, else, while, do, for, break, continue, return, ?:

      The parenthesis cannot be omitted, and the keys either, unless it is a single simple assignment.

      Throw

      Exceptions can be launched, but they cannot be captured. The sentence ThrowEther restores the Sender and the State.

      Error treatment

      The error treatment is very basic in Solidity. There are several sentences to manage errors:
      ASSERT (condition)(Make a THROWS if the condition is not fulfilled, for example internal errors),
      REQUIRE (CONDITION)(Make a THROWS if the condition is not met, for example to validate tickets),
      Revert(abort the execution and restore state changes).

      Iterators

      The iterations are limited in Solidity, an array can be traveled, but the maps cannot be traveled without knowing the "keys."

      Mathematical and cryptographic functions

      We have several hashing functions and module multiplication available.

      Addmod (Uint X, Uint and, Uint K) Returns (Uint):

      Calculate (x + y) % k where the sum is performed with arbitrary precision and does not adjust to 2 ** 256. Assert that k! = 0 from version 0.5.0.

      Mulmod (Uint X, Uint and, Uint K) Returns (Uint):

      Calculate (x*y) % k where the sum is performed with arbitrary precision and does not adjust to 2 ** 256. Assert that k! = 0 from version 0.5.0.

      KECCAK256 (...) Returns (bytes32):

      Calculate the hash ethhereum-sha-3 (Keccak-256) of the packaged arguments

      SHA256 (...) Returns (bytes32):

      Calculate the hash Sha-256 of the packaged arguments

      Sha3 (...) Returns (bytes32):

      It is a alias of Keccak256

      Ripemd160 (...) Returns (bytes20):

      Calculate the hash Ripemd-160 of the packaged arguments

      ECRECOVER (bytes32 hash, Uint8 V, bytes32 r, bytes32 s) Returns (address):

      Recovers the address associated with the public key of the signing of the elliptical curve or returns zero if there is error

      Note: Packaging arguments means that the arguments are concatenated without padding (filling).

      In solidity events can be defined with the sentence EventMere (a)and then that event can be triggered by calling on myself.

      This is useful for calling Callback Javascript functions, in the view of a DAPP (distributed application).

      The arguments are stored in the transaction log, a special data structure in the blockchain.

      The events of the events cannot be consulted from a Smart Contract.

      And in JavaScript:

                var abi = /* abi generado por el compilador */;
                var ClientReceipt = web3.eth.contract(abi);
                var clientReceipt = ClientReceipt.at("0x1234...ab67" /* address */);
      
                var event = clientReceipt.Deposit();
      
                // esperar a que hayan cambios
                event.watch(function(error, result){
                    if (!error)
                    console.log(result);
                    });
      
                // O pasar una función de callback para ver cambios inmediatamente
                var event = clientReceipt.Deposit(function(error, result) {
                    if (!error)
                    console.log(result);
                    });
                

      Этот веб-сайт использует файлы cookie для получения статистических данных о навигации своих пользователей. Если вы продолжаете просмотр, мы считаем, что вы принимаете его использование. политики cookie