SlideShare a Scribd company logo
1 of 44
Download to read offline
PROGRAMMING SMART CONTRACTS WITH
SOLIDITY
Navigate : Space / Arrow Keys | - Menu | - Fullscreen | - Overview | - Blackout | - Speaker | - HelpM F O B S ?

1 / 44
EMANUEL MOTA - @EMOTA7
Founder of Yari Labs
emanuel@yarilabs.com
@yarilabs
Braga Blockchain

2 / 44
ABOUT THE TALK
Intro
Ethereum Overview
Smart Contracts
Solidity Crash Course
What is an ERC20 token
ICO on Ethereum
Questions
Braga Blockchain

3 / 44
#BRAGABLOCKCHAIN
TELEGRAM -HTTP://T.ME/BRAGABLOCKCHAIN
Braga Blockchain

4 / 44
SOME STATS ABOUT THE AUDIENCE
Developers: 70% of the audience
Knowledge of Solidity programming language?
Never heard of it before - 53%
I'm a Beginner - 26%
I've tryed it a couple of times - 16%
I'm an Intermediate user - 5%
I'm a Solidity Guru - 0%
Braga Blockchain

5 / 44
Ethereum Network
“Each node of the Ethereum
network hosts a blockchain database
and a node client capable of
executing application code stored on
blockchain. Nodes communicate
through Wire protocol and expose
same interface but can be
implemented in different languages.”
Excerpt From: Roberto Infante. “Building Ethereum ÐApps”
ETHEREUM
Braga Blockchain

6 / 44
ETHEREUM
Bitcoin like distributed ledger
Cryptocurrency (Ether)
Ethereum Virtual Machine (EVM)
Turing complete
Braga Blockchain

7 / 44
ETHEREUM
Ethereum Blockchain
Contracts (code)
Storage
Logs
Events
Braga Blockchain

8 / 44
ETHEREUM
Two kinds of accounts
External Accounts (wallets controlled by humans)
Contract Accounts (controlled by code)
every account has a balance
Braga Blockchain

9 / 44
ETHEREUM
Code execution costs GAS
Transaction is a message sent from one account to
another and can have a data payload
Braga Blockchain

10 / 44
SMART CONTRACTS
Braga Blockchain

11 / 44
SMART CONTRACTS
Braga Blockchain

12 / 44
SMART CONTRACTS
Contract = code (i.e. functions) + data (i.e. state) and
resides on the blockchain
EVM is the runtime for Smart Contracts on
Ethereum
Accounts have a persistent memory area which is
called storage
Contracts can neither read nor write to any storage
apart from their own
Braga Blockchain

13 / 44
SMART CONTRACTS
Contracts can call other contracts
1024 max call stack depth
Support Events
Contracts can purge themselves from the blockchain
(OPCODE selfdestruct)
Braga Blockchain

14 / 44
SOLIDITY PROGRAMMING LANGUAGE
https://solidity.readthedocs.io/
Braga Blockchain

15 / 44
SOLIDITY
Solidity is a statically typed, contract programming
language that has similarities to Javascript, Java and C.
Braga Blockchain

16 / 44
SOLIDITY
Has some contract-speci c features like:
modi er (guard) clauses
event noti ers for listeners
custom global variables.
Braga Blockchain

17 / 44
SOLIDITY
Hello World
version pragma — declares the version of the compiler to be used to avoid breaking changes
introduced on future versions
pragma solidity ^0.4.19;
contract HelloWorld {
}
Braga Blockchain

18 / 44
SOLIDITY
Statically typed language
uint data type is an unsigned integer (non-
negative number)
int data type is used for signed integers
uint has 256 bits we can also have uint8, uint16,
uint32
contract Example {
// This will be stored permanently in the blockchain
uint myUnsignedInteger = 100;
string name;
}
Braga Blockchain

19 / 44
SOLIDITY
More complex data types - Structs
struct TokenHolder {
uint age;
string obs;
}
// Arrays
string[5] stringArray;
// a dynamic Array - has no fixed size, can keep growing:
uint[] dynamicArray;
// Public array
TokenHolder[] public shareHolders;
Braga Blockchain

