SlideShare a Scribd company logo
ethereum
smart contract
林修平
online compiler
• online compiler :
https://ethereum.github.io/browser-solidity/
MANUAL COMPILE(using geth)
• connect to console
• set up a chain
• connect to main chain:go-ethereum/build/bin/geth console
• connect to testnet:go-ethereum/build/bin/geth --testnet console
• build a private net:go-ethereum/build/bin/geth --datadir “your_directory"
--rpc --rpcport port --rpccorsdomain "*" --port "30303" --nodiscover --
ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi
"db,eth,net,web3" --autodag --networkid number --nat "any" console
MANUAL COMPILE(using geth)
• in console
• var contractABI = web3.eth.contract([{contractABI}]);
• var contract123 = contractABI.new(
parameters,
{from: address,
data: bytecode,
gas: gas
}, callback_function)
Quick Intro
• price unit:ether
• address:you can withdraw from or save ether to it.
• it can represent an user account
• no code
• or represent a contract
• tied with a code
• NOTE: same code on different address is different contract
• transaction:
• send ether
• or to execute function in a contract
• or both
Quick Intro
• contract: comprised of state and function
• state: used by user to keep information regarding the contract
• function: change state of a contract
• NOTE: Ethereum discourage users from using state to preserve information, so it cost a lot of gas to either
create or change the state.
• WHY? Since every node(miner) needs to keep a full copy of the blockchain, they have to be compensated
for storage cost of every contract.
• gas
• every function comprised of many operations and there’s a price to every type of operation
• there’s a fixed amount of gas cost to function you design and you have to pay for it when you want to execute a
function
• you can decide how much ether you want to pay per gas and that becomes transaction fee needed for this
execution
Quick Intro
• If you are on a public chain, every storage cost matters.
• But what if you are on a private chain?
• you can have ether as many as you want so you don’t need to
worry about transaction fee
• but does it mean that you can use as many storage as you want?
• YES! but still, the costs of storing these states are to be
taken by all nodes in your private chain
Quick Intro
How it work
• state
• function:operate on states
• design logic:use functions
to make your contract work
How it work
How it work
contract Count123{
uint counts(0);
function incre(){
counts = count + 1;
}
}
Transaction(Deploy)
How it work
contract Count123{
uint counts(0);
function incre(){
counts = count + 1;
}
}
How it work
Transaction(Invoke)
Count123.incre()
contract Count123{
uint counts(0);
function incre(){
counts = count + 1;
}
}
let’s take slock.it for example and write a simple bike renting contract!
slock.it
How it work
state declaration
state declaration
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
…
}
• type , visibility , variable_name
state declaration
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
…
}
• type , visibility , variable_name
• type : bool, int, uint, address, mapping, bytes, string, struct
• visibility : public or private(default)
• public: accessible externally
(declare in your contract) uint public totalCount = 3;
(access in a console) mycontract.totalCount(); //3
(access from other contract) thatcontract.totalCount() //3
• variable_name
state declaration
• Array in solidity :
• address[] owners; address[3] threeOwners;
• push item into array: owners.push(address)
• delete item: delete owners[2]
• pitfall: only changes the value of specified item to zero
instead of erase the item
state declaration
• mapping :
• mapping(typeA => typeB) variable_name;
• example
• declare a mapping:
• mapping(address => uint) deposits;
• map address 0x123456789abcdef to integer 10:
• deposits[0x123456789abcdef] = 10;
• uninitialized or undeclared values are zero instead of NULL
• NOTE: there’s no NULL in Solidity
state declaration
• Units and Globally available variables
• Ether unit:ether、finney、wei
• time unit:seconds、weeks、years、now
• now: present time
• more specifically, the time when this block is mined, i.e,
the time_stamp parameter in the block header
state declaration
• Special variables and functions
• msg: information regarding this transaction
• msg.sender: address who send the transaction
• msg.value: value sent with the transaction
• address related functions
• address.balance
• address.send(amount):send ether to address
state declaration
• Special variables and functions
• throw
• reverts all changes made so far by the underlying transaction
• confiscate all gas provided by underlying transaction
state declaration
initialization
initialization
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
uint public unitPrice;
function bikeRenting(uint _unitPrice){
owner = msg.sender;
currentRenter = 0x0;
expireTime = now;
unitPrice = _unitPrice;
}
}
• constructor function
• it’s name is exactly the same as contract’s
• executed when the contract is been deployed to blockchain
• executed only once
• not necessary
initialization
function
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
uint public unitPrice;
function bikeRenting(uint _unitPrice){
…
}
function rent() payable returns(bool){
if(currentRenter != 0x0) return false;
else{
if( (msg.value/1 ether) / unitPrice < 1) return false;
else {
expireTime = now + 15 minutes * (msg.value/1 ether)/unitPrice;
currentRenter = msg.sender;
rentingRecord(msg.sender, now, (msg.value/1 ether)/unitPrice);
}
}
}
}
check if it’s been rented
how much time you get
for one unit
check if paid more than a unit price
function
how many ether per unit
function functionName(parameter1, parameter2, …) returns(type) {
…
}
• declare parameters: bool a, uint b, address c, …
• returns:
• not necessary
• function foo() returns(uint, address, bool) {
…
return (1, 0x0, true);
}
function
• visibility of a function
• public(default)
• private: only accessible by this contract
• internal: only accessible by this contract and contracts inherited from this one
• external: exactly the opposite of internal
• payable:
• decide if people can send ether while they execute this function, in other words, if you
create a transaction to execute this function, you will be able to send the transaction
along with some ether only if this function is a payable function
function
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
uint public unitPrice;
function bikeRenting(uint _unitPrice){…}
function rent() payable returns(bool){…}
function isInUse(bool ifWantToRent) payable returns(bool){
if( expireTime > now ) return true;
else{
currentRenter = 0x0;
if( ifWantToRent == true) rent();
}
}
}
this function checks if the bike is rented
ifWantToRent is a parameter sent by
person who execute this transaction,
indicating if he/she wants to rent this bike
not expired yet, it is rented
function
function
• we have to make sure person who executes isInUse function has the priority to
rent if the bike is available because he/she pays transaction fee to execute this
function
• why we need someone else to check if the bike is been rented or not?
• because a smart contract is not a robot, it won’t execute a command actively
• it won’t lock the bike itself even time is up, it needs to be triggered
• but if there are more than two people execute the same function in the
same time, there’s no guarantee on the order of the execution
• so we have to make sure person who gets to execute isInUse
function first will have the priority to rent the bike because he/she
pays for this execution
contract bikeRenting {
address public owner;
address public currentRenter;
uint public expireTime;
uint public unitPrice;
function bikeRenting(uint _unitPrice){…}
function rent() payable returns(bool){…}
function isInUse(bool ifWantToRent) payable returns(bool){…}
function collectMoney() {
if( msg.sender == owner){
owner.send(this.balance) ;
}
}
}
make sure only owner can
execute this function
function
privilege
privilege
• there’s no built-in mechanism to restrict execution privilege, you have to check if person
who executes the function has the right to
• HOW?
• using msg.sender to compare with addresses which have the right to execute
function collectMoney() {
if(msg.sender == owner){
…
}
}
repetitive actions
• modifier
• attach to modifier: function bar() foo1() {…}
• attach to multiple modifiers: function bar() foo1() foo2() foo3(){…}
repetitive actions
modifier foo1 {
do_something
_;
or_do_something_here
}
contract foo1 {
…
modifier ownerCheck { if(msg.sender == owner ) _;}
function collectMoney() ownerCheck {
owner.send(this.balance) ;
}
…
}
repetitive actions
contract modifierTest{
modifier foo1(){
foo1before;
_;
foo1after;
}
modifier foo2(){
foo2before;
_;
foo2after;
}
function bar() foo1() foo2() {
bar;
}
}
repetitive actions
execution order:
foo1before
foo2before
bar
foo2after
foo1after
contract creation in a contract
contract creation in a contract
contract foo{ … }
address newFooAddr = new foo();
• returns an address
foo foo1 = foo(newFooAddr);
• returns a contract
• NOTE: contract creation usually cost a lot of gas so remember to
supply enough gas if you execute a function which creates new
contracts
fallback function
fallback function
• it’s executed only when someone executes a function not existed in the contract or
someone simply sends some ether to this contract
• not necessary
• pitfall:
• person who owns this contract gets to decide what to do in a fallback function
• if you simply sends some ether to this contract, you also have to pay for the
execution of fallback function if there is one
function () {
…
}
pitfalls
pitfalls
• throw when address.send() fails
• throw will revert all changes and confiscate all gas even if you are
halfway there
for(uint i=0; i<investorsCount; i++) {
if( inverstors[i].send(100) == false )
throw;
}
pitfalls
• throw when address.send() fails
• why address.send() fail?
• 1. out of gas
• supply enough gas
• 2. callstack
• 1024 layer
pitfalls
• throw when address.send() fails
• mitigation: use a withdraw pattern
• still, this solution leaves the problems mentioned to the msg
sender
function withdraw(amount) {
if( balances[msg.sender] >= amount ) {
msg.sender.send(amount);
balances[msg.sender] -= amount;
}
}
pitfalls
• shared state between external call and external callable functions
function extCall() {
…
external_call();
…
if(shared_state) {
…
}
…
}
function extCallable(){
do_something_on_shared_state…
}
pitfalls
• state corruption
• 1. sum of sizes of 1st and 2nd state variables are less than 256
bytes
• 2. first variable is not a signed interger or bytesXX type
function extCall() {
uint32 a;
uint32 b;
function run() returns(uint32){
a--;
return b;
}
}
fixed after compiler version 0.4.4
Misc
• selfdestruct(recipient)
• terminate the contract, destroy code and storage, then transfer the remaining ether to
recipient
• event: writes data into transaction receipt
• example: event paymentRecord(address indexed buyer, uint value)
• indexed: write data into topics field
• if data is more than 32 bytes, hash of data is written into topics instead
• transaction receipt
• data
• topics: can be used as a condition filter
Misc
• contract inheritance : contract Final is most-base-like, …, most-derived
{…}
Misc
tips
• use delete on array to delete all elements
• --vmdebug, --verbosity
• --targetgaslimit

