Please insert coin to start

ether

Ethereum is a decentralized platform that executes smart contracts: applications that run exactly as scheduled without the possibility of downtime, censorship, fraud or third-party interference.

Smart contracts are usually programmed with Solidity which is a mixture of several languages: C++, Javascript and Python, and is still in development.

Thanks to solidity and several technologies already known as html, css and javascript, Dapps (distributed applications) can be created. 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 change of paradigm and it is currently trending topic.

Although this Ethereum course with solidity was created as of February 2018 , currently Ethereum and solidity evolve rapidly, and some commands and APIs are becoming obsolete, so you are likely to find many examples on the Internet that no longer work.

The solidity course is composed of a interactive practice part and another theory part (in the lower area)

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

Instructions for using the practice part
  • To compile the smart contract press button "Compile".
  • To get the balance of an account (address) inform de public key and press button "Balance".
  • To deploy the smart contract you can use Metamask or inform the address (with at least 0.1 Ether) and the private key and press button "Deploy using private key..."
  • To view transaction details inform the tx hash and press button "View transaction".
  • To view transaction receipt (address del contrato) inform the tx hash and press button "View receipt".
  • To view block data inform the block number and press button "View block".

Solidity editor


Contract details

     

    Ethereum testnet - Ropsten

    Wallet

    ... Ether

      Search blocks and transactions

       

      Block data

      Transaction data

      Receipt data

      Solidity

      A smart contract is located at a specific address (address) within the Ethereum blockchain.

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

      There are two types of accounts: the external accounts that are controlled by key pairs (public / private) and the contract accounts that are controlled by the source code of the contract. The account of a contract is created at the time the contract is displayed in the blockchain.
      Each account has a balance in units of wei (ether) that can be modified by sending transactions that include a value.

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

      A call is a message that does not involve ether. For example, a call to a method of a contract.

      Each transaction is loaded with a quantity of gas, which is consumed during its execution. The creator of the transaction sets the price of the gas, and must pay a total = gas price * gas used from his/her ether account. If there is gas left over during the transaction, after the execution it will be returned.

      Each 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 contracts from other contracts or to send ether to non-contract accounts. They are similar to transactions.

      Contracts can load dynamic code from another address. The "storage", address and the balance refer to the contract that makes the call. This makes it possible to implement libraries in solidity.

      Contracts can save logs in a special region of the blockchain, and are used in the handling of events . The contracts can not access the logs after creating them, but they can be seen from outside the blockchain, for example from a "thin client".

      Solidity, the language to develop smart contracts

      We can think of a contract as being a class in object-oriented programming.

      The attributes would be the state variables and the properties would be the functions that can modify these state variables.

      You would also have your constructor (only one is allowed) although it is optional.

      To define a contract, use the pragma statement with the solidity version and then contract :

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

      This example contract does not do anything special, it only saves a data that is a whole number. And anyone could call the set method to change it.

      Within a contract we usually define events, data structures and enums.

      Functions can have modifiers that change the behavior. For example, visibility: as private or public.

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

      A public variable can be read by the rest of contracts and actors.

      State variables are permanently stored in the contract.

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

      Solidity source code files usually have the extension .sol and use the style guide pep8 inherited from Python .

      Inheritance

      Contracts can inherit from others using is.

      Multiple inheritance is allowed.

      contract foo is father { 
        variables
        funciones 
      }

      new

      A contract can create another contract with the word new. You can send ether when creating the contract, calling value() method after the constructor.

      Destruction

      A contract can be destroyed with the call selfdestruct (address), sending accumulated ether to that address. It is the only way to eliminate a contract from the blockchain. Although it is always advisable to have a state variable to deactivate it that causes throws to be thrown when invoking their functions, so the ether will be returned. It is recommended to save the msg.sender in the constructor and then pass it as an argument in selfdestruct.

      Abstract contracts

      They are contracts that have some functions without implementation. That is, the name of the function, the input and output parameters are defined, and it is ended with a semicolon. These contracts are not compiled, they are used as base contracts for other contracts that inherit them.

      Interfaces

      The interfaces are similar to the abstract contracts, but they can not have any function implemented. Neither can they inherit from other contracts or interfaces, they can not define a constructor, nor variables, nor structs, nor enums. They are used in the contracts that inherit them.

      You can use a powerfull online compiler: Remix or EthFiddle a simpler one.

      Solidity is a statically typed language, which means that the type of each variable (state and local) must be specified at compile time. The language provides certain types of basic variables, which can be combined to form complex types.

      Types

      bool: a value that can be true or false.

      uint: a signed or unsigned integer. The smaller size is 8 bits (uint8) and the bigger one is 256 bits (uint256). There are types for all sizes in steps of 8. This type is also used for amounts & dates (unix format).

      Ether units: an amount can have a suffix to determine its value: wei, finney, szabo, ether. By default: wei.

      Time units: an amount can have a suffix to determine a time: seconds, minutes, hours, days, weeks, years. By default: seconds.

      address: a special type of 20 bytes that stores an ethereum address. It has two properties: balance (to know the balance) and transfer (to send ether (in wei units) to an address.

      Note: Wei is the smallest amount of Ether. 1 Ether is 1018 Wei.

      msg: it has the message received by the contract. It has some properties: sender (sender's address), value (amount of ether in wei), data (call data), gas (remaining gas).

      Note: If the method is a constructor then msg.sender is the contract's owner.

      now: current date in unix format (uint), is the same as the block.timestamp.

      block: block data. It has some properties: number (current block number), difficulty (current block difficulty), gasLimit (block's gas limit).

      storage: persistent storage of hash.

      fixed-sized arrays: arrays with fixed size like byte1, byte2, ...byte32 with the property length that is the arrays's length.

      dinamically-sized arrays: arrays with variable size like bytes, string (UTF-8). Strings are enclosed within simple or double quotes. Compatible with escape chars like \n \uNNNN. There are also hexadecimal defined with hex. Dinamically-sized arrays can be redim if they are in storage (not in memory) changing its property length. These ones have also an adding elements' function push. This function returns the new length of the array.

      enums: to create specific types defined by the user.

      struct: complex types defined by the user that include some other simpler types.

      dictionary (key/value): created with mapping(key type => value type).

      this: refers to contract's address, so this.balance is the balance stored in the contract.

      Variables can be initialized or reset with delete. Sets 0 the values.

      Because the variables are visible in the blockchain, you can hash values to "hide" real values.

      Constants

      State variables can be declared as constants. Therefore they have to be assigned to a value at compile time. 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 if we want to store it in memory (memory) or in storage (storage). By default it is in memory for the arguments of the functions and their return, whereas for the state variables the default value is storage.

      The functions in solidity are specified as follows:

      function () {internal|external} [pure|constant|view|payable] [returns ()]

      They can be internal or external. The return types can not be empty. If nothing s returned then do not specify the returns statement.

      Functions can return more than one parameter, each specified within the "returns" statement.

      By default, the functions are internal, so this modifier is usually omitted. The initern are only visible in the current contract and those who inherit from it.

      Visibility

      The functions can be external, internal, private or public. By default they are public.

      external:

      External functions are part of the contract interface and can be called from other contracts and via transactions. Can not be called internally.

      public:

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

      internal:

      Internal functions and state variables can only be accessed internally (from the current contract or contracts that derive from it) without using this.

      private:

      Private functions and state variables are only visible in the contract in which they are defined, and not in inherited contracts.

      Overload

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

      Modifiers

      The modifier constant indicates that the function can not change the variable. It runs locally, not in the blockchain. Its use is deprecated in favor of pure or view.

      The modifier view indicates that the function not modifies state.

      Note: What is considered modifying the state: write the value of the variable, trigger an event, create another contract, use selfdestruct, send ether via calls, invoke another function that is not pure or view, use low level calls, use assembler code that contains certain opcodes.

      The modifier pure indicates that the function does not change a variable nor reads 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.data, invoke another function other than pure, use assembly code that contains certain opcodes.

      The modifier payable shows that the function can receive ether.

      You can create custom modifiers for functions with the word modifier. For example, this is one that validates that only the creator of the contract invokes it:

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

      You can call functions of other contracts with external calls, in that case you can indicate the value of wei and gas sent with the methods .value(v).gas(g)

      These calls can throw exceptions if the contract does not exist, or the external method throws 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 , otherwise it is not possible to send ether to the contract through transactions. Except in the case of being the destination of a coinbase transaction (a miner's reward) or a selfdestruct destination.

      Flow control structures

      The majority of control statements that are used in Javascript are allowed except switch & goto. So we can use: if, else, while, do, for, break, continue, return, ?:

      Parentheses can not be omitted, and curly braces can not be omitted, unless it is a single simple assignment.

      Throw

      Exceptions can be thrown, but they can not be captured. The throw statement resets the ether to the sender and the state.

      Error handling

      Error handling is very simple in solidity. There are several statements to manage errors:
      assert (condition) (trigger a throws if condition is not met, for instance when some error is found),
      require (condition) (trigger a throws if condition is not met, for instance when validating input variables),
      revert (abort execution and reset state changes).

      Iterators

      Iterations are limited in solidity, you can traverse an array, but maps can not be traversed without knowing the "keys".

      Math and crypto functions

      There are some hashing functions, included module add and multiply.

      addmod(uint x, uint y, uint k) returns (uint):

      calculates (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2**256. Assert that k != 0 starting from version 0.5.0.

      mulmod(uint x, uint y, uint k) returns (uint):

      calculates (x * y) % k where the multiplication is performed with arbitrary precision and does not wrap around at 2**256. Assert that k != 0 starting from version 0.5.0.

      keccak256(...) returns (bytes32):

      calculates Ethereum-SHA-3 (Keccak-256) hash of tightly packed arguments

      sha256(...) returns (bytes32):

      calculates SHA-256 hash of tightly packed arguments

      sha3(...) returns (bytes32):

      is an alias for keccak256

      ripemd160(...) returns (bytes20):

      calculates RIPEMD-160 hash of tightly packed arguments

      ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address):

      recover the address associated with the public key of the elliptic curve signature or return zero if there is an error

      Note: tightly packed arguments means that the arguments are concatenated without padding.

      In solidity you can define events with the event MyEvent statement (a) and then you can trigger that event by calling MyEvent (a).

      This is useful for calling callback Javascript functions, in the part of the view of a Dapp (distributed application).

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

      The data of the events can not be consulted from within a contract.

      For instance in Javascript:

                var abi = /* abi generated by the compiler */;
                var ClientReceipt = web3.eth.contract(abi);
                var clientReceipt = ClientReceipt.at("0x1234...ab67" /* address */);
      
                var event = clientReceipt.Deposit();
      
                //watch for changes 
                event.watch(function(error, result){
                  if (!error)
                    console.log(result);
                });
      
                // Or use a callback to watch changes inmediately
                var event = clientReceipt.Deposit(function(error, result) {
                  if (!error)
                    console.log(result);
                });