20 / 44
SOLIDITY
Mappings and data type address
rst example, the key is an address and the value is a uint
second example, the key is a uint and the value is a string
// For a financial app, storing a uint that holds the user's account balance:
mapping (address => uint) public accountBalance;
// Or could be used to store / lookup usernames based on userId
mapping (uint => string) userIdToName;
Braga Blockchain

21 / 44
SOLIDITY
Function declarations
uint[] scores;
function addNewScore(string _clientId, uint _score) public {
...
_updateScores(_score);
}
function _updatesScores(string _clientId, uint _number) private {
...
scores.push(_number) {
...
}
Braga Blockchain

22 / 44
SOLIDITY
More about functions
string greeting = "Whazaaa ?";
function sayHello() public returns (string) {
return greeting;
}
Braga Blockchain

23 / 44
SOLIDITY
Function Modi ers
function sayHello() public view returns (string) {
function _multiply(uint a, uint b) private pure returns (uint) {
return a * b;
}
// Functions can return many arguments, and by specifying returned arguments
// names we don't need to explicitly return
function increment(uint x, uint y) returns (uint x, uint y) {
x += 1;
y += 1;
}
// when a function returns multiple values we need to parallel assign
(x1, y1) = increment(1,2);
Braga Blockchain

24 / 44
SOLIDITY
More on functions Modi ers
modifier onlyAfter(uint _time) { require (now >= _time); _; }
modifier onlyOwner { require(msg.sender == owner) _; }
// Append right after function declaration
function changeOwner(newOwner) onlyAfter(someTime) onlyOwner() {
owner = newOwner;
}
Braga Blockchain

25 / 44
SOLIDITY
Payable function Modi er
// All functions that receive ether must be marked 'payable'
function depositEther() public payable {
balances[msg.sender] += msg.value;
}
Braga Blockchain

26 / 44
SOLIDITY
Events
Events are a way for a contract to communicate that something happened on the blockchain
to a front-end client that is 'listening' for events
A javascript implementation would look something like:
// declare the event
event IntegersAdded(uint x, uint y, uint result);
function add(uint _x, uint _y) public returns(uint) {
uint result = _x + _y;
// fire an event to let the app know the function was called:
IntegersAdded(_x, _y, result);
return result;
}
YourContract.IntegersAdded(function(error, result) {
// do something with result
}
Braga Blockchain

27 / 44
SOLIDITY
Important global variables
this; // address of contract
this.balance; // often used at end of contract life to transfer balance
// ** msg - Current message received by the contract ** **
msg.sender; // address of sender
msg.value; // amount of eth sent to contract (in wei) function should be "payabl
msg.data; // bytes, complete call data
msg.gas; // remaining gas
now; // current time (approximately) - uses Unix time
Braga Blockchain

28 / 44
IMPORTANT DESIGN NOTES
Obfuscation: All variables are publicly viewable on
blockchain, so anything that is private needs to be
obfuscated
Storage optimization: Writing to blockchain is
expensive, as data is stored forever
Braga Blockchain

29 / 44
IMPORTANT DESIGN NOTES
Cron Job: Contracts must be manually called to
handle time-based scheduling
Cost of Gas: the fuel Ethereum DApps run on
Braga Blockchain

30 / 44
SOME USEFULL LINKS
Braga Blockchain

31 / 44
SOME USEFULL LINKS
Ethereum website
Online compiler
Another online compiler
Online tools
(block explorer, tx submit)
EthFiddle
https://www.ethereum.org/
https://remix.ethereum.org/
https://etherchain.org/solc
https://testnet.etherscan.io
https://etherscan.io
https://eth ddle.com/
Braga Blockchain

32 / 44
SOME USEFULL LINKS
(so you don’t have to run your own
node/s)
Truf e .
Embark
Open Zeppelin
https://etherchain.org/
http://infura.io
https://github.com/ConsenSys/truf e
https://github.com/iurimatias/embark-
framework
https://openzeppelin.org/
https://metamask.io/
Braga Blockchain

33 / 44
WHAT IS AN ERC20 TOKEN?
Braga Blockchain

34 / 44
ERC20 TOKEN
ERC stands for Ethereum Request for Comments
contract MyToken {
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* Initializes contract with initial supply tokens to the creator */
function MyToken(
uint256 initialSupply
) {
// Give the creator all initial tokens
balanceOf[msg.sender] = initialSupply;
}
Braga Blockchain

35 / 44
ERC20 TOKEN (CONTINUATION)
(from ethereum.org)
/* Send coins */
function transfer(address _to, uint256 _value) {
// Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
}
Braga Blockchain

36 / 44
ERC20 TOKEN
An ERC20 token implements the following API
name
symbol
decimals
transfer(to, value)
transferFrom(from, to, value)
approve(spender, value)
approveAndCall(spender, value, extraData)
burn(value)
burnFrom(from, value)
plus trigger a set of events
a complete spec of a ERC20 Token check andhttps://ethereum.org/token
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
Braga Blockchain

37 / 44
ERC20 TOKEN
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner)
public constant returns (uint balance);
function allowance(address tokenOwner, address spender)
public constant returns (uint remaining);
function transfer(address to, uint tokens)
public returns (bool success);
function approve(address spender, uint tokens)
public returns (bool success);
function transferFrom(address from, address to, uint tokens)
public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint toke
}
Braga Blockchain

38 / 44
HOW TO MAKE AN ICO (CROWDSALE)
CONTRACT
Braga Blockchain

39 / 44
WHAT REALLY IS AN ICO ?
An ICO - Initial Coin Offer should really be called:
token generation event (TGE) as ICO is a term
initially coined for currencies and now its being used
for selling ERC20 (ethereum tokens).
And ICO should be done automatically via a
SmartContract that implements the rules of the
token sale.
Braga Blockchain

40 / 44
ICO
To buy tokens from a smart contract participants
should transfer ethereum directly from their wallets to
the smart contract address so that the smartcontract
assigns them the tokens automatically.
To see an example of a crowdsale contract check:
https://ethereum.org/crowdsale
Braga Blockchain

41 / 44
NON-FUNGIBLE TOKENS ERC-721
https://www.cryptokitties.co/marketplace
https://cryptozombies.io
Braga Blockchain

42 / 44
QUESTIONS ?
EMANUEL MOTA
@YARILABS
emanuel@yarilabs.com
twitter: @emota7
github: emanuel
HTTP://YARILABS.COM
Braga Blockchain

43 / 44
HANDS ON IN THE AFTERNOON :)
Prepare your rinkeby testnet wallets!
And join BragaBlockchain telegram
Braga Blockchain

44 / 44

More Related Content

What's hot

PoW vs. PoS - Key Differences
PoW vs. PoS - Key DifferencesPoW vs. PoS - Key Differences
PoW vs. PoS - Key Differences
101 Blockchains
 
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Simplilearn
 
Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
101 Blockchains
 

What's hot (20)

Consensus Algorithms.pptx
Consensus Algorithms.pptxConsensus Algorithms.pptx
Consensus Algorithms.pptx
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
 
Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum) Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum)
 