More Related Content

What's hot

Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
101 Blockchains
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
Murughan Palaniachari
 
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
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
Zied GUESMI
 
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
 
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
Truong Nguyen
 
Hyperledger
HyperledgerHyperledger
Hyperledger
Roshan Ranabhat
 
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
 
Hyperledger fabric architecture
Hyperledger fabric architectureHyperledger fabric architecture
Hyperledger fabric architecture
Celine George
 
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
Edureka!
 
Blockchain Digital Transformation Presentation
Blockchain Digital Transformation PresentationBlockchain Digital Transformation Presentation
Blockchain Digital Transformation Presentation
101 Blockchains
 
Ethereum 2.0
Ethereum 2.0Ethereum 2.0
Ethereum 2.0
Gene Leybzon
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshell
Daniel Chan
 
Smart contracts
Smart contractsSmart contracts
Smart contracts
Philippe Camacho, Ph.D.
 
Understanding private blockchains
Understanding private blockchainsUnderstanding private blockchains
Understanding private blockchains
Coin Sciences Ltd
 
Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum) Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum)
عطاءالمنعم اثیل شیخ
 
Ethereum
EthereumEthereum
Ethereum
Brian Yap
 
Blockchain and Smart Contracts (Series: Blockchain Basics)
Blockchain and Smart Contracts (Series: Blockchain Basics)Blockchain and Smart Contracts (Series: Blockchain Basics)
Blockchain and Smart Contracts (Series: Blockchain Basics)
Financial Poise
 
