Workshop:
Ethereum e
Smart Contracts
André Ferreira
● twitter.com/aferreira44
● linkedin.com/in/aferreira44
● facebook.com/aferreira44
E-mail: contato@andreferreira.me
Ethereum
Ethereum é uma plataforma descentralizada que executa
contratos inteligentes: aplicativos que funcionam exatamente
como programado sem qualquer possibilidade de tempo de
inatividade, censura, fraude ou interferência de terceiros.
Smart Contract
Um contrato inteligente (“smart contract”) é um trecho de
código, com suas funções e dados, que reside em um
endereço específico na cadeia de blocos do Ethereum e
executa obrigações contratuais automaticamente.
Ether
Ether é um elemento necessário - um combustível - para
operar a plataforma de aplicação distribuída do Ethereum. É
uma forma de pagamento feita pelos clientes da plataforma às
máquinas que executam as operações solicitadas.
Gas e Gas Price
Cada transação especifica um limite de gas e gasPrice. O limite
de gas serve para protegê-lo de bugs no código que podem
ser executados até seus fundos serem esgotados.
O produto de gasPrice e gas representa o valor máximo de Wei
(ether) que você está disposto a pagar pela execução da
transação. O gasPrice também é usado pelos mineradores para
classificar as transações para inclusão na cadeia de blocos.
Solidity
Solidity é uma linguagem de alto nível orientada a contrato
cuja sintaxe é semelhante à do JavaScript e é projetada para
ser executada na Máquina Virtual Ethereum (EVM).
Solidity é estaticamente tipada, suporta herança, bibliotecas e
tipos complexos definidos pelo usuário e outros recursos.
Geth
“geth” é a interface de linha de
comando para executar um full node
de Ethereum, implementada em Go.
● Download geth: Link
● Documentação geth: Link
Clique aqui para baixar outros clientes
Ethereum (Python, C++, Rust, Java)
Navegue, controle suas contas, tokens
e use Ðapps na rede Ethereum.
Download Mist: Link
Mist
Solidity IDE
● Remix - Solidity IDE (remix.ethereum.org)
Simple Storage
pragma solidity ^0.4.13;
contract SimpleStorage {
uint storedData;
function set(uint x) {
storedData = x;
}
function get() constant returns (uint) {
return storedData;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
Simple Token
Simple Token
pragma solidity ^0.4.13;
contract MyToken {
mapping (address => uint256) public balanceOf;
}
1
2
3
4
5
Simple Token
pragma solidity ^0.4.13;
contract MyToken {
mapping (address => uint256) public balanceOf;
function MyToken() {
balanceOf[msg.sender] = 21000000;
}
}
1
2
3
4
5
6
7
8
9
Simple Token
pragma solidity ^0.4.13;
contract MyToken {
mapping (address => uint256) public balanceOf;
function MyToken(uint256 initialSupply) {
balanceOf[msg.sender] = initialSupply;
}
}
1
2
3
4
5
6
7
8
9
Simple Token
pragma solidity ^0.4.13;
contract MyToken {
mapping (address => uint256) public balanceOf;
function MyToken(uint256 initialSupply) {
balanceOf[msg.sender] = initialSupply;
}
function transfer(address _to, uint256 _value) {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Simple Tokenpragma solidity ^0.4.13;
contract MyToken {
mapping (address => uint256) public balanceOf;
string public name;
string public symbol;
uint8 public decimals;
function MyToken(uint256 initialSupply, string name, string symbol, uint8 decimalUnits) {
balanceOf[msg.sender] = initialSupply;
name = name;
symbol = symbol;
decimals = decimalUnits;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) revert();
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Simple Tokenpragma solidity ^0.4.13;
contract MyToken {
event Transfer(address indexed from, address indexed to, uint256 value);
mapping (address => uint256) public balanceOf;
string public name;
string public symbol;
uint8 public decimals;
function MyToken(uint256 initialSupply, string name, string symbol, uint8 decimalUnits) {
balanceOf[msg.sender] = initialSupply;
name = name;
symbol = symbol;
decimals = decimalUnits;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) revert();
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Improved Token
(but not so much)
github.com/aferreira44/smart-contracts-examples
Repositório Público

Workshop: Ethereum e Smart contracts

  • 1.
    Workshop: Ethereum e Smart Contracts AndréFerreira ● twitter.com/aferreira44 ● linkedin.com/in/aferreira44 ● facebook.com/aferreira44 E-mail: contato@andreferreira.me
  • 2.
    Ethereum Ethereum é umaplataforma descentralizada que executa contratos inteligentes: aplicativos que funcionam exatamente como programado sem qualquer possibilidade de tempo de inatividade, censura, fraude ou interferência de terceiros.
  • 3.
    Smart Contract Um contratointeligente (“smart contract”) é um trecho de código, com suas funções e dados, que reside em um endereço específico na cadeia de blocos do Ethereum e executa obrigações contratuais automaticamente.
  • 4.
    Ether Ether é umelemento necessário - um combustível - para operar a plataforma de aplicação distribuída do Ethereum. É uma forma de pagamento feita pelos clientes da plataforma às máquinas que executam as operações solicitadas.
  • 5.
    Gas e GasPrice Cada transação especifica um limite de gas e gasPrice. O limite de gas serve para protegê-lo de bugs no código que podem ser executados até seus fundos serem esgotados. O produto de gasPrice e gas representa o valor máximo de Wei (ether) que você está disposto a pagar pela execução da transação. O gasPrice também é usado pelos mineradores para classificar as transações para inclusão na cadeia de blocos.
  • 6.
    Solidity Solidity é umalinguagem de alto nível orientada a contrato cuja sintaxe é semelhante à do JavaScript e é projetada para ser executada na Máquina Virtual Ethereum (EVM). Solidity é estaticamente tipada, suporta herança, bibliotecas e tipos complexos definidos pelo usuário e outros recursos.
  • 7.
    Geth “geth” é ainterface de linha de comando para executar um full node de Ethereum, implementada em Go. ● Download geth: Link ● Documentação geth: Link Clique aqui para baixar outros clientes Ethereum (Python, C++, Rust, Java) Navegue, controle suas contas, tokens e use Ðapps na rede Ethereum. Download Mist: Link Mist
  • 8.
    Solidity IDE ● Remix- Solidity IDE (remix.ethereum.org)
  • 9.
    Simple Storage pragma solidity^0.4.13; contract SimpleStorage { uint storedData; function set(uint x) { storedData = x; } function get() constant returns (uint) { return storedData; } } 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 10.
  • 11.
    Simple Token pragma solidity^0.4.13; contract MyToken { mapping (address => uint256) public balanceOf; } 1 2 3 4 5
  • 12.
    Simple Token pragma solidity^0.4.13; contract MyToken { mapping (address => uint256) public balanceOf; function MyToken() { balanceOf[msg.sender] = 21000000; } } 1 2 3 4 5 6 7 8 9
  • 13.
    Simple Token pragma solidity^0.4.13; contract MyToken { mapping (address => uint256) public balanceOf; function MyToken(uint256 initialSupply) { balanceOf[msg.sender] = initialSupply; } } 1 2 3 4 5 6 7 8 9
  • 14.
    Simple Token pragma solidity^0.4.13; contract MyToken { mapping (address => uint256) public balanceOf; function MyToken(uint256 initialSupply) { balanceOf[msg.sender] = initialSupply; } function transfer(address _to, uint256 _value) { balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 15.
    Simple Tokenpragma solidity^0.4.13; contract MyToken { mapping (address => uint256) public balanceOf; string public name; string public symbol; uint8 public decimals; function MyToken(uint256 initialSupply, string name, string symbol, uint8 decimalUnits) { balanceOf[msg.sender] = initialSupply; name = name; symbol = symbol; decimals = decimalUnits; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) revert(); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 16.
    Simple Tokenpragma solidity^0.4.13; contract MyToken { event Transfer(address indexed from, address indexed to, uint256 value); mapping (address => uint256) public balanceOf; string public name; string public symbol; uint8 public decimals; function MyToken(uint256 initialSupply, string name, string symbol, uint8 decimalUnits) { balanceOf[msg.sender] = initialSupply; name = name; symbol = symbol; decimals = decimalUnits; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) revert(); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  • 17.
  • 18.

Notas do Editor

  • #5 Também funciona como incentivo para que os desenvolvedores escrevam aplicativos de qualidade (o desperdício de código é custoso) e que a rede permaneça saudável (as pessoas são compensadas pelos recursos contribuídos).
  • #10 You can think of it as a single slot in a database that can be queried and altered by calling functions of the code that manages the database. In the case of Ethereum, this is always the owning contract. This contract does not do much yet (due to the infrastructure built by Ethereum) apart from allowing anyone to store a single number that is accessible by anyone in the world without a (feasible) way to prevent you from publishing this number. Of course, anyone could just call set again with a different value and overwrite your number, but the number will still be stored in the history of the blockchain. Line 1: Tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality Line 3: Declares a state variable called storedData of type "uint" (unsigned integer of 256 bits) Line 5-11: And in this case, the functions set and get can be used to modify or retrieve the value of the variable. Line 11: To access a state variable, you do not need the prefix this. as is common in other languages.To access a state variable, you do not need the prefix this. as is common in other languages.
  • #12 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.
  • #13 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.
  • #14 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.
  • #15 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.
  • #16 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.
  • #17 The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair. Linha 4: Declares a state variable of type address that is publicly accessible. The keyword publicautomatically generates a function that allows you to access the current value of the state variable. Without this keyword, other contracts have no way to access the variable.The function will look something like this: function minter() returns (address) { return minter; } Linha 5: creates a public state variable, but it is a more complex datatype. The type maps addresses to unsigned integers Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros. This analogy does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping, nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced data type) what you added to the mapping or use it in a context where this is not needed, like this one. The getter function created by the publickeyword is a bit more complex in this case. It roughly looks like the following: function balances(address _account) returns (uint) { return balances[_account]; } As you see, you can use this function to easily query the balance of a single account. Linha 7: declares a so-called “event” which is fired in the last line of the function send. Linha 9: is the constructor which is run during creation of the contract and cannot be called afterwards. It permanently stores the address of the person creating the contract: msg (together with tx and block) is a magic global variable that contains some properties which allow access to the blockchain. msg.sender is always the address where the current (external) function call came from.