Blockchain
BlockchainBlockchain
Blockchain
 
Introduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptxIntroduction to Solidity and Smart Contract Development (9).pptx
Introduction to Solidity and Smart Contract Development (9).pptx
 
Ethereum Blockchain with Smart contract and ERC20
Ethereum Blockchain with Smart contract and ERC20Ethereum Blockchain with Smart contract and ERC20
Ethereum Blockchain with Smart contract and ERC20
 
PoW vs. PoS - Key Differences
PoW vs. PoS - Key DifferencesPoW vs. PoS - Key Differences
PoW vs. PoS - Key Differences
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial EN
 
Smart contract
Smart contractSmart contract
Smart contract
 
Understanding Proof of Work (PoW) and Proof of Stake (PoS) Algorithms
Understanding Proof of Work (PoW) and Proof of Stake (PoS) AlgorithmsUnderstanding Proof of Work (PoW) and Proof of Stake (PoS) Algorithms
Understanding Proof of Work (PoW) and Proof of Stake (PoS) Algorithms
 
Blockchain Essentials and Blockchain on Azure
Blockchain Essentials and Blockchain on AzureBlockchain Essentials and Blockchain on Azure
Blockchain Essentials and Blockchain on Azure
 
Blockchain concepts
Blockchain conceptsBlockchain concepts
Blockchain concepts
 
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
Ethereum Tutorial - Ethereum Explained | What is Ethereum? | Ethereum Explain...
 
Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & Ethereum
 