Ethereum Solidity Fundamentals
Ethereum Solidity FundamentalsEthereum Solidity Fundamentals
Ethereum Solidity Fundamentals
Eno Bassey
 
Bitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & BlockchainBitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & Blockchain
Jitendra Chittoda
 

What's hot (20)

Introduction To Solidity
Introduction To SolidityIntroduction To Solidity
Introduction To Solidity
 
Hyperledger Fabric
Hyperledger FabricHyperledger Fabric
Hyperledger Fabric
 
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...
 
Blockchain Presentation
Blockchain PresentationBlockchain Presentation
Blockchain Presentation
 
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...
 
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
 
Hyperledger
HyperledgerHyperledger
Hyperledger
 
Introduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart ContractIntroduction to Ethereum Blockchain & Smart Contract
Introduction to Ethereum Blockchain & Smart Contract
 
Hyperledger fabric architecture
Hyperledger fabric architectureHyperledger fabric architecture
Hyperledger fabric architecture
 
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
Smart Contracts Programming Tutorial | Solidity Programming Language | Solidi...
 
Blockchain Digital Transformation Presentation
Blockchain Digital Transformation PresentationBlockchain Digital Transformation Presentation
Blockchain Digital Transformation Presentation
 
Ethereum 2.0
Ethereum 2.0Ethereum 2.0
Ethereum 2.0
 
