0% found this document useful (0 votes)
24 views90 pages

Solidity - Basics+ganache

The document provides an overview of smart contracts and Solidity programming, detailing the fundamentals of blockchain technology, Ethereum accounts, and the structure and functionality of smart contracts. It covers essential topics such as gas costs, programming languages for smart contracts, and tools for development and deployment. Additionally, it outlines the development workflow for creating, funding, and interacting with smart contracts.

Uploaded by

tempmail16364
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views90 pages

Solidity - Basics+ganache

The document provides an overview of smart contracts and Solidity programming, detailing the fundamentals of blockchain technology, Ethereum accounts, and the structure and functionality of smart contracts. It covers essential topics such as gas costs, programming languages for smart contracts, and tools for development and deployment. Additionally, it outlines the development workflow for creating, funding, and interacting with smart contracts.

Uploaded by

tempmail16364
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

Smart Contracts and Solidity Basics

Prof. (Dr.) Neeraj Kumar

1
Prerequisite
• Blockchain
• Ethereum
• Smart contracts
Blockchain
Fully Distributed Database like BTC
Advantages:
• Highly Secure
• Transparent
• Immutable

Disadvantages:
• Scaling
• Performance
Summarizing
Blockchain
• It is a decentralized distributed ledger (data structure) where data is being
stored inside blocks in form of transactions.
• Remove the dependency on the trusted third party for recording the data in
Blocks.
• Since each block is built on top of previous Block immutability has been
achieved.
• Very difficult to add a fake block & very easy to detect the fake Block.
• Every participants of the Blockchain contain the almost same copy of the
Blockchain.
Blockchain Main
Themes
• Longitudinal immutability
• Reliable timestamps
• Cryptographic security
• Fully distributed replication
• Publicly verifiable code governing all transactions
• Value in Smart Contract Assets
Accounts and Wallets in
Accounts:
Ethereum
• Two Kinds:
 External Owned Accounts - (EOA, most common account)
 Contract Accounts
• Consist of a public/private keypair
• Allow for interaction with the blockchain
Wallets:
• A set of one or more external accounts
• Used to store/transfer ether
What is a Smart
Contract
• Smart contract is a term used to describe computer program code that
is capable of facilitating, executing, and enforcing the negotiation or
performance of an agreement (i.e. contract) using blockchain
technology.
• The entire process is automated can act as a complement, or substitute,
for legal contracts, where the terms of the smart contract are recorded
in a computer language as a set of instructions.
Smart Contracts
• Executable code
• Turing Complete
• Function like an external account
 Hold funds
 Can interact with other accounts and smart contracts
 Contain code
• Can be called through transactions
Code
Execution
• Every node contains a virtual machine (similar to Java)
 Called the Ethereum Virtual Machine (EVM)
 Compiles code from high-level language to bytecode
 Executes smart contract code and broadcasts state
• Every full-node on the blockchain processes every
transaction and stores the entire state
Gas Cost
• Gas Price: current market price of a unit of Gas (in Wei)
 Check gas price here: https://ethgasstation.info/
 Is always set before a transaction by user
• Gas Limit: maximum amount of Gas user is willing to spend
• Helps to regulate load on network
• Gas Cost (used when sending transactions) is calculated by
gasLimit*gasPrice.
 All blocks have a Gas Limit (maximum Gas each block can use)

Campbell R. Harvey 2018


Smart Contract Programming

• Solidity (javascript based), most popular


 Not yet as functional as other, more mature, programming
languages
• Serpent (python based)
• LLL (lisp based)
Smart Contract Programming

Atom Ethereum interface - Plugin for the Atom editor that features
syntax highlighting, compilation and a runtime environment (requires
backend node).
Atom Solidity Linter - Plugin for the Atom editor that provides Solidity
linting.

Vim Solidity - Plugin for the Vim editor providing syntax highlighting.
Vim Syntastic - Plugin for the Vim editor providing compile checking.
B. Smart Contract Programming
• Solidity (javascript based), most popular
 Not yet as functional as other, more mature, programming
languages
• Serpent (python based)
• LLL (lisp based)

