Module 5
Module 5
Understand Ethereum
Define Smart Contracts
Identify Cryptocurrency used in Ethereum
Describe Transactions in Ethereum
Define Consensus Mechanism in Ethereum
List Development Technologies
Identify Ethereum Clients
Define Platform Functions
Understand Solidity
Describe Solidity Operators and Functions
“
© Copyright, Intellipaat Software Solutions Pvt. Ltd. All rights reserved.
Ethereum
“
complete language that allows the development of
smart contracts for Blockchain and decentralized
applications.
Bitcoin Ethereum
“
contracts”. Let’s understand what smart
contracts are.
An option contract between parties A triggering event like an Regulators can use the
is written as a code into the expiration date or a strike Blockchain to understand the
Blockchain. The individuals involved price is hit, and the contract activity in the market, while
are anonymous, but the contract is executes itself according to maintaining the privacy of an
written in the public ledger. the coded terms. individual actor's position.
“
Let’s have a look at the cryptocurrency used in
Ethereum.
“
system and why it is necessary.
• The more the fee, the higher the chances for the
transactions to be picked up by the miners for inclusion
in the block.
• gasUsed is the total gas that is supposed to be used by the transaction during the
execution.
“
accounts in Ethereum Blockchain.
Ethereum blocks contain both a transaction list and the most recent “state” of the ledger of these transactions.
Accounts are one of the main building blocks of the Ethereum Blockchain.
• Externally owned accounts (EOAs): Defined as the basic form of an account, EOAs interact
with and generate updates on the Ethereum Blockchain.
“
• Contract accounts: They programmatically execute when they receive instructions in the
form of a transaction from an EOA. Contracts can push or pull funds and request these
actions from other contracts, calling on the code to perform dynamic actions.
• If we restrict Ethereum to only externally owned accounts and allow only transactions
between them, we arrive at an “altcoin” system that is less powerful than bitcoin itself and
can only be used to transfer ether.
• The state of all accounts is the state of the Ethereum network, which is updated with every
block and about which the network really needs to reach at a consensus.
“
© Copyright, Intellipaat Software Solutions Pvt. Ltd. All rights reserved.
Validators (or Miners) in Ethereum
“
• Like in Bitcoin, transactions are approved by the miners.
• Anyone can take on the role of a miner and approve the block of transactions.
“
• It takes around 12–15 seconds approximately for a miner to approve or mine a block.
“
used in Ethereum.
• Similar to bitcoin, the core idea behind mining is to find a nonce that once hashed
“
the result in a predetermined difficulty level.
• It uses different cryptographic primitive for its hashing function, known as SHA-3,
rather than SHA-256.
“
Virtual Machine.
Metropolis Serenity
“
technologies in development that seek to help
the network, and the components built on the
network, run more efficiently.
“
and what purpose they serve.
“
languages. This client diversity is essential for the long-term health of the Ethereum
network
• Approve transactions/blocks
Swarm (POC)
Whisper (POC)
“
in Ethereum.
• People add funds to the DAO and are given tokens that represent the ownership.
• The DAO begins to operate by having members to propose how to spend the
money.
• When the predetermined time has passed and the predetermined number of votes
has accrued, the proposals passes; otherwise, fails.
Type 1: A user may need to Type 2: The app mixes money with Type 3: The goal of DAO is to
exchange ether as a way to information from outside the Blockchain, form a leaderless company and
settle a contract with another for example, a crop insurance application program rules at the beginning
user, using the network's that's dependent on an outside weather about how members can vote
distributed computer nodes feed. (Say, a farmer buys a derivative that and how to release company
to facilitate the distribution of automatically pays out if there's a drought funds and then let it go.
this data. that impacts his work.)
KYC-chain allows users to maintain a private “identity wallet” which can be used to authenticate
their identification in finance, legal or commerce settings.
WeiFund uses smart contracts to enhance crowdfunding services including GoFundMe and
Kickstarter.
Storj provides censorship-free, secure and zero-downtime distributed cloud storage by sharing data
and storing it among a decentralized network of computers.
4G Capital provides micro loans for small businesses in Africa by utilizing smart contracts.
“
programming language and that language is Solidity.
Version Pragma
• Source files can (and should) be annotated with a so-called version pragma to reject
“
being compiled with future compiler versions that might introduce incompatible
change.
Such a source file will not compile with a compiler, earlier than version 0.4.0, and it
will also not work on a compiler starting from version 0.5.0.
Memory Storage
The contract can use any amount of The storage, on the other hand, is
memory while executing its code. But, persisted into the Blockchain itself so that
when execution stops, the entire content the next time the contract executes some
of the memory is wiped out, and the next code, it has access to all the data it
execution will start afresh. previously stored into its storage area.
Boolean Integers
Bool: The possible values are int/uint: Signed and unsigned
constants, i.e., true and false. integers of various sizes.
“ Members of Addresses
address x= 0x123;
address myAddress = this;
if (x.balance< 10 && myAddress.balance >=10) x.transfer(10);
String literals are written with either double or single quotes, such as “foo” or ‘bar’.
They do not imply trailing zeroes as in C; ”foo” represents three bytes not four.
As with integer literals their types can vary, but they are implicitly convertible to bytes1, …,
bytes32, if they fit to bytes and to string.
String literals support escape characters, such as \n, \xNN and \uNNNN.
\xNN takes a hex value and inserts the appropriate byte, while \uNNNN takes a Unicode code point
and inserts a UTF-8 sequence.
Dynamic storage arrays and bytes have a member function called push that can be used to append
an element at the end of the array.
• Creating arrays with variable length in memory can be done using a “new” keyword.
• As opposed to storage arrays, it is not possible to resize memory arrays by assigning to the
length member.
• A type of an array literal is the memory array of fixed size whose base type is a common type of
the given elements.
contract C {
function f() { g([uint(1), 2, 3]);
}
function g(uint[3] _data) {
// ...
} }
Here, _KeyType can be almost any type except for a dynamically sized array, a contract, an enum
and a struct.
Mappings can be seen as hash tables which are virtually initialized such that every possible key
exists and is mapped to a value whose byte representation is all zeros: a type’s default value.
The similarity ends here. Though the key data is not actually stored in a mapping, only its hash is
used to look up the value.
contract MappingExample {
mapping(address => uint) public balances;
contract MappingUser {
function f() returns (uint) { MappingExample m = new MappingExample(); m.update(100);
return m.balances(this);
}
}
• They are explicitly convertible to and from all integer types, but implicit conversion is not
allowed.
• The explicit conversions check the value ranges at runtime and a failure causes an exception.
Enums need at least one member.
function setGoStraight() {
choice = ActionChoices.GoStraight;
}
Block.blockhash(uint blockNumber) returns (bytes32): hash of the given block only works for 256
most recent blocks excluding current
addmod(uint x, uint y, uint k) returns (uint): mulmod(uint x, uint y, uint k) returns (uint):
Compute (x+y)%k where the addition is Compute (x*y)%k where the multiplication is
performed with arbitrary precision and does performed with arbitrary precision and does
not wrap around at 2**256 not wrap around at 2**256
Assert(bool condition):
Throws if the condition is not met to be used for internal errors
Require(bool condition):
Throws if the condition is not met to be used for errors in inputs or
external components
Revert():
Abort execution and revert state changes
“
Solidity.
Incremental Operators:
• Incremental operators in Solidity are: a++, a--, ++a, --a, a+=1, a=a+1
• Rules applicable to other programming languages are similar in Solidity as well.
Bitwise Operators:
• Following are the operators: (Bitwise OR) ‘|’, (Bitwise XOR), (Bitwise negation) ‘~’ , (Bitwise right shift)
‘>>’, (Bitwise left shift) ‘<
Logical Operators:
• Logical operators in Solidity: ! (logical negation), && (logical and), || (logical or), ==(equality), != (not
equal)
• Most of the control structures from JavaScript are available in Solidity except for switch
and goto.
• So there is: if, else, while, do, for, break, continue, return, ? :, with the usual semantics
known from C or JavaScript.
• Parentheses can not be omitted for conditionals, but curly braces can be omitted from
around single-statement bodies.
Example:
• The default value for a bool is false.
• The default value for the uint or int type is 0.
• For statically-sized arrays and bytes1 to bytes32, each individual element will be
initialized to the default value corresponding to its type.
• For dynamically-sized arrays, bytes and string, the default value is an empty array or
string.
Declaration:
A variable declared anywhere within a function will be in scope for the entire function,
regardless of where it is declared.
Input Parameters
Example: If we wish to return two results, the sum and the product of the two given
integers, then we would write:
Simple {
function arithmetics(uint _a, uint _b) returns (uint o_sum, uint
0_product){
O_sum = _a + _b; O_product
= _a* _b;
}
}
For example, they can automatically check a condition prior to executing the function.
These conditions can be checked even before making the function calls because they have
been declared in the function definitions in the smart contracts.
Modifiers are the inheritable properties of the contract and may be overridden by the
derived contracts.
It is executed on a call to the contract if none of the other functions match the given
function identifier.
Furthermore, this function is executed whenever the contract receives plain ether.
Contracts that receive ether directly (without a function call, i.e., using send or transfer),
but do not define a fallback function, throw an exception sending back the ether. So if you
want your contract to receive Ether, you have to implement a fallback function.
All function calls are virtual, which means that the most derived function is called, except
when the contract name is explicitly given.
When a contract inherits from multiple contracts, only a single contract is created on the
Blockchain, and the code from all the base contracts is copied into the created contract.
contract owned {
address owner;
function owned(){
owner = msg.sender;
}}
contract mortal is owned{ //’is’ keyword is used for Inheritance
function kill(){
self-destruct(owner);}}
contract User is owned, mortal //Multiple Inheritance
{
String public UserName;
function User(String _name){
UserName = _name;
}
}
contract Feline {
function utterance() returns (bytes32);
}
Such contracts cannot be compiled, but they can be used as base contracts.
contract Feline {
function utterance() returns (bytes32);
}
contract Cat is feline{
function utterance() returns (bytes32) {
return “miaow;
}
interface Token {
function transfer(address recipient, uint amount);
}
When they are called, they cause the arguments to be stored in the transaction’s log—a
special data structure in the Blockchain.
contract SimpleAuction {
event HighestBidIncreased(address bidder, uint amount); // Event
contract ClientReceipt {
event Deposit(
address indexed _from,
bytes32 indexed _id,
uint _value
);
This means that if library functions are called, their code is executed in the
context of the calling contract.
As a library is an isolated piece of source code, it can only access state variables of
the calling contract if they are explicitly supplied.
Q1. A Decentralized application would (typically) not require a midtier as it connects directly to the Ethereum
Network.
A. True
B. False
Q1. A Decentralized application would (typically) not require a midtier as it connects directly to the Ethereum
Network.
A. True
B. False
A. Casper
B. Ghost
C. Clique
D. ETHash
A. Casper
B. Ghost
C. Clique
D. ETHash