Ethereum in a nutshell
Ethereum in a nutshellEthereum in a nutshell
Ethereum in a nutshell
 
Smart contracts
Smart contractsSmart contracts
Smart contracts
 
Understanding private blockchains
Understanding private blockchainsUnderstanding private blockchains
Understanding private blockchains
 
Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum) Ethereum-Cryptocurrency (All about Ethereum)
Ethereum-Cryptocurrency (All about Ethereum)
 
Ethereum
EthereumEthereum
Ethereum
 
Blockchain and Smart Contracts (Series: Blockchain Basics)
Blockchain and Smart Contracts (Series: Blockchain Basics)Blockchain and Smart Contracts (Series: Blockchain Basics)
Blockchain and Smart Contracts (Series: Blockchain Basics)
 
Ethereum Solidity Fundamentals
Ethereum Solidity FundamentalsEthereum Solidity Fundamentals
Ethereum Solidity Fundamentals
 
Bitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & BlockchainBitcoin, Ethereum, Smart Contract & Blockchain
Bitcoin, Ethereum, Smart Contract & Blockchain
 

Viewers also liked

Intro to smart contract on blockchain en
Intro to smart contract on blockchain enIntro to smart contract on blockchain en
Intro to smart contract on blockchain en
Nicholas Lin
 
以太坊智能合約撰寫簡單教學
以太坊智能合約撰寫簡單教學以太坊智能合約撰寫簡單教學
以太坊智能合約撰寫簡單教學
Nicholas Lin
 
CopyRightContractDemo
CopyRightContractDemoCopyRightContractDemo
CopyRightContractDemo
Nicholas Lin
 
部署並執行以太坊智能合約
部署並執行以太坊智能合約部署並執行以太坊智能合約
部署並執行以太坊智能合約
Nicholas Lin
 
區塊鏈智能合約應用於點數平台之架構
區塊鏈智能合約應用於點數平台之架構區塊鏈智能合約應用於點數平台之架構
區塊鏈智能合約應用於點數平台之架構
Nicholas Lin
 
智能合約結合區塊鏈簡介
智能合約結合區塊鏈簡介智能合約結合區塊鏈簡介
智能合約結合區塊鏈簡介
Nicholas Lin
 
Ingredients for creating dapps
Ingredients for creating dappsIngredients for creating dapps
Ingredients for creating dapps
Stefaan Ponnet
 
