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

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
 
Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & EthereumAkshay Singh
 
Bitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & BlockchainBitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & BlockchainJitendra Chittoda
 
Ethereum
EthereumEthereum
EthereumV C
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain PresentationZied GUESMI
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts101 Blockchains
 
Intro to Web3
Intro to Web3Intro to Web3
Intro to Web3asasdasd5
 
Decentralized applications 101: How and why to build a DApp
Decentralized applications 101: How and why to build a DAppDecentralized applications 101: How and why to build a DApp
Decentralized applications 101: How and why to build a DAppErik Trautman
 
Blockchain Smart Contract v5
Blockchain   Smart Contract v5Blockchain   Smart Contract v5
Blockchain Smart Contract v5MD SAQUIB KHAN
 
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...Melanie Swan
 
Blockchain Technology ppt project.pptx
Blockchain Technology ppt project.pptxBlockchain Technology ppt project.pptx
Blockchain Technology ppt project.pptxSahilBansal648873
 
Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity101 Blockchains
 
que es la blockchain y como funciona
que es la blockchain y como funcionaque es la blockchain y como funciona
que es la blockchain y como funcionaVic Perez
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to BlockchainMalak Abu Hammad
 
Blockchain Technology and Its Application in Libraries
Blockchain Technology and Its Application in LibrariesBlockchain Technology and Its Application in Libraries
Blockchain Technology and Its Application in LibrariesNabi Hasan
 

What's hot (20)

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...
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
 
Smart Contract & Ethereum
Smart Contract & EthereumSmart Contract & Ethereum
Smart Contract & Ethereum
 
Bitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & BlockchainBitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & Blockchain
 
Ethereum
EthereumEthereum
Ethereum
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
 
Examples of Smart Contracts
Examples of Smart ContractsExamples of Smart Contracts
Examples of Smart Contracts
 
Intro to Web3
Intro to Web3Intro to Web3
Intro to Web3
 
Decentralized applications 101: How and why to build a DApp
Decentralized applications 101: How and why to build a DAppDecentralized applications 101: How and why to build a DApp
Decentralized applications 101: How and why to build a DApp
 
Ethereum
EthereumEthereum
Ethereum
 
Blockchain
BlockchainBlockchain
Blockchain
 
Blockchain Smart Contract v5
Blockchain   Smart Contract v5Blockchain   Smart Contract v5
Blockchain Smart Contract v5
 
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...
Bitcoin Protocols 1.0 and 2.0 Explained in the Series: Blockchain: The Inform...
 
Blockchain Technology ppt project.pptx
Blockchain Technology ppt project.pptxBlockchain Technology ppt project.pptx
Blockchain Technology ppt project.pptx
 
Blockchain 2.0
Blockchain 2.0Blockchain 2.0
Blockchain 2.0
 
Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
 
que es la blockchain y como funciona
que es la blockchain y como funcionaque es la blockchain y como funciona
que es la blockchain y como funciona
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
 
Blockchain
BlockchainBlockchain
Blockchain
 
Blockchain Technology and Its Application in Libraries
Blockchain Technology and Its Application in LibrariesBlockchain Technology and Its Application in Libraries
Blockchain Technology and Its Application in Libraries
 

Similar to Programming smart contracts in solidity

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?Doug Hawkins
 
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 IoTBenjamin Cabé
 
Import golang; struct microservice
Import golang; struct microserviceImport golang; struct microservice
Import golang; struct microserviceGiulio De Donato
 
[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 맹개발 Yunho Maeng
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchainBellaj Badr
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019chayanikaa
 
“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 PandeyEIT Digital Alumni
 
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 快速搭建微服務架構應用程式實戰KAI CHU CHUNG
 
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 Conor Svensson
 
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...Flink Forward
 
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 FlinkAljoscha Krettek
 
Advanced Sockets Programming
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programmingelliando 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 BytecodeShakacon
 

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
 
Ethereum
EthereumEthereum
Ethereum
 
“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
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

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