Blockchain ecosystem and evolution
Blockchain ecosystem and evolutionBlockchain ecosystem and evolution
Blockchain ecosystem and evolution
 
Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
 
Blockchain
BlockchainBlockchain
Blockchain
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
 
Blockchain Smart Contract v5
Blockchain   Smart Contract v5Blockchain   Smart Contract v5
Blockchain Smart Contract v5
 
Blockchain basics
Blockchain basicsBlockchain basics
Blockchain basics
 

Similar to Programming smart contracts in solidity

Advanced Sockets Programming
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programming
elliando dias
 
A Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts BytecodeA Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts Bytecode
Shakacon
 

Similar to Programming smart contracts in solidity (20)

JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Devoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoTDevoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoT
 
Import golang; struct microservice
Import golang; struct microserviceImport golang; struct microservice
Import golang; struct microservice
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Hexagonal architecture
Hexagonal architectureHexagonal architecture
Hexagonal architecture
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019
 
How to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contractHow to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contract
 
“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip Pandey“Create your own cryptocurrency in an hour” - Sandip Pandey
“Create your own cryptocurrency in an hour” - Sandip Pandey
 
Build resource server & client for OCF Cloud (2018.8.30)
Build resource server & client for OCF Cloud (2018.8.30)Build resource server & client for OCF Cloud (2018.8.30)
Build resource server & client for OCF Cloud (2018.8.30)
 
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
 
Building Java and Android apps on the blockchain
Building Java and Android apps on the blockchain Building Java and Android apps on the blockchain
Building Java and Android apps on the blockchain
 
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
 
Advanced Sockets Programming
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programming
 
Verilog
VerilogVerilog
Verilog
 
A Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts BytecodeA Decompiler for Blackhain-Based Smart Contracts Bytecode
A Decompiler for Blackhain-Based Smart Contracts Bytecode
 
Programming Decentralized Application
Programming Decentralized ApplicationProgramming Decentralized Application
Programming Decentralized Application
 