Blockchain: The Information Technology of the Future
Blockchain: The Information Technology of the FutureBlockchain: The Information Technology of the Future
Blockchain: The Information Technology of the Future
Melanie Swan
 
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
Andris Soroka
 
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
Andris Soroka
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
Nicholas Lin
 
Etherem ~ agvm
Etherem ~ agvmEtherem ~ agvm
Etherem ~ agvmgha sshee
 
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
 
日本のIT市場のトピックス
日本のIT市場のトピックス日本のIT市場のトピックス
日本のIT市場のトピックス
Hiroyasu NOHATA
 
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
 
Etherisc Versicherung neu erfinden
Etherisc Versicherung neu erfindenEtherisc Versicherung neu erfinden
Etherisc Versicherung neu erfinden
Stephan Karpischek
 
Solidity intro
Solidity introSolidity intro
Solidity intro
Angello Pozo
 

Viewers also liked (20)

Intro to smart contract on blockchain en
Intro to smart contract on blockchain enIntro to smart contract on blockchain en
Intro to smart contract on blockchain en
 
以太坊智能合約撰寫簡單教學
以太坊智能合約撰寫簡單教學以太坊智能合約撰寫簡單教學
以太坊智能合約撰寫簡單教學
 
CopyRightContractDemo
CopyRightContractDemoCopyRightContractDemo
CopyRightContractDemo
 
部署並執行以太坊智能合約
部署並執行以太坊智能合約部署並執行以太坊智能合約
部署並執行以太坊智能合約
 
區塊鏈智能合約應用於點數平台之架構
區塊鏈智能合約應用於點數平台之架構區塊鏈智能合約應用於點數平台之架構
區塊鏈智能合約應用於點數平台之架構
 
智能合約結合區塊鏈簡介
智能合約結合區塊鏈簡介智能合約結合區塊鏈簡介
智能合約結合區塊鏈簡介
 
Ingredients for creating dapps
Ingredients for creating dappsIngredients for creating dapps
Ingredients for creating dapps
 
Blockchain: The Information Technology of the Future
Blockchain: The Information Technology of the FutureBlockchain: The Information Technology of the Future
Blockchain: The Information Technology of the Future
 
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
DSS.LV @ IBM and ALSO Tech Workshop in Riga, Latvia (May, 2016)
 
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
Zane Beļavska - LR MOD - Normatīvie akti kiberdrošībā - @ LTRK + DSS.LV = Hak...
 
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
以比特幣為例的區塊鏈技術介紹 ( Intro to Blockchain using Bitcoin as an example)
 
Etherem ~ agvm
Etherem ~ agvmEtherem ~ agvm
Etherem ~ agvm
 
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
 
日本のIT市場のトピックス
日本のIT市場のトピックス日本のIT市場のトピックス
日本のIT市場のトピックス
 
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...
 
Etherisc Versicherung neu erfinden
Etherisc Versicherung neu erfindenEtherisc Versicherung neu erfinden
Etherisc Versicherung neu erfinden
 
Solidity intro
Solidity introSolidity intro
Solidity intro
 

Similar to Solidity Simple Tutorial EN

Ethereum
EthereumEthereum
Ethereum
V C
 
Smart contract and Solidity
Smart contract and SoliditySmart contract and Solidity
Smart contract and Solidity
겨울 정
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token Contract
KC Tam
 
Smart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSmart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathon
Sittiphol Phanvilai
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
Bellaj Badr
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to Ethereum
Arnold Pham
 
“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
EIT Digital Alumni
 
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK ShyamasundarRobust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Napier University
 
Hello world contract
Hello world contractHello world contract
Hello world contract
Gene Leybzon
 