Campbell R. Harvey 2018


B. Smart Contract Programming
Solidity
Solidity is a language similar to JavaScript which allows you to develop contracts and compile to EVM
bytecode. It is currently the flagship language of Ethereum and the most popular.
• Solidity Documentation - Solidity is the flagship Ethereum high level language that is used to
write contracts.
• Solidity online realtime compiler

Serpent
Serpent is a language similar to Python which can be used to develop contracts and compile to EVM
bytecode. It is intended to be maximally clean and simple, combining many of the efficiency benefits of
a low-level language with ease-of-use in programming style, and at the same time adding special
domain-specific features for contract programming. Serpent is compiled using LLL.
• Serpent on the ethereum wiki
• Serpent EVM compiler

Campbell R. Harvey 2018


B. Smart Contract Programming

Atom Ethereum interface - Plugin for the Atom editor that features
syntax highlighting, compilation and a runtime environment (requires
backend node).
Atom Solidity Linter - Plugin for the Atom editor that provides Solidity
linting.

Vim Solidity - Plugin for the Vim editor providing syntax highlighting.
Vim Syntastic - Plugin for the Vim editor providing compile checking.

Campbell R. Harvey 2018


B. Smart Contract Programming:
Solidity
contract Example {

uint value;

function setValue(uint pValue) {


value = pValue;
}

function getValue() returns (uint) {


return value;
}

Campbell R. Harvey 2018


B. Smart Contract Programming:
Solidity
var logIncrement =
OtherExample.LogIncrement({sender: userAddress,
uint value});

logIncrement.watch(function(err, result) {
// do something with result
})

Campbell R. Harvey 2018


Remix IDE
Remix IDE
Smart contract compilation
Smart contract compilation
• Contract bytecode is readable in public form
• Contract doesn't have to be public
• Bytecode is immutable
• ABI act as a bridge between application and smart contract
• ABI and bytecode can’t be generated without source code
Mainnet vs Testnet
Mainnet Testnet
Used for actual transaction with Used for testing smart contracts
value and decentralized applications
Mainnet’s network ID is 1 Testnets have network IDs of 3,
4, and 42
Example- Ethereum Example- Rinkeby test networks
Metamask
• MetaMask is a lightweight Chrome browser-based
extension that helps in interacting with Ethereum
networks.
• It is also a wallet that helps in sending and receiving
Ether.
• It does not download the entire chaindata locally
• It is a function to inject a javascript library called
web3.js into the namespace of each page your browser
loads.
Metamask installation

Install from here


Metamask installation

Account
address

Account
balance
Testnet (Rinkeby) faucet
• ETH on testnet has no real value; therefore we get testnet ETH from
faucet
• Example, Rinkeby faucet, Ropsten faucet
Rinkeby faucet
About solidity
• High level statically typed programming language
• With solidity you can create contracts for uses such as voting, blind
auction, crowdfunding, and multi-signature wallets
• Case sensitive
• Latest updates are available on solidity documentation
Variables in solidity
• A variable is basically a placeholder for data which can be manipulated at
runtime.
• Synatax:

• A variable can be of three types


1. State variables
2. Local variables
3. Global variables
State variable in solidity
• Permanently stored in contract storage
• Not declared in functions
• Cost gas (expensive)
• Storage not dynamically allowed
• Instance of the contract cannot have other state variable
besides these already declared
Local variable in solidity
• Variables whose values are present till function is
executing
• Declared inside functions and are kept on stack, not on storage
• Don’t cost gas
• There are some types that reference the storage by default
Local vs. state variable
Solidity variable names
• You should not use any of the Solidity reserved
keywords as a variable name. These keywords are
mentioned in the next section. For example, break or
boolean variable names are not valid.
• Solidity variable names should not start with a numeral
(0-9). They must begin with a letter or an underscore
character. For example, 123test is an invalid variable
name but _123test is a valid one
• Solidity variable names are case-sensitive. For example,
Name and name are two different variables.
Solidity-Access modifiers
Access Modifiers are the keywords used to specify the declared
accessibility of a function or a type. There are four access modifiers
available in Solidity.
• Public − Public state variables can be accessed internally as well as via
messages. For a public state variable, an automatic getter function is
generated.
• Internal − Internal state variables can be accessed only internally from
the current contract or contract deriving from it without using this.
• Private − Private state variables can be accessed only internally from
the current contract they are defined not in the derived contract from it.
• External - The External element can’t be inherited but it can be
accessed by external elements. Current contract instance can’t access
external element, it can be accessed externally only.
Example
Functions in solidity
• A function is a group of reusable code which can be
called anywhere in your program
• Syntax:

• Example:
Solidity- View vs Pure functions
• View function can be declared view in which case they
promise not to modify the state. they can view the state
variable but can't modify it

• Pure function declares that no state variable will be


changed or read

• Both of these don't cost any gas to call if they're called


externally from outside the contract (but they do cost
gas if called internally by another function).
Functions-Start
Coding
• Setter and Getter: Set and get the information.

Variable

Getter function

Setter function
Compile the
Contract
• Compile tab: Start to compile button
Set Deployment
Parameters (1/2)
• Run tab: Environment = JavaScript VM
Set Deployment
Parameters (2/2)
• JavaScript VM: All the transactions will be executed in a sandbox blockchain in the
browser. Nothing will be persisted and a page reload will restart a new blockchain
from scratch, the old one will not be saved.
• Injected Provider: Remix will connect to an injected web3 provider. Mist and
Metamask are example of providers that inject web3, thus they can be used with
this option.
• Web3 Provider: Remix will connect to a remote node. You will need to provide
the URL address to the selected provider: geth, parity or any Ethereum client.

• Gas Limit: The maximum amount of gas that can be set for all the instructions of a
contract.
• Value: Input some ether with the next created transaction (wei = 10-18 of ether).
Deploy the Contract on the Private
• Run tab: Deploy button
Blockchain of Remix
Interact with the
Contract
• Setter = Red Button: Creates transaction
• Getter= Blue Button: Just gives information

Press getBalance to see the initial amount 1

Input a value and press deposit button


2
to create and confirm the transaction

Press getBalance again to see the result 3


Constructor function in solidity
• Executed only once
• You can create only one constructor and this is optimal
• A default constructor is created by the compiler if there is no explicit
defined constructor
• A constructor can be either public or internal
• After a constructor code executed, the final code is
deployed to blockchain.
Construc
tor
• Will be called at the creation of the instance of the contract

We want to save
the address of the
contract creator
A sample program
Solidity- View vs Pure functions
Example
Solidity- View vs Pure functions
Example
Receive ether (Payable
function)
• Transfer money to the contract

Payable keyword
allows receiving
ether

Hidden Code:
Address(this).balance += msg.value; We can get the
balance of the
contract 19
Receive ether
Input the value as wei
1
(10-18 of ether)

Click the receiveDeposit button to


2
transfer the money to the
contract
Contract balance update
Withdraw
funds
• Modifier: Conditions you want to
test in other functions
• First the modifier will execute, then
the invoked function

Only the contract’s creator is


permitted to withdraw

Transfer some money from the


contract’s balance to the owner
Mappings in solidity
• Mappings in solidity acts like a hash table or dictionary in other
languages
• Store data in form of a key value pair
• Mostly used to associate the Ethereum address with associated value
type
• Syntax:
Example-Mappings
Now deploying a smart
contract on an
external
Tools blockchain
Remix Ganache MyEtherWallet Geth
Activities
1 Configuring the Blockchain - - - +
Not
2 Deploying the Blockchain Persisten + - +
t

3 Developing the contract + - - +


4 Compiling the contract + - - +
5 Creating user account + + + +
6 Deploying the contract + - + +

7 Creating the UI for + - + +


interacting
8 Run the client + - + +

9 Interact with the contract & + - + +


have fun
10 Monitoring the execution - + - +
Run
Ganache
MyEtherWallet
• add your custom network that you want to test your contracts on
Import your RPC server address and the port
number from Ganache to MyEtherWallet
MyEtherWal
let
• Contracts tab: Deploy Contract
Rem
ixType your contract and compile it

Remix
Click on Details Button: access ByteCode to import it to
MyEtherWallet
Ganache
Access your private key for signing your contract in
MyEtherWallet.
MyEtherWal
let
1.Paste the
contract’s
ByteCode from
Remix

2.Gas Limit
will
automaticall
y be
calculated

3.Paste your
private key
from Ganache
31
MyEtherWal
let on Sign Transaction button to deploy
Click
your contract

32
Ganache
You can see now you have one transaction for your
address and your balance has been changed because
of the amount of gas you paid for creating the
contract.
Interacting with the smart
contract
Extract the contract address Extract the ABI (Application Binary
from Ganache Interface) of the code from Remix

Interact with the contract in MyEtherWallet


(Import the contract address and the ABI into the MyEtherWallet)

Select a function Write Pay some gas

Read
Generate the transaction

Receive the result


Ganac
he
Transactions tab: Copy the created
contract address

35
Rem
ix
Copy the ABI
(ABI is the interface that tells MyEtherWallet how to
interact with the contract)
MyEtherWallet
Contracts tab:
Interact with Contract = Paste the contract address
from Ganache and the ABI from Remix
MyEtherWallet
You now can interact with the contract by selecting a
function and invoking it
MyEtherWal
let
If you select the getValue function you will
receive the value without paying any gas
(There is no operation cost for getting
information)
MyEtherWallet
If you choose a function that updates the state of
the contract, you will need to pay gas for it in a
transaction.
C. Development Workflow
Testing Cycle

Create Fund Develop Compile Sign & Interact &


Account Account Deploy Test

● Onboard Additional Users


● Create New Accounts
● Develop New Applications

Campbell R. Harvey 2018


C. Development Workflow: Create
Account
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• Programmatically: Go, Python, C++, JavaScript, Haskell


• Tools
 MyEtherWallet.com
 MetaMask
 TestRPC
 Many other websites
Campbell R. Harvey 2018
C. Development Workflow: Fund
Account
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• From friends
• Faucet
• Exchanges (for public blockchain)

Campbell R. Harvey 2018


C. Development Workflow: Develop
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• Ethereum Application Components:


 Base application: can be developed in any
language
 Smart contract: developed in Solidity or one of
the other contract compatible languages
 Connector library: facilitates communication
between base application and smart contracts
(Metamask) Campbell R. Harvey 2018
C. Development Workflow: Sign and
Deploy
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

Sig Deploy Live


Transactio n Signed
n tx Smart
Contract
Bytecodes Connector*

rary that facilitates communication and connection with Blockchain; Connects yo


Campbell R. Harvey 2018
C. Development Workflow: TestRPC
Create Fund Develop Compile Sign & Interact
Account Account Deploy &
Test

TestRPC/TestChain
• Local development or Test Blockchain
• https://github.com/ethereumjs/testrpc

Campbell R. Harvey 2018


Create Custom Ethereum
Blockchain
• Instead of using Ganache with its default properties for private
blockchain you can run your own blockchain
• Install Geth: One of the implementations of Ethereum written
in Go
• Create the genesis block
• Create storage of the blockchain
• Deploy blockchain nodes
• Connect MyEtherWallet to your blockchain to interact with it
Geth
help
Genesis
block
• The first block in the chain and a json file that stores the configuration
of the chain

• Create and store the file as genesis.json


Create the storage of the
blockchain
• Go to the directory of the genesis.json file
• Specify directory of your blockchain
• Create the storage from the genesis block

Folder name of your


blockchain
Inside the Blockchain
Folder
• geth folder: Store your database
• keystore: Store your Ethereum accounts
Start the Ethereum
peer node
• Start the blockchain

• Networkid provides privacy for your network.


• Other peers joining your network must use the same networkid.
Blockchain
started
• Type
admin.nodeInfo
to get the
information
about your
current node
Create an
account
• Type personal.newAccount to create as many accounts as you need

• See the created account(s)


Minin
g
• Type miner.start() to start mining

• Type miner.stop() to stop mining

You might also like