OpenTelemetry Introduction
OpenTelemetry Introduction OpenTelemetry Introduction
OpenTelemetry Introduction
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Programming smart contracts in solidity

  • 1. PROGRAMMING SMART CONTRACTS WITH SOLIDITY Navigate : Space / Arrow Keys | - Menu | - Fullscreen | - Overview | - Blackout | - Speaker | - HelpM F O B S ?  1 / 44
  • 2. EMANUEL MOTA - @EMOTA7 Founder of Yari Labs emanuel@yarilabs.com @yarilabs Braga Blockchain  2 / 44
  • 3. ABOUT THE TALK Intro Ethereum Overview Smart Contracts Solidity Crash Course What is an ERC20 token ICO on Ethereum Questions Braga Blockchain  3 / 44
  • 5. SOME STATS ABOUT THE AUDIENCE Developers: 70% of the audience Knowledge of Solidity programming language? Never heard of it before - 53% I'm a Beginner - 26% I've tryed it a couple of times - 16% I'm an Intermediate user - 5% I'm a Solidity Guru - 0% Braga Blockchain  5 / 44
  • 6. Ethereum Network “Each node of the Ethereum network hosts a blockchain database and a node client capable of executing application code stored on blockchain. Nodes communicate through Wire protocol and expose same interface but can be implemented in different languages.” Excerpt From: Roberto Infante. “Building Ethereum ÐApps” ETHEREUM Braga Blockchain  6 / 44
  • 7. ETHEREUM Bitcoin like distributed ledger Cryptocurrency (Ether) Ethereum Virtual Machine (EVM) Turing complete Braga Blockchain  7 / 44
  • 9. ETHEREUM Two kinds of accounts External Accounts (wallets controlled by humans) Contract Accounts (controlled by code) every account has a balance Braga Blockchain  9 / 44
  • 10. ETHEREUM Code execution costs GAS Transaction is a message sent from one account to another and can have a data payload Braga Blockchain  10 / 44
  • 13. SMART CONTRACTS Contract = code (i.e. functions) + data (i.e. state) and resides on the blockchain EVM is the runtime for Smart Contracts on Ethereum Accounts have a persistent memory area which is called storage Contracts can neither read nor write to any storage apart from their own Braga Blockchain  13 / 44
  • 14. SMART CONTRACTS Contracts can call other contracts 1024 max call stack depth Support Events Contracts can purge themselves from the blockchain (OPCODE selfdestruct) Braga Blockchain  14 / 44
  • 16. SOLIDITY Solidity is a statically typed, contract programming language that has similarities to Javascript, Java and C. Braga Blockchain  16 / 44
  • 17. SOLIDITY Has some contract-speci c features like: modi er (guard) clauses event noti ers for listeners custom global variables. Braga Blockchain  17 / 44
  • 18. SOLIDITY Hello World version pragma — declares the version of the compiler to be used to avoid breaking changes introduced on future versions pragma solidity ^0.4.19; contract HelloWorld { } Braga Blockchain  18 / 44
  • 19. SOLIDITY Statically typed language uint data type is an unsigned integer (non- negative number) int data type is used for signed integers uint has 256 bits we can also have uint8, uint16, uint32 contract Example { // This will be stored permanently in the blockchain uint myUnsignedInteger = 100; string name; } Braga Blockchain  19 / 44
  • 20. SOLIDITY More complex data types - Structs struct TokenHolder { uint age; string obs; } // Arrays string[5] stringArray; // a dynamic Array - has no fixed size, can keep growing: uint[] dynamicArray; // Public array TokenHolder[] public shareHolders; Braga Blockchain  20 / 44
  • 21. SOLIDITY Mappings and data type address rst example, the key is an address and the value is a uint second example, the key is a uint and the value is a string // For a financial app, storing a uint that holds the user's account balance: mapping (address => uint) public accountBalance; // Or could be used to store / lookup usernames based on userId mapping (uint => string) userIdToName; Braga Blockchain  21 / 44
  • 22. SOLIDITY Function declarations uint[] scores; function addNewScore(string _clientId, uint _score) public { ... _updateScores(_score); } function _updatesScores(string _clientId, uint _number) private { ... scores.push(_number) { ... } Braga Blockchain  22 / 44
  • 23. SOLIDITY More about functions string greeting = "Whazaaa ?"; function sayHello() public returns (string) { return greeting; } Braga Blockchain  23 / 44
  • 24. SOLIDITY Function Modi ers function sayHello() public view returns (string) { function _multiply(uint a, uint b) private pure returns (uint) { return a * b; } // Functions can return many arguments, and by specifying returned arguments // names we don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { x += 1; y += 1; } // when a function returns multiple values we need to parallel assign (x1, y1) = increment(1,2); Braga Blockchain  24 / 44
  • 25. SOLIDITY More on functions Modi ers modifier onlyAfter(uint _time) { require (now >= _time); _; } modifier onlyOwner { require(msg.sender == owner) _; } // Append right after function declaration function changeOwner(newOwner) onlyAfter(someTime) onlyOwner() { owner = newOwner; } Braga Blockchain  25 / 44
  • 26. SOLIDITY Payable function Modi er // All functions that receive ether must be marked 'payable' function depositEther() public payable { balances[msg.sender] += msg.value; } Braga Blockchain  26 / 44
  • 27. SOLIDITY Events Events are a way for a contract to communicate that something happened on the blockchain to a front-end client that is 'listening' for events A javascript implementation would look something like: // declare the event event IntegersAdded(uint x, uint y, uint result); function add(uint _x, uint _y) public returns(uint) { uint result = _x + _y; // fire an event to let the app know the function was called: IntegersAdded(_x, _y, result); return result; } YourContract.IntegersAdded(function(error, result) { // do something with result } Braga Blockchain  27 / 44
  • 28. SOLIDITY Important global variables this; // address of contract this.balance; // often used at end of contract life to transfer balance // ** msg - Current message received by the contract ** ** msg.sender; // address of sender msg.value; // amount of eth sent to contract (in wei) function should be "payabl msg.data; // bytes, complete call data msg.gas; // remaining gas now; // current time (approximately) - uses Unix time Braga Blockchain  28 / 44
  • 29. IMPORTANT DESIGN NOTES Obfuscation: All variables are publicly viewable on blockchain, so anything that is private needs to be obfuscated Storage optimization: Writing to blockchain is expensive, as data is stored forever Braga Blockchain  29 / 44
  • 30. IMPORTANT DESIGN NOTES Cron Job: Contracts must be manually called to handle time-based scheduling Cost of Gas: the fuel Ethereum DApps run on Braga Blockchain  30 / 44
  • 31. SOME USEFULL LINKS Braga Blockchain  31 / 44
  • 32. SOME USEFULL LINKS Ethereum website Online compiler Another online compiler Online tools (block explorer, tx submit) EthFiddle https://www.ethereum.org/ https://remix.ethereum.org/ https://etherchain.org/solc https://testnet.etherscan.io https://etherscan.io https://eth ddle.com/ Braga Blockchain  32 / 44
  • 33. SOME USEFULL LINKS (so you don’t have to run your own node/s) Truf e . Embark Open Zeppelin https://etherchain.org/ http://infura.io https://github.com/ConsenSys/truf e https://github.com/iurimatias/embark- framework https://openzeppelin.org/ https://metamask.io/ Braga Blockchain  33 / 44
  • 34. WHAT IS AN ERC20 TOKEN? Braga Blockchain  34 / 44
  • 35. ERC20 TOKEN ERC stands for Ethereum Request for Comments contract MyToken { /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; /* Initializes contract with initial supply tokens to the creator */ function MyToken( uint256 initialSupply ) { // Give the creator all initial tokens balanceOf[msg.sender] = initialSupply; } Braga Blockchain  35 / 44
  • 36. ERC20 TOKEN (CONTINUATION) (from ethereum.org) /* Send coins */ function transfer(address _to, uint256 _value) { // Check if the sender has enough require(balanceOf[msg.sender] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } } Braga Blockchain  36 / 44
  • 37. ERC20 TOKEN An ERC20 token implements the following API name symbol decimals transfer(to, value) transferFrom(from, to, value) approve(spender, value) approveAndCall(spender, value, extraData) burn(value) burnFrom(from, value) plus trigger a set of events a complete spec of a ERC20 Token check andhttps://ethereum.org/token https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md Braga Blockchain  37 / 44
  • 38. ERC20 TOKEN contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint toke } Braga Blockchain  38 / 44
  • 39. HOW TO MAKE AN ICO (CROWDSALE) CONTRACT Braga Blockchain  39 / 44
  • 40. WHAT REALLY IS AN ICO ? An ICO - Initial Coin Offer should really be called: token generation event (TGE) as ICO is a term initially coined for currencies and now its being used for selling ERC20 (ethereum tokens). And ICO should be done automatically via a SmartContract that implements the rules of the token sale. Braga Blockchain  40 / 44
  • 41. ICO To buy tokens from a smart contract participants should transfer ethereum directly from their wallets to the smart contract address so that the smartcontract assigns them the tokens automatically. To see an example of a crowdsale contract check: https://ethereum.org/crowdsale Braga Blockchain  41 / 44
  • 43. QUESTIONS ? EMANUEL MOTA @YARILABS emanuel@yarilabs.com twitter: @emota7 github: emanuel HTTP://YARILABS.COM Braga Blockchain  43 / 44
  • 44. HANDS ON IN THE AFTERNOON :) Prepare your rinkeby testnet wallets! And join BragaBlockchain telegram Braga Blockchain  44 / 44