Blockchain Development
Blockchain DevelopmentBlockchain Development
Blockchain Development
preetikumara
 
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereumDappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Tomoaki Sato
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
How to Build a Telegraf Plugin by Noah Crowley
How to Build a Telegraf Plugin by Noah CrowleyHow to Build a Telegraf Plugin by Noah Crowley
How to Build a Telegraf Plugin by Noah Crowley
InfluxData
 
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxDataBuilding a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
InfluxData
 
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
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
PowerfullBoy1
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
Bo-Yi Wu
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
Jalpesh Vadgama
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
vorfeed chen
 

Similar to Solidity Simple Tutorial EN (20)

Ethereum
EthereumEthereum
Ethereum
 
Smart contract and Solidity
Smart contract and SoliditySmart contract and Solidity
Smart contract and Solidity
 
ERC20 Token Contract
ERC20 Token ContractERC20 Token Contract
ERC20 Token Contract
 
Smart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSmart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathon
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to 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
 
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK ShyamasundarRobust Programming of Smart Contracts in Solidity+, RK Shyamasundar
Robust Programming of Smart Contracts in Solidity+, RK Shyamasundar
 
Hello world contract
Hello world contractHello world contract
Hello world contract
 
Blockchain Development
Blockchain DevelopmentBlockchain Development
Blockchain Development
 
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereumDappsmedia smartcontract _write_smartcontracts_on_console_ethereum
Dappsmedia smartcontract _write_smartcontracts_on_console_ethereum
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
How to Build a Telegraf Plugin by Noah Crowley
How to Build a Telegraf Plugin by Noah CrowleyHow to Build a Telegraf Plugin by Noah Crowley
How to Build a Telegraf Plugin by Noah Crowley
 
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxDataBuilding a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
Building a Telegraf Plugin by Noah Crowly | Developer Advocate | InfluxData
 
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
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 

Solidity Simple Tutorial EN

  • 2. online compiler • online compiler : https://ethereum.github.io/browser-solidity/
  • 3. MANUAL COMPILE(using geth) • connect to console • set up a chain • connect to main chain:go-ethereum/build/bin/geth console • connect to testnet:go-ethereum/build/bin/geth --testnet console • build a private net:go-ethereum/build/bin/geth --datadir “your_directory" --rpc --rpcport port --rpccorsdomain "*" --port "30303" --nodiscover -- ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi "db,eth,net,web3" --autodag --networkid number --nat "any" console
  • 4. MANUAL COMPILE(using geth) • in console • var contractABI = web3.eth.contract([{contractABI}]); • var contract123 = contractABI.new( parameters, {from: address, data: bytecode, gas: gas }, callback_function)
  • 6. • price unit:ether • address:you can withdraw from or save ether to it. • it can represent an user account • no code • or represent a contract • tied with a code • NOTE: same code on different address is different contract • transaction: • send ether • or to execute function in a contract • or both Quick Intro
  • 7. • contract: comprised of state and function • state: used by user to keep information regarding the contract • function: change state of a contract • NOTE: Ethereum discourage users from using state to preserve information, so it cost a lot of gas to either create or change the state. • WHY? Since every node(miner) needs to keep a full copy of the blockchain, they have to be compensated for storage cost of every contract. • gas • every function comprised of many operations and there’s a price to every type of operation • there’s a fixed amount of gas cost to function you design and you have to pay for it when you want to execute a function • you can decide how much ether you want to pay per gas and that becomes transaction fee needed for this execution Quick Intro
  • 8. • If you are on a public chain, every storage cost matters. • But what if you are on a private chain? • you can have ether as many as you want so you don’t need to worry about transaction fee • but does it mean that you can use as many storage as you want? • YES! but still, the costs of storing these states are to be taken by all nodes in your private chain Quick Intro
  • 10. • state • function:operate on states • design logic:use functions to make your contract work How it work
  • 11. How it work contract Count123{ uint counts(0); function incre(){ counts = count + 1; } } Transaction(Deploy)
  • 12. How it work contract Count123{ uint counts(0); function incre(){ counts = count + 1; } }
  • 13. How it work Transaction(Invoke) Count123.incre() contract Count123{ uint counts(0); function incre(){ counts = count + 1; } }
  • 14. let’s take slock.it for example and write a simple bike renting contract! slock.it How it work
  • 16. state declaration contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; … }
  • 17. • type , visibility , variable_name state declaration contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; … }
  • 18. • type , visibility , variable_name • type : bool, int, uint, address, mapping, bytes, string, struct • visibility : public or private(default) • public: accessible externally (declare in your contract) uint public totalCount = 3; (access in a console) mycontract.totalCount(); //3 (access from other contract) thatcontract.totalCount() //3 • variable_name state declaration
  • 19. • Array in solidity : • address[] owners; address[3] threeOwners; • push item into array: owners.push(address) • delete item: delete owners[2] • pitfall: only changes the value of specified item to zero instead of erase the item state declaration
  • 20. • mapping : • mapping(typeA => typeB) variable_name; • example • declare a mapping: • mapping(address => uint) deposits; • map address 0x123456789abcdef to integer 10: • deposits[0x123456789abcdef] = 10; • uninitialized or undeclared values are zero instead of NULL • NOTE: there’s no NULL in Solidity state declaration
  • 21. • Units and Globally available variables • Ether unit:ether、finney、wei • time unit:seconds、weeks、years、now • now: present time • more specifically, the time when this block is mined, i.e, the time_stamp parameter in the block header state declaration
  • 22. • Special variables and functions • msg: information regarding this transaction • msg.sender: address who send the transaction • msg.value: value sent with the transaction • address related functions • address.balance • address.send(amount):send ether to address state declaration
  • 23. • Special variables and functions • throw • reverts all changes made so far by the underlying transaction • confiscate all gas provided by underlying transaction state declaration
  • 25. initialization contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; uint public unitPrice; function bikeRenting(uint _unitPrice){ owner = msg.sender; currentRenter = 0x0; expireTime = now; unitPrice = _unitPrice; } }
  • 26. • constructor function • it’s name is exactly the same as contract’s • executed when the contract is been deployed to blockchain • executed only once • not necessary initialization
  • 28. contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; uint public unitPrice; function bikeRenting(uint _unitPrice){ … } function rent() payable returns(bool){ if(currentRenter != 0x0) return false; else{ if( (msg.value/1 ether) / unitPrice < 1) return false; else { expireTime = now + 15 minutes * (msg.value/1 ether)/unitPrice; currentRenter = msg.sender; rentingRecord(msg.sender, now, (msg.value/1 ether)/unitPrice); } } } } check if it’s been rented how much time you get for one unit check if paid more than a unit price function how many ether per unit
  • 29. function functionName(parameter1, parameter2, …) returns(type) { … } • declare parameters: bool a, uint b, address c, … • returns: • not necessary • function foo() returns(uint, address, bool) { … return (1, 0x0, true); } function
  • 30. • visibility of a function • public(default) • private: only accessible by this contract • internal: only accessible by this contract and contracts inherited from this one • external: exactly the opposite of internal • payable: • decide if people can send ether while they execute this function, in other words, if you create a transaction to execute this function, you will be able to send the transaction along with some ether only if this function is a payable function function
  • 31. contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; uint public unitPrice; function bikeRenting(uint _unitPrice){…} function rent() payable returns(bool){…} function isInUse(bool ifWantToRent) payable returns(bool){ if( expireTime > now ) return true; else{ currentRenter = 0x0; if( ifWantToRent == true) rent(); } } } this function checks if the bike is rented ifWantToRent is a parameter sent by person who execute this transaction, indicating if he/she wants to rent this bike not expired yet, it is rented function
  • 32. function • we have to make sure person who executes isInUse function has the priority to rent if the bike is available because he/she pays transaction fee to execute this function • why we need someone else to check if the bike is been rented or not? • because a smart contract is not a robot, it won’t execute a command actively • it won’t lock the bike itself even time is up, it needs to be triggered • but if there are more than two people execute the same function in the same time, there’s no guarantee on the order of the execution • so we have to make sure person who gets to execute isInUse function first will have the priority to rent the bike because he/she pays for this execution
  • 33. contract bikeRenting { address public owner; address public currentRenter; uint public expireTime; uint public unitPrice; function bikeRenting(uint _unitPrice){…} function rent() payable returns(bool){…} function isInUse(bool ifWantToRent) payable returns(bool){…} function collectMoney() { if( msg.sender == owner){ owner.send(this.balance) ; } } } make sure only owner can execute this function function
  • 35. privilege • there’s no built-in mechanism to restrict execution privilege, you have to check if person who executes the function has the right to • HOW? • using msg.sender to compare with addresses which have the right to execute function collectMoney() { if(msg.sender == owner){ … } }
  • 37. • modifier • attach to modifier: function bar() foo1() {…} • attach to multiple modifiers: function bar() foo1() foo2() foo3(){…} repetitive actions modifier foo1 { do_something _; or_do_something_here }
  • 38. contract foo1 { … modifier ownerCheck { if(msg.sender == owner ) _;} function collectMoney() ownerCheck { owner.send(this.balance) ; } … } repetitive actions
  • 39. contract modifierTest{ modifier foo1(){ foo1before; _; foo1after; } modifier foo2(){ foo2before; _; foo2after; } function bar() foo1() foo2() { bar; } } repetitive actions execution order: foo1before foo2before bar foo2after foo1after
  • 40. contract creation in a contract
  • 41. contract creation in a contract contract foo{ … } address newFooAddr = new foo(); • returns an address foo foo1 = foo(newFooAddr); • returns a contract • NOTE: contract creation usually cost a lot of gas so remember to supply enough gas if you execute a function which creates new contracts
  • 43. fallback function • it’s executed only when someone executes a function not existed in the contract or someone simply sends some ether to this contract • not necessary • pitfall: • person who owns this contract gets to decide what to do in a fallback function • if you simply sends some ether to this contract, you also have to pay for the execution of fallback function if there is one function () { … }
  • 45. pitfalls • throw when address.send() fails • throw will revert all changes and confiscate all gas even if you are halfway there for(uint i=0; i<investorsCount; i++) { if( inverstors[i].send(100) == false ) throw; }
  • 46. pitfalls • throw when address.send() fails • why address.send() fail? • 1. out of gas • supply enough gas • 2. callstack • 1024 layer
  • 47. pitfalls • throw when address.send() fails • mitigation: use a withdraw pattern • still, this solution leaves the problems mentioned to the msg sender function withdraw(amount) { if( balances[msg.sender] >= amount ) { msg.sender.send(amount); balances[msg.sender] -= amount; } }
  • 48. pitfalls • shared state between external call and external callable functions function extCall() { … external_call(); … if(shared_state) { … } … } function extCallable(){ do_something_on_shared_state… }
  • 49. pitfalls • state corruption • 1. sum of sizes of 1st and 2nd state variables are less than 256 bytes • 2. first variable is not a signed interger or bytesXX type function extCall() { uint32 a; uint32 b; function run() returns(uint32){ a--; return b; } } fixed after compiler version 0.4.4
  • 50. Misc • selfdestruct(recipient) • terminate the contract, destroy code and storage, then transfer the remaining ether to recipient • event: writes data into transaction receipt • example: event paymentRecord(address indexed buyer, uint value) • indexed: write data into topics field • if data is more than 32 bytes, hash of data is written into topics instead • transaction receipt • data • topics: can be used as a condition filter
  • 51. Misc
  • 52. • contract inheritance : contract Final is most-base-like, …, most-derived {…} Misc
  • 53. tips • use delete on array to delete all elements • --vmdebug, --verbosity • --targetgaslimit