Piyawad Kasabai
Smart Contract on Blockchain
Dr.Piyawad Kasabaipiyawad.k (at) udru.ac.thhttps://github.com/piyk
Piyawad Kasabai
Outline
● Ethereum○ Components○ Ether unit names○ Wallet
● Ethereum Accounts● Ethereum Tokens● Building a Smart Contract with Solidity● Deploy Smart Contract on Testnet (Kovan Network)
Piyawad Kasabai
Ethereum
● Ethereum is often described as "the world computer.” ● Ethereum is an open source, globally decentralized computing
infrastructure that executes programs called smart contracts. ● Ethereum uses a blockchain to synchronize and store the system’s
state changes, along with a cryptocurrency called ether to meter and constrain execution resource costs.
● In December 2013, Vitalik Buterin started sharing a whitepaper that outlined the idea behind Ethereum: a Turing-complete, general-purpose blockchain.
Piyawad Kasabai
Ethereum’s Components● P2P network: runs on the Ethereum network, which is addressable on TCP port 30303, and runs a
protocol called DEVp2p.
● Consensus rules
● Transactions: transactions are network messages that include (among other things) a sender,
recipient, value, and data payload.
● State machine: Ethereum state transitions are processed by the Ethereum Virtual Machine (EVM). EVM
programs, called "smart contracts," are written in high-level languages (e.g., Solidity) and compiled
to bytecode for execution on the EVM.
● Data structures: Ethereum’s state is stored locally on each node as a database (usually Google’s
LevelDB)
● Consensus algorithm: Ethereum 1.0 PoW is used, and 2.0 PoS will be used, codenamed Casper
● Clients: Ethereum has several interoperable implementations of the client software
Piyawad Kasabai
Ether denominations and unit namesValue (in wei) Exponent Common name SI name
1 1 wei Wei
1,000 103 Babbage Kilowei or femtoether
1,000,000 106 Lovelace Megawei or picoether
1,000,000,000 109 Shannon Gigawei or nanoether
1,000,000,000,000 1012 Szabo Microether or micro
1,000,000,000,000,000 1015 Finney Milliether or milli
1,000,000,000,000,000,000 1018 Ether Ether
1,000,000,000,000,000,000,000 1021 Grand Kiloether
1,000,000,000,000,000,000,000,000 1024 Megaether
Piyawad Kasabai
Choosing an Ethereum Wallet● MetaMask a browser extension wallet that runs in your browser (Chrome, Firefox, Opera, or Brave
Browser). It is easy to use and convenient for testing, as it is able to connect to a variety of
Ethereum nodes and test blockchains. MetaMask is a web-based wallet that also includes mobile
apps for both iOS and Android.
● Jaxx a multiplatform and multicurrency wallet that runs on a variety of operating systems, including
Android, iOS, Windows, macOS, and Linux. It is often a good choice for new users as it is designed
for simplicity and ease of use. Jaxx is either a mobile or a desktop wallet, depending on where you
install it.
● MyEtherWallet (MEW) is primarily a web-based wallet that runs in any browser. It is also available on
Android and iOS. It has multiple sophisticated features we will explore in many of our examples.
Piyawad Kasabai
Ethereum Accounts
There are two different types of accounts in Ethereum: externally owned
accounts (EOAs) and contract accounts.
● EOAs are controlled by users, often via software such as a wallet
application that is external to the Ethereum platform.
● Contract accounts are controlled by program code (also commonly
referred to as “smart contracts”) that is executed by the Ethereum
Virtual Machine.
Piyawad Kasabai
Ethereum Tokens
● ERC-20 Fungible Token Standard is the most widely used and most general token standard that ‘provides basic functionality to transfer tokens, as well as allows tokens to be approved so they can be spent by another on-chain third party.
● ERC-721 Non-Fungible Token Standard concerns tokens where each token is distinct (aka non-fungible) and thus enables the tracking of distinguishable assets.
● ERC-1155 Multi Token Standard allows for the management of any combination of fungible and non-fungible tokens in a single contract, including transferring multiple token types at once.
Piyawad Kasabai
How Tokens Are Used
● Currency A token can serve as a form of currency, with a value determined through private trade.● Resource A token can represent a resource earned or produced in a sharing economy or resource-sharing
environment; for example, a storage or CPU token representing resources that can be shared over a network.● Asset A token can represent ownership of an intrinsic or extrinsic, tangible or intangible asset; for example,
gold, real estate, a car, oil, energy, MMOG items, etc.● Access A token can represent access rights and grant access to a digital or physical property, such as a
discussion forum, an exclusive website, a hotel room, or a rental car.● Equity A token can represent shareholder equity in a digital organization (e.g., a DAO) or legal entity (e.g., a
corporation).● Voting A token can represent voting rights in a digital or legal system.● Collectible A token can represent a digital collectible (e.g., CryptoPunks) or physical collectible (e.g., a painting).● Identity A token can represent a digital identity (e.g., avatar) or legal identity (e.g., national ID).● Utility A token can be used to access or pay for a service.
Piyawad Kasabai
ERC20 interface specification looks like in Solidity:contract ERC20 { function totalSupply() constant returns (uint theTotalSupply); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value);}
Piyawad Kasabai
ERC721 contract interface specification is:
interface ERC721 /* is ERC165 */ { event Transfer(address indexed _from, address indexed _to, uint256 _deedId); event Approval(address indexed _owner, address indexed _approved, uint256 _deedId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256 _balance); function ownerOf(uint256 _deedId) external view returns (address _owner); function transfer(address _to, uint256 _deedId) external payable; function transferFrom(address _from, address _to, uint256 _deedId) external payable; function approve(address _approved, uint256 _deedId) external payable; function setApprovalForAll(address _operator, boolean _approved) payable; function supportsInterface(bytes4 interfaceID) external view returns (bool);}
Piyawad Kasabai
Initial Coin Offering (ICO)
If a company is selling tokens for an ICO, they can approve a crowdsale contract
address to distribute a certain amount of tokens. The crowdsale contract can then
transferFrom the token contract owner’s balance to each buyer of the token
Piyawad Kasabai
Ethereum High-Level Languages● LLL A functional (declarative) programming language, with Lisp-like syntax. It was the first high-level
language for Ethereum smart contracts but is rarely used today.● Serpent A procedural (imperative) programming language with a syntax similar to Python. Can also
be used to write functional (declarative) code, though it is not entirely free of side effects.● Solidity A procedural (imperative) programming language with a syntax similar to JavaScript, C++, or
Java. The most popular and frequently used language for Ethereum smart contracts.● Vyper A more recently developed language, similar to Serpent and again with Python-like syntax.
Intended to get closer to a pure-functional Python-like language than Serpent, but not to replace Serpent.
● Bamboo A newly developed language, influenced by Erlang, with explicit state transitions and without iterative flows (loops). Intended to reduce side effects and increase auditability. Very new and yet to be widely adopted.
Piyawad Kasabai
Building a Smart Contract with Solidity
Ethereum IDE
https://remix.ethereum.org
Piyawad Kasabai
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/** * @title Storage * @dev Store & retrieve value in a variable */contract Storage {
uint256 number;
/** * @dev Store value in variable * @param num value to store */ function store(uint256 num) public { number = num; }
/** * @dev Return value * @return value of 'number' */ function retrieve() public view returns (uint256){ return number; }}
Store value
Piyawad Kasabai
pragma solidity >=0.7.0 <0.9.0;
/** * @title Owner * @dev Set & change owner */contract Owner {
address private owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } /** * @dev Set contract deployer as owner */ constructor() { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); }
/** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; }
/** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; }}
Change Owner
Piyawad Kasabai
pragma solidity >=0.7.0 <0.9.0;
contract Voting{ struct Candidate{ uint id; string name; uint voteCount; } mapping (uint => Candidate) public candidates; uint public candidatecount; mapping (address => bool) public citizen; constructor(){ addCandidate("Lisa"); addCandidate("Jennie"); addCandidate("Jisoo"); addCandidate("Rose"); } function addCandidate(string memory _name) private{ candidatecount++; candidates[candidatecount] = Candidate(candidatecount, _name, 0); } function vote(uint _candidateid) public{ require(!citizen[msg.sender]); citizen[msg.sender] = true; candidates[_candidateid].voteCount ++; }}
Voting
Piyawad Kasabai
pragma solidity ^0.5.0;//import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/*** @title Supply Chain* @author Alberto Cuesta Canada* @notice Implements a basic compositional supply chain contract.*/contract SupplyChain { // using SafeMath for uint256; event StepCreated(uint256 step); /** * @notice Supply chain step data. By chaining these and not * allowing them to be modified afterwards we create an Acyclic * Directed Graph. * @dev The step id is not stored in the Step itself because it * is always previously available to whoever looks for the step. * @param creator The creator of this step. * @param item The id of the object that this step refers to. * @param precedents The step ids preceding this one in the * supply chain. */ struct Step { address creator; uint256 item; uint256[] precedents; } /** * @notice All steps are accessible through a mapping keyed by * the step ids. Recursive structs are not supported in solidity. */ mapping(uint256 => Step) public steps; /** * @notice Step counter */ uint256 public totalSteps; /** * @notice Mapping from item id to the last step in the lifecycle * of that item. */
Supply Chain
Source:https://medium.com/hackernoon/implementing-a-supply-chain-in-the-ethereum-blockchain-dcc91ea718ab
Piyawad Kasabai
mapping(uint256 => uint256) public lastSteps;
function newStep(uint256 _item, uint256[] memory _precedents) public returns(uint256) { for (uint i = 0; i < _precedents.length; i++){ require( isLastStep(_precedents[i]), "Append only on last steps." ); } bool repeatInstance = false; for (uint i = 0; i < _precedents.length; i++){ if (steps[_precedents[i]].item == _item) { repeatInstance = true; break; } } if (!repeatInstance){ require(lastSteps[_item] == 0, "Instance not valid."); } steps[totalSteps] = Step( msg.sender, _item, _precedents ); uint256 step = totalSteps; totalSteps += 1; lastSteps[_item] = step; emit StepCreated(step); return step; }
function isLastStep(uint256 _step) public view returns(bool) { return lastSteps[steps[_step].item] == _step; } /** * @notice A method to retrieve the precedents of a step. * @param _step The step id of the step to retrieve precedents * for. * @return An array with the step ids of the precedent steps. */ function getprecedents(uint256 _step) public view returns(uint256[] memory) { return steps[_step].precedents; }}
Supply Chain (cont.)
Source:https://medium.com/hackernoon/implementing-a-supply-chain-in-the-ethereum-blockchain-dcc91ea718ab
Piyawad Kasabai
Deploy Smart Contract on Testnet (Kovan Network)
● Install MetaMask on chrome browserhttps://metamask.io/download.html
● Get ethereum testnet (Kovan Network) faucethttps://ethdrop.dev
● Remix IDE (Injected Web3)https://remix.ethereum.org
● Example of Contracthttps://kovan.etherscan.io/address/0x8fcb0d24d034ca948411256894073cfe39826639
Piyawad Kasabai
Create your own COIN (ERC-20)
Piyawad Kasabai
ERC-20 Fungible Token
● fungible token used for identical entities for creating coins (example
Tether, USDC and DAI), ICO (Initial Coin Offering)
● Code Example:
https://github.com/piyk/smartcontract/blob/main/MyCOIN.sol
Piyawad Kasabai
Create your own NFT (ERC-721)
Piyawad Kasabai
ERC-721
● non-fungible token (NFT) is unique token that cannot be replaced and
have a different value from other tokens that are part of the same
smart contract.
● Code Example:
https://github.com/piyk/smartcontract/blob/main/MyNFT.sol
Piyawad Kasabai
Q/A
Piyawad Kasabai
Ref.
● Andreas Antonopoulos. “Mastering Ethereum”, O’REILLY, second
edition, 2019
● https://eprint.iacr.org/2017/375.pdf
● https://github.com/ethereumbook/ethereumbook
● https://remix.ethereum.org/
● https://github.com/ethereum/solidity