SlideShare a Scribd company logo
Ethereum Developers
Community
Learning Solidity
Arnold Pham
Lunyr Inc.
https://www.linkedin.com/in/arnoldpham/
Unless otherwise stated, these slides are licensed under the Creative Commons Attribution-
NonCommercial 3.0 License (https://creativecommons.org/licenses/by-nc/3.0/us/)
How to compile
• Use Browser-Solidity
• Use geth console
Basic Features (similar to Java, Javascript, Python)
• Comments
• Primitive Types
• Strings
• Arrays
• Statements
• Boolean, Conditional, and Arithmetic Expressions
• Loops
• Variables
• Literals
• Methods
Version Pragma
• Annotates source files with a prerequisite
• Comes from semantic versioning which is widely used in the JavaScript
community (https://docs.npmjs.com/misc/semver)
^pragma solidity ^0.4.0 means >= compiler version 0.4.0 but <0.5.0
Comments
Use // or /*...*/
pragma solidity ^0.4.0;
/*
Multisignature Wallet for requiring multiple owners to approve a transaction
*/
contract MultiSigWallet{
address[] public owners;
uint public required; // the number of owner approval required
}
Natspec documentation
Produced as an object when you call a contract object from eth.compile.solidity(source)
Contract objects have the following properties
• code
• info
• source
• language
• languageVersion
• compilerVersion
• abiDefinition
• userDoc
• the Natspec Doc for users
• developerDoc
• the Natspec Doc for developers
Natspec
@title: This is a title that should describe the contract and go above the contract
definition
@author: The name of the author of the contract. Should also go above the
contract definition.
@notice: Represents user documentation. This is the text that will appear to the
user to notify him of what the function he is about to execute is doing
@dev: Represents developer documentation. This is documentation that would
only be visible to the developer.
@param: Documents a parameter just like in doxygen. Has to be followed by the
parameter name.
@return: Documents the return type of a contract's function.
Structs
• Advantageous for describing a set of variables that will be repeatedly used to
describe something
• Defines a new type
• Cheaper to use than abstract contracts which require paying gas for contract
creation
Structs example
Imagine you have a contract that registers people, and will do that repeatedly
struct Person{
string name;
uint birthdate;
enum gender;
}
mapping (uint => Person) people;
uint personID;
Conditional Expressions
Uses control structures that are typical in other languages
1. if
2. else
3. while
4. do
5. for
6. break
7. continue
8. return
9. ? :
Warning with loops
Operations cost gas so it is best to construct loops to repeat a known number of
times if possible
Boolean Expressions
Widely used for throw, which reverses all side effects
function transfer(address _to, uint256 _value) returns (bool) {
var senderBalance = balances[msg.sender];
if (senderBalance >= _value && _value > 0) {
senderBalance -= _value;
balances[msg.sender] = senderBalance;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
Variables
State and local variables are in storage by default
contract Products {
mapping (address->uint) owned
}
Mappings
Only allowed for state variables
Mappings can be seen as hashtables which are virtually initialized such that
every possible key exists and is mapped to a value
Global variables
1. msg.sender
a. the address of the sender in the current call
2. msg.value
a. the amount of wei sent with the message
3. now
a. the current unix timestamp in seconds
Visibility for functions and state variables
• Public
• can be called either internally or from messages
• default for functions
• Private
• can only be called from the contract that it is defined in and not from
derived contracts
• Internal
• can be called from the contract it is defined in or in derived contracts
• default for state variables
• External
• can only be called from other contracts and via transactions
• cannot be called internally
Inheritance
• For contracts inheriting from multiple other contracts, only a single contract is
created on the blockchain
• The code from the base contracts is copied into the final contract
Use “is” to inherit from another contract
Multiple inheritance is possible
“super”
• Use “super” to call the next position in line in the inheritance hierarchy
• If Base1 calls a function of super, then it will call it on Base2 rather than on
Base1
destinationAddress.send or Currentaddress.balance
Use destinationAddress.send to send wei to a destination address from the
current contract
Use currentAddress.balance to check the balance of currentAddress
Bytes32
• Each bytes32 can store up to 32 letters (ASCII): each character is a byte.
• The EVM has a word-size of 32 bytes, so it is "optimized" for dealing with data
in chunks of 32 bytes. (Compilers, such as Solidity, have to do more work and
generate more bytecode when data isn't in chunks of 32 bytes, which
effectively leads to higher gas cost.)
Gas costs
• ~20,000 gas when a value is set to non-zero from zero
• ~5,000 gas when writing to existing storage or setting a value to zero
• ~15,000 gas refund when a non-zero value is set to zero.
Function modifiers
modifier onlyOwner() {
if (msg.sender != owner) throw;
_
}
Constructor Functions
Called once during contract creation
Calling a method from another contract
Either import the contract or use an abstract contract/interface
Example Code

More Related Content

What's hot

Contract Practice with Remix
Contract Practice with RemixContract Practice with Remix
Contract Practice with Remix
KC Tam
 
Smart contracts
Smart contractsSmart contracts
Smart contracts
Philippe Camacho, Ph.D.
 
Ethereum (Blockchain Network)
Ethereum (Blockchain Network)Ethereum (Blockchain Network)
Ethereum (Blockchain Network)
Qais Ammari
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial EN
Nicholas Lin
 
Programming smart contracts in solidity
Programming smart contracts in solidityProgramming smart contracts in solidity
Programming smart contracts in solidity
Emanuel Mota
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token Contract
KC Tam
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
Murughan Palaniachari
 
Ethereum 2.0
Ethereum 2.0Ethereum 2.0
Ethereum 2.0
Gene Leybzon
 
Write Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on EthereumWrite Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on Ethereum
劉 維仁
 
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
Simplilearn
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
Techracers
 
Consensus Algorithms.pptx
Consensus Algorithms.pptxConsensus Algorithms.pptx
Consensus Algorithms.pptx
Rajapriya82
 
Blockchain 101 by imran bashir
Blockchain 101  by imran bashirBlockchain 101  by imran bashir
Blockchain 101 by imran bashir
Imran Bashir
 
Introduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart ContractIntroduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart Contract
Thanh Nguyen
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
Saad Zaher
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshell
Daniel Chan
 
Attacks on Smart Contracts
Attacks on Smart ContractsAttacks on Smart Contracts
Attacks on Smart Contracts
Marcin Majchrzak
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
Zied GUESMI
 
Smart contract
Smart contractSmart contract
Smart contract
Akhmad Daniel Sembiring
 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.js
Felix Crisan
 

What's hot (20)

Contract Practice with Remix
Contract Practice with RemixContract Practice with Remix
Contract Practice with Remix
 
Smart contracts
Smart contractsSmart contracts
Smart contracts
 
Ethereum (Blockchain Network)
Ethereum (Blockchain Network)Ethereum (Blockchain Network)
Ethereum (Blockchain Network)
 
Solidity Simple Tutorial EN
Solidity Simple Tutorial ENSolidity Simple Tutorial EN
Solidity Simple Tutorial EN
 
Programming smart contracts in solidity
Programming smart contracts in solidityProgramming smart contracts in solidity
Programming smart contracts in solidity
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token Contract
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
 
Ethereum 2.0
Ethereum 2.0Ethereum 2.0
Ethereum 2.0
 
Write Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on EthereumWrite Smart Contract with Solidity on Ethereum
Write Smart Contract with Solidity on Ethereum
 
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
What is A Smart Contract? | Smart Contracts Tutorial | Smart Contracts in Blo...
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
 
Consensus Algorithms.pptx
Consensus Algorithms.pptxConsensus Algorithms.pptx
Consensus Algorithms.pptx
 
Blockchain 101 by imran bashir
Blockchain 101  by imran bashirBlockchain 101  by imran bashir
Blockchain 101 by imran bashir
 
Introduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart ContractIntroduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart Contract
 
Introduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart ContractsIntroduction to Blockchain and Smart Contracts
Introduction to Blockchain and Smart Contracts
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshell
 
Attacks on Smart Contracts
Attacks on Smart ContractsAttacks on Smart Contracts
Attacks on Smart Contracts
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
 
Smart contract
Smart contractSmart contract
Smart contract
 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.js
 

Viewers also liked

Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to Ethereum
Arnold Pham
 
The Ethereum Geth Client
The Ethereum Geth ClientThe Ethereum Geth Client
The Ethereum Geth Client
Arnold Pham
 
Ethereum Smart Contract Tutorial
Ethereum Smart Contract TutorialEthereum Smart Contract Tutorial
Ethereum Smart Contract Tutorial
Arnold Pham
 
Mist and parity
Mist and parityMist and parity
Mist and parity
Arnold Pham
 
A tour of ethereum ecosystem
A tour of ethereum ecosystemA tour of ethereum ecosystem
A tour of ethereum ecosystem
Chang-Wu Chen
 
Smart contracts & dApps
Smart contracts & dAppsSmart contracts & dApps
Smart contracts & dApps
Shermin Voshmgir
 
Blockchain &amp; the Future of Democracy
Blockchain &amp; the Future of DemocracyBlockchain &amp; the Future of Democracy
Blockchain &amp; the Future of Democracy
Shermin Voshmgir
 
History of Distributed Computing
History of Distributed ComputingHistory of Distributed Computing
History of Distributed Computing
Shermin Voshmgir
 
Ethereum @ descon 2016
Ethereum @ descon 2016Ethereum @ descon 2016
Ethereum @ descon 2016
Predrag Radović
 
Dapps for Web Developers Aberdeen Techmeetup
Dapps for Web Developers Aberdeen TechmeetupDapps for Web Developers Aberdeen Techmeetup
Dapps for Web Developers Aberdeen Techmeetup
James Littlejohn
 
Etherem ~ agvm
Etherem ~ agvmEtherem ~ agvm
Etherem ~ agvmgha sshee
 
日本のIT市場のトピックス
日本のIT市場のトピックス日本のIT市場のトピックス
日本のIT市場のトピックス
Hiroyasu NOHATA
 
Etherisc Versicherung neu erfinden
Etherisc Versicherung neu erfindenEtherisc Versicherung neu erfinden
Etherisc Versicherung neu erfinden
Stephan Karpischek
 
Vision for a health blockchain
Vision for a health blockchainVision for a health blockchain
Vision for a health blockchain
James Littlejohn
 
Introduction to Idea
Introduction to IdeaIntroduction to Idea
Introduction to Idea
James Littlejohn
 
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter..."Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
Khaled Ben Driss
 
Solidity intro
Solidity introSolidity intro
Solidity intro
Angello Pozo
 
The Ethereum ÐApp IDE: Mix
The Ethereum ÐApp IDE: MixThe Ethereum ÐApp IDE: Mix
The Ethereum ÐApp IDE: Mix
gavofyork
 
NodeJS Blockchain.info Wallet
NodeJS Blockchain.info WalletNodeJS Blockchain.info Wallet
NodeJS Blockchain.info Wallet
Sjors Provoost
 
Ingredients for creating dapps
Ingredients for creating dappsIngredients for creating dapps
Ingredients for creating dapps
Stefaan Ponnet
 

Viewers also liked (20)

Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to Ethereum
 
The Ethereum Geth Client
The Ethereum Geth ClientThe Ethereum Geth Client
The Ethereum Geth Client
 
Ethereum Smart Contract Tutorial
Ethereum Smart Contract TutorialEthereum Smart Contract Tutorial
Ethereum Smart Contract Tutorial
 
Mist and parity
Mist and parityMist and parity
Mist and parity
 
A tour of ethereum ecosystem
A tour of ethereum ecosystemA tour of ethereum ecosystem
A tour of ethereum ecosystem
 
Smart contracts & dApps
Smart contracts & dAppsSmart contracts & dApps
Smart contracts & dApps
 
Blockchain &amp; the Future of Democracy
Blockchain &amp; the Future of DemocracyBlockchain &amp; the Future of Democracy
Blockchain &amp; the Future of Democracy
 
History of Distributed Computing
History of Distributed ComputingHistory of Distributed Computing
History of Distributed Computing
 
Ethereum @ descon 2016
Ethereum @ descon 2016Ethereum @ descon 2016
Ethereum @ descon 2016
 
Dapps for Web Developers Aberdeen Techmeetup
Dapps for Web Developers Aberdeen TechmeetupDapps for Web Developers Aberdeen Techmeetup
Dapps for Web Developers Aberdeen Techmeetup
 
Etherem ~ agvm
Etherem ~ agvmEtherem ~ agvm
Etherem ~ agvm
 
日本のIT市場のトピックス
日本のIT市場のトピックス日本のIT市場のトピックス
日本のIT市場のトピックス
 
Etherisc Versicherung neu erfinden
Etherisc Versicherung neu erfindenEtherisc Versicherung neu erfinden
Etherisc Versicherung neu erfinden
 
Vision for a health blockchain
Vision for a health blockchainVision for a health blockchain
Vision for a health blockchain
 
Introduction to Idea
Introduction to IdeaIntroduction to Idea
Introduction to Idea
 
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter..."Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
"Performance Analysis of In-Network Caching in Content-Centric Advanced Meter...
 
Solidity intro
Solidity introSolidity intro
Solidity intro
 
The Ethereum ÐApp IDE: Mix
The Ethereum ÐApp IDE: MixThe Ethereum ÐApp IDE: Mix
The Ethereum ÐApp IDE: Mix
 
NodeJS Blockchain.info Wallet
NodeJS Blockchain.info WalletNodeJS Blockchain.info Wallet
NodeJS Blockchain.info Wallet
 
Ingredients for creating dapps
Ingredients for creating dappsIngredients for creating dapps
Ingredients for creating dapps
 

Similar to Learning Solidity

Ethereum
EthereumEthereum
Ethereum
V C
 
How to Start Building in Web3 – Smart Contract Design & Development Part 1
How to Start Building in Web3 – Smart Contract Design & Development Part 1How to Start Building in Web3 – Smart Contract Design & Development Part 1
How to Start Building in Web3 – Smart Contract Design & Development Part 1
Zeeve
 
solidity programming.pptx
solidity programming.pptxsolidity programming.pptx
solidity programming.pptx
RohiniBagul4
 
Advanced Qtp Book
Advanced Qtp BookAdvanced Qtp Book
Advanced Qtp Book
G.C Reddy
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
aprilyyy
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
Koen Metsu
 
VB Script Overview
VB Script OverviewVB Script Overview
VB Script Overview
Praveen Gorantla
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
Rainer Stropek
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.gerrell
 
Ecma script
Ecma scriptEcma script
Ecma script
MOHIT KUMAR
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
Ethereum.pptx
Ethereum.pptxEthereum.pptx
Ethereum.pptx
INAMULLAH699891
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kimkimberly_Bm10203
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
Nitin Aggarwal
 
Kotlin programming language
Kotlin programming languageKotlin programming language
Kotlin programming language
DSCMESCOE
 
Ethereum
EthereumEthereum
Ethereum
Brian Yap
 
Advanced+qtp+open+order
Advanced+qtp+open+orderAdvanced+qtp+open+order
Advanced+qtp+open+orderRamu Palanki
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 

Similar to Learning Solidity (20)

Ethereum
EthereumEthereum
Ethereum
 
How to Start Building in Web3 – Smart Contract Design & Development Part 1
How to Start Building in Web3 – Smart Contract Design & Development Part 1How to Start Building in Web3 – Smart Contract Design & Development Part 1
How to Start Building in Web3 – Smart Contract Design & Development Part 1
 
solidity programming.pptx
solidity programming.pptxsolidity programming.pptx
solidity programming.pptx
 
Advanced Qtp Book
Advanced Qtp BookAdvanced Qtp Book
Advanced Qtp Book
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
My final requirement
My final requirementMy final requirement
My final requirement
 
VB Script Overview
VB Script OverviewVB Script Overview
VB Script Overview
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
Ecma script
Ecma scriptEcma script
Ecma script
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Ethereum.pptx
Ethereum.pptxEthereum.pptx
Ethereum.pptx
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
Kotlin programming language
Kotlin programming languageKotlin programming language
Kotlin programming language
 
Ethereum
EthereumEthereum
Ethereum
 
Advanced+qtp+open+order
Advanced+qtp+open+orderAdvanced+qtp+open+order
Advanced+qtp+open+order
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 

Recently uploaded

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 

Recently uploaded (20)

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 

Learning Solidity

  • 1. Ethereum Developers Community Learning Solidity Arnold Pham Lunyr Inc. https://www.linkedin.com/in/arnoldpham/ Unless otherwise stated, these slides are licensed under the Creative Commons Attribution- NonCommercial 3.0 License (https://creativecommons.org/licenses/by-nc/3.0/us/)
  • 2. How to compile • Use Browser-Solidity • Use geth console
  • 3.
  • 4. Basic Features (similar to Java, Javascript, Python) • Comments • Primitive Types • Strings • Arrays • Statements • Boolean, Conditional, and Arithmetic Expressions • Loops • Variables • Literals • Methods
  • 5. Version Pragma • Annotates source files with a prerequisite • Comes from semantic versioning which is widely used in the JavaScript community (https://docs.npmjs.com/misc/semver) ^pragma solidity ^0.4.0 means >= compiler version 0.4.0 but <0.5.0
  • 6. Comments Use // or /*...*/ pragma solidity ^0.4.0; /* Multisignature Wallet for requiring multiple owners to approve a transaction */ contract MultiSigWallet{ address[] public owners; uint public required; // the number of owner approval required }
  • 7. Natspec documentation Produced as an object when you call a contract object from eth.compile.solidity(source) Contract objects have the following properties • code • info • source • language • languageVersion • compilerVersion • abiDefinition • userDoc • the Natspec Doc for users • developerDoc • the Natspec Doc for developers
  • 8. Natspec @title: This is a title that should describe the contract and go above the contract definition @author: The name of the author of the contract. Should also go above the contract definition. @notice: Represents user documentation. This is the text that will appear to the user to notify him of what the function he is about to execute is doing @dev: Represents developer documentation. This is documentation that would only be visible to the developer. @param: Documents a parameter just like in doxygen. Has to be followed by the parameter name. @return: Documents the return type of a contract's function.
  • 9. Structs • Advantageous for describing a set of variables that will be repeatedly used to describe something • Defines a new type • Cheaper to use than abstract contracts which require paying gas for contract creation
  • 10. Structs example Imagine you have a contract that registers people, and will do that repeatedly struct Person{ string name; uint birthdate; enum gender; } mapping (uint => Person) people; uint personID;
  • 11. Conditional Expressions Uses control structures that are typical in other languages 1. if 2. else 3. while 4. do 5. for 6. break 7. continue 8. return 9. ? :
  • 12. Warning with loops Operations cost gas so it is best to construct loops to repeat a known number of times if possible
  • 13. Boolean Expressions Widely used for throw, which reverses all side effects function transfer(address _to, uint256 _value) returns (bool) { var senderBalance = balances[msg.sender]; if (senderBalance >= _value && _value > 0) { senderBalance -= _value; balances[msg.sender] = senderBalance; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } return false; }
  • 14. Variables State and local variables are in storage by default contract Products { mapping (address->uint) owned }
  • 15. Mappings Only allowed for state variables Mappings can be seen as hashtables which are virtually initialized such that every possible key exists and is mapped to a value
  • 16. Global variables 1. msg.sender a. the address of the sender in the current call 2. msg.value a. the amount of wei sent with the message 3. now a. the current unix timestamp in seconds
  • 17. Visibility for functions and state variables • Public • can be called either internally or from messages • default for functions • Private • can only be called from the contract that it is defined in and not from derived contracts • Internal • can be called from the contract it is defined in or in derived contracts • default for state variables • External • can only be called from other contracts and via transactions • cannot be called internally
  • 18. Inheritance • For contracts inheriting from multiple other contracts, only a single contract is created on the blockchain • The code from the base contracts is copied into the final contract
  • 19. Use “is” to inherit from another contract
  • 21. “super” • Use “super” to call the next position in line in the inheritance hierarchy • If Base1 calls a function of super, then it will call it on Base2 rather than on Base1
  • 22. destinationAddress.send or Currentaddress.balance Use destinationAddress.send to send wei to a destination address from the current contract Use currentAddress.balance to check the balance of currentAddress
  • 23. Bytes32 • Each bytes32 can store up to 32 letters (ASCII): each character is a byte. • The EVM has a word-size of 32 bytes, so it is "optimized" for dealing with data in chunks of 32 bytes. (Compilers, such as Solidity, have to do more work and generate more bytecode when data isn't in chunks of 32 bytes, which effectively leads to higher gas cost.)
  • 24. Gas costs • ~20,000 gas when a value is set to non-zero from zero • ~5,000 gas when writing to existing storage or setting a value to zero • ~15,000 gas refund when a non-zero value is set to zero.
  • 25. Function modifiers modifier onlyOwner() { if (msg.sender != owner) throw; _ }
  • 26. Constructor Functions Called once during contract creation
  • 27. Calling a method from another contract Either import the contract or use an abstract contract/interface

Editor's Notes

  1. Solidity is a statically typed language. The type of every variable must be specified at compile-time
  2. Allows changes that do not modify the left-most non-zero digit
  3. http://ethereum.stackexchange.com/questions/8615/child-contract-vs-struct Under most circumstances, data structures, even complicated ones, should be structs. Here are some reasons to choose structs: Contracts are more expensive. You'll have to pay for the contract's creation initially, and every time you access it, you'll need to pay for a call to another contracts. This is much, much more expensive than a sha3 for a lookup inside the contract's own storage. Contracts must replicate code. Every contract must contain the logic for setting and altering values, which you must pay for in gas. A struct needs only set of functions. Contracts are exposed. Anyone can send a message to a contract. If you use a contract for storing data structures, you'll have to manage access manually. Libraries might be what you're actually looking for. If you find yourself looking for functions on a data structure (i.e. foo.bar()), you can use a library contract to do it without the additional complexity of creating contracts for every instance. Here are some reasons where contracts would be superior: Contracts can be polymorphic. A contract could potentially contain arbitrary code. This allows multiple types to be intermingled, or even to have users bring their own logic. The logic will be split. In this registrar contract each Deed could have been a struct. By making Deeds their own contracts, there is less of an attack surface for the Deeds themselves, reducing the chance of another TheDAO-scale disaster. Contracts are exposed. If users have to configure their data structures, having a unique address they can interface with directly may prove simpler. Contracts are contracts. A child contract can do anything a contract can do. If the data structures, for some reason, would own things as an address would, then having a contract would be far superior. A contract can directly hold Ether, as opposed to a struct sharing the main contract's balance with other structs. However, these are less common. My advice: try it with structs first, and use data structure contracts as a last resort.
  4. Solidity is a statically typed language. The type of every variable must be specified at compile-time
  5. you can check the