Uploaded by Rohit Mahajan

Blockchain Elements Lab 2

advertisement
BLOCKCHAIN ELEMENTS
LAB 2:
INTRODUCTION
TO SOLIDITY
BLOCKCHAIN ELEMENTS LAB 2
LAB OUTLINE
1
ETHEREUM VIRTUAL MACHINE
2
SOLIDITY: OVERVIEW
3
QUICK DOCS
4
EXERCISE: SOLIDITY USING REMIX
BLOCKCHAIN ELEMENTS LAB 2
1
ETHEREUM
VIRTUAL
MACHINE
BLOCKCHAIN ELEMENTS LAB 2
THE ETHEREUM VIRTUAL MACHINE
THE WORLD COMPUTER
●
The Ethereum Virtual Machine (EVM) is a powerful software
embedded within each full Ethereum node, responsible for
executing contract bytecode.
●
It is a Turing complete software that runs on the Ethereum
network.
●
It allows anyone to run any program, given enough time and
memory, making the process of creating blockchain
applications much easier and efficient than ever before.
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE ETHEREUM VIRTUAL MACHINE
THE WORLD COMPUTER
●
Every node participating in the network runs the EVM
●
Nodes will go through the transactions listed in the block they are verifying and run
the code as triggered by the transaction within the EVM
●
Every full node does the same calculations and stores the same values
AUTHOR: NICK ZOGHB
BLOCKCHAIN ELEMENTS LAB 2
THE ETHEREUM VIRTUAL MACHINE
THE WORLD COMPUTER
● Solidity lets you program on Ethereum, and allows the
creation and execution of smart contracts, without
requiring centralized or trusted parties
● It is a statically typed, contract programming language
that has similarities to Javascript and C.
○ Some contract-specific features include
modifier (guard) clauses, event notifiers for
listeners, and custom global variables
AUTHOR: NICK ZOGHB
BLOCKCHAIN ELEMENTS LAB 2
2
SOLIDITY
OVERVIEW
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
WHAT DOES A BANK NEED TO
DO?
1.
Manage Deposits
2.
Manage Withdrawals
3.
Balance Checks
https://learnxinyminutes.com/docs/solidity/
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
●
contract has similarities to a class in other
languages (class variables, inheritance, etc.)
○
Declare state variables outside any
function, so that they persist throughout
the life of contract
●
●
mapping is a dictionary that maps addresses to balances (here)
○
always be careful about overflow attacks with numbers
○
private means that other contracts can't directly access the mapping
public makes something externally readable (not writeable) by users or
contracts
AUTHOR: COLLIN CHIN
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
●
event - Events are signals the contracts
can fire. External listeners like DApps
can listen to these events and act
accordingly.
●
constructor - When a contract is created, its
constructor is executed only once.
Constructors are optional.
●
msg - a special global variable that contains properties which allow
access to the blockchain.
○
msg.sender gives address of the message sender who made the
current function call i.e. the person/contract currently connecting
with the contract ( address of contract deployer/creator here )
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
●
deposit()
○ Takes no parameters, but we can send
Ether using the payable modifier.
○
public makes function externally
readable (not writeable) by users or
contracts
○
Returns user’s balance as an unsigned
integer (uint)
●
In balances[msg.sender], no this or self required as it is a state variable
●
LogDepositMade event is fired using emit
AUTHOR: COLLIN CHIN
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
●
Withdraw()
○
●
withdrawAmount parameter
○ Returns user’s balance
Note the way we deduct the balance
right away, before sending
○
We do this because of the risk of a recursive call that may allow the caller to
request an amount greater than their balance.
AUTHOR: COLLIN CHIN
BLOCKCHAIN ELEMENTS LAB 2
THE BANK CONTRACT
LEARNING FAST
●
balance():
○ constant prevents the function
from editing state variables, that
are stored on the blockchain.
○
Returns user’s balance as an uint.
AUTHOR: COLLIN CHIN
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THE FALLBACK FUNCTION
●
A contract can have exactly one unnamed function, which cannot have arguments and
cannot return anything.
●
It is executed on a call to the contract if none of the other functions match the given
function identifier (or if no data was supplied at all).
●
Furthermore, this function is executed whenever the contract receives plain Ether
(without data). To receive Ether and add it to the total balance of the contract, the
fallback function must be marked payable. If no such function exists, the contract cannot
receive Ether through regular transactions and throws an exception.
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
3
QUICK DOCS
BLOCKCHAIN ELEMENTS LAB 2
3.1
DATA TYPES
BLOCKCHAIN ELEMENTS LAB 2
DATA TYPES
BYTES
// Bytes are available from 1 to 32:
byte a; // byte is same as bytes1
bytes2 b;
bytes32 c;
// Dynamically sized bytes:
bytes m; // A special arrray, same as byte[] array but packed tightly.
//More expensive than bytes1,.....,bytes32, so use those when possible.
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
DATA TYPES
STRING
//
same as bytes, but does not allow length or index access
string n = "hello";
//
stored in UTF-8, note double quotes, not single
//
prefer bytes32/bytes, as UTF-8 uses more storage
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
DATA TYPES
VAR
// It is not always necessary to explicitly specify the type of a variable
// Using var, the compiler automatically infers it from the type of the first expression that is
assigned to the variable.
// var cannot be used for function parameters or return parameters.
bool x= true;
var y= x;
var z= false;
// Here the type of both y and z will be bool.
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
DATA TYPES
// Variables can be used to assign function to variable
function a(uint x) public returns (uint) {
return x * 2;
}
var f = a;
f(22); // call
// By default, all values are set to 0 on instantiation.
// Delete can be called on most types. It does NOT destroy the value, but sets it to 0,
the initial value.
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
3.2
DATA
STRUCTURES
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
ARRAYS
// Arrays
bytes32[5] nicknames; // static array
bytes32[] names; // dynamic array
uint newLength = names.push("John"); // push returns the new length of the array (Here 1)
names.length; // get length
names.length = 1; // lengths can be set (for dynamic arrays in storage only)
// multidimensional array
uint x[][5]; // arr with 5 dynamic array elements (opposite order of most languages)
AUTHOR: ALI MOUSA
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
MAPPINGS
// Dictionaries (any type to any other type)
mapping (string => uint) public balances;
balances["charles"] = 1;
console.log(balances["ada"]);
// gives 0, all non-set key values return zero
// 'public' allows access from another contract
contractName.balances("charles"); // returns 1
// 'public' created a getter (but not setter) like the following:
function balances(string _account) returns (uint balance) {
return balances[_account];
}
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
MAPPINGS
// Nested mappings
mapping (address => mapping (address => uint)) public custodians;
// To delete
delete balances["John"]; // sets corresponding element to 0
delete balances; // do not set any element to 0
// Unlike other languages, we CANNOT iterate through all elements in a
// mapping, without knowing source keys. However, we can build a data structure
// on top to do this
AUTHOR: ALI MOUSA
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
MAPPINGS
Delete has no effect on mappings as the keys of mappings may be arbitrary and are
generally unknown.
However, individual keys and what they map to can be deleted.
Eg: If ‘a’ is a mapping, then delete a[x] will delete the value stored at x.
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
STRUCTS
// Structs and enums
struct Bank {
address owner;
uint balance;
}
Bank b = Bank({
owner: msg.sender,
balance: 5
});
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
STRUCTS
// or
struct Bank {
address owner;
uint balance;
}
Bank c = Bank(msg.sender, 5);
c.balance = 9; // set to new value
delete b;
// sets to initial value, set all variables in struct to 0, exceptmappings
AUTHOR: ALI MOUSA
BLOCKCHAIN ELEMENTS LAB 2
DATA STRUCTURES
ENUMS
// Enums
enum State { Created, Locked, Inactive } // often used for state machine
State public state; // Declare variable from enum
state = State.Created;
// enums can be explicitly converted to ints
uint x = uint(State.Created); // 0
uint y = uint(State.Inactive); // 2
AUTHOR: ALI MOUSA
UPDATED BY: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
WHERE DATA GOES
NOTE ON MEMORY AND STORAGE
● Data locations:
○
memory
vs.
storage
vs. stack - all complex types (array, struct, mapping) have a data location.
does not persist,
storage
does.
● Default is
memory
storage
for local and state variables;
memory
for function arguments
○ For most types, the data location to use can be explicitly set
● The stack holds small local variables
○ Used for values in intermediate calculations
○ General consensus is not to interact with it as a developer
AUTHOR: NICK ZOGHB
BLOCKCHAIN ELEMENTS LAB 2
4
EXERCISE
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
REMIX IDE
THE WORLD ON A SINGLE WEB APP
AUTHOR: YOGESH AGARWAL
BLOCKCHAIN ELEMENTS LAB 2
THINGS TO DO
UH-OH, TIME TO WORK
We want you to flex your creative problem-solving skills in this new environment.
With a mind for clean code, use the Remix IDE to implement the following:
● A ‘greeter’ contract with a 'greet' method that returns the string “Hello World!”
○ TRY: The user should be able to change the greeting without redeploying the contract
● The Fibonacci function
○ TRY: Iteratively
AUTHOR: NICK ZOGHB
BLOCKCHAIN ELEMENTS LAB 2
THINGS TO DO
UH-OH, TIME TO WORK
● An XOR function
○ Input ‘1’ or ‘0’
○ This does not require any bitwise operations!
○ TRY: Input a string of 1's and 0's, e.g. "10001110101101"
● A method to concatenate two strings
○ Importing a module is fine
○ TRY: Do not use a module
AUTHOR: NICK ZOGHB
Download