Download as pdf or txt
Download as pdf or txt
You are on page 1of 97

Module 3

 Permissionless Blockchain : Ethereum


 Introduction to Etheream
 Ethereum 1.0 and 2.0 ,
 Turing completeness EVM and compare with bitcoin
 Basics of Ether Units
 Ethereum Wallets Working with Metamask
 EOA and Contracts Transaction:: Structure of Transaction,
 Transaction Nonce,
 Transaction GAS,
 Recipient, Values and Data
 Transmitting Values to EOA and Contracts
Module 3
 Smart Contracts and Solidity
 Development environment and client ,
 Basic of Solidityand Web 3 Life cycle of Smart contract,
 Smart Contract programming using solidity,
 Metamask (Ethereum Wallet)
 Setting up development environment
 Use cases of Smart Contract
 Smart Contracts: Opportunities and Risk.

 Smart Contract Deployment


 Introduction to Truffle
 Use of Remix and test networks for deployment
Introduction to Etheream

 Ethereum is an open source, globally decentralized


computing infrastructure that executes programs
called smart contracts.
 It 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.
Introduction to Etheream

 The Ethereum platform enables developers to build


powerful decentralized applications with built-in
economic functions. While providing high
availability, auditability, transparency, and neutrality,
it also reduces or eliminates censorship and reduces
certain counterparty risks.
Components to Blockchain
 A peer-to-peer (P2P) network connecting participants and propagating
transactions and blocks of verified transactions, based on a standardized
“gossip” protocol.
 Messages, in the form of transactions, representing state transitions
 A set of consensus rules, governing what constitutes a transaction and what
makes for a valid state transition
 A state machine that processes transactions according to the consensus
rules
 A chain of cryptographically secured blocks that acts as a journal of all the
verified and accepted state transitions
 A consensus algorithm that decentralizes control over the blockchain, by
forcing participants to cooperate in the enforcement of the consensus rules
 A game-theoretically sound incentivization scheme (e.g., proof-of-work
costs plus block rewards) to economically secure the state machine in an
open environment
 One or more open source software implementations of the above
(“clients”)
Components to Ethereum

 P2P network
 Consensus Rules
 Transactions
 State Machines
 Data Structures
 Consensus Algorithms
 Economic Security
 Clients
Overview
- 2013: White Paper written by Vitalik Buterin (who
was 19 at the time!)
- 2015: The project was launched
- Goals:
- An alternative protocol for building decentralized applications
(DApps)
- A blockchain with a Turing-complete programming language
- The be able to build smart contracts on top of the protocol
- Namecoin can be written in 2 lines of code in Ethereum!
Ethereum Account
- Two types of accounts
- Externally owned account (User) - controlled by keys
- Contract account - controlled by code
- Account has four fields
- Nonce
- Ether balance
- Contract code (If contract account)
- Storage (mainly for contract account)
- Ether is the fuel that pays transaction fees
Transactions
- Signed data pack that stores a message that was sent from an externally
owned account
- Transactions contain
- Recipient of message
- Sender’s signature
- Amount of ether to send
- Maximum number of gas
- Price of gas
Messages
- Sent between contract accounts
- Virtual objects that are not serialized and only exist in ethereum
- Message contains
- Sender
- Recipient
- Amount of ether
- Start gas
- Basically like a transaction, but made by a contract
Ethereum State Transition Function
1. Check for well written form, valid signature, and matching nonce.
2. Calculate the transaction fee and find the destination address. Subtract the fee and
increment nonce for sender
3. Start the gas, and use some of it to pay for transaction
4. Transfer value from the sender's account to the receiving account
5. If the value transfer failed, revert all changes except the fee payment, which is added to
miner’s account
6. Otherwise, refund remaining gas to the sender, and send the fees paid for gas
consumed to the miner.
Code Execution
- EVM (Ethereum Virtual Machine) Code
- Low level, stack-based bytecode language
- Can have infinite loops
- Three places to store data
- Stack
- Memory
- Long term storage
- State: (block_state, transaction, message, code, memory, stack, pc, gas)
Blockchain and Mining
- Similar to Bitcoin’s Blockchain
- Contains transaction list and most recent state
- Block Validation Algorithm
- Check if previous block exists
- Check if timestamp is correct
- Check block number, difficulty, root, and gas limit
- Check proof of work
- Apply all transactions in transaction list
- Add payment to the miner
- State can be stored Patricia tree
- Like a merkle tree, but nodes can inserted/deleted efficiently
Gas + Fees
- Used to address infinite loops
- There is a need for regulatory mechanism (fees) to prevent use of Ethereum
- The concept of Gas was created for that
- Code on the contract will only run until all the Gas runs out
- Will revert back to original state if incomplete
- Gas incentivise people to write good contracts that don’t use up a lot of gas
- Miners will choose to run contracts that won’t take that much gas
- Also ethereum has a hard cap on how big a block can be
Currency and Issuance
- Ether is the main currency
- To pay transaction fees
- Exchange for different assets
- Can be divided into many little parts
- 1 Ether = 10^18 wei
- Permanent linear supply growth model to reduce risk of wealth concentration
- Supply growth rate will tend to zero over time
- Coins will be lost due to death, carelessness and coin loss
Sustainability
- Mining algorithm of Ethereum: Fetch some random data from state, compute
some random transactions on the last N blocks, return hash
- Lessen the need for ASICs
- An adaptive solution
- To deal with an ever growing blockchain size:
- Every miner will forced to be a full node,
- Include an intermediate state tree root in the blockchain after processing each transaction
Applications
Decentralized File Storage
- Similar to Dropbox, but decentralized
- Individual users can earn money by renting out unused space in their own
hard drives
- Possible thanks to smart contracts
- Split the file into many pieces to be stored
Decentralized Finance (DeFi)
- Collection of financial products on Ethereum
- No need to trust third parties to handle your money
- YOU hold your money
- YOU control where the money goes
- The future of banking?
- Market is open to anyone
- Transparency
- Transfers happens in minutes
- Ethereum is a great foundation for DeFi
- Smart Contracts enable borrowing, funding, insurance, and portfolio
managers
Decentralized Autonomous
Organization (DAO)
- An effective and safe way to interact with like-minded people
- Fully democratic: Just trust the DAO’s code
- Changes to code determined by a vote
- Smart Contract makes the backbone for the trust
- Also acts as a treasury
- Service handled automatically in a decentralized manner
- Use Cases
- Charities
- Freelance Network
- Membership
- Token based or share based
Non Fungible Token (NFT)
- Represent ownership of unique DIGITAL assets
- Only one official owner of a given NFT
- Secured by the blockchain
- Easy to prove ownership
- Minted by smart contracts

- Not Interchangeable (aka Fungible)


- Digital creators can now have ownership of
their work
- Digital work can also get auctioned
- You can get the “original copy”
Endless Possibilities...
- Crop insurance
- Cloud computing
- Peer to Peer gambling
- Prediction markets
- Data Feeds
- Lotteries
Ethereum Now
Ethereum Classic
- In 2016, “The DAO” was attacked
- 150 Million dollars lost!
- Ethereum Community decided to do a hard fork
- Code is not law anymore
- Some Miners didn’t agree with the fork
- Thus, “Ethereum Classic” was created as the old fork
Ethereum 2.0?
- Started in 2020, will fully merge with Ethereum 1.0 in 2022
- Proof of Stake
- Users stake their ETH to become validators
- Validators selected at random to choose blocks
- Much more eco-friendly
- Encourages more participation
- The Beacon Chain
- Expected to merge with Ethereum 1.0 in 2022
Controversy
- Ethereum’s price is extremely volatile (as with other cryptocurrencies)
- Gas Fees are on the high end
- NFT’s are controversial as people debate its value
- Still requires a lot of energy for proof of work
Ethereum Compared to Bitcoin
Ethereum Compared to Bitcoin
Ethereum Compared to Bitcoin
A General-Purpose Blockchain
Turing Completeness
Turing Completeness
Turing Completeness and GAS
Transactions


Type of Transactions
Transaction Structure
Transaction Structure (Cont…)

● The transaction message structure is serialized using the Recursive Length Prefix
(RLP) encoding scheme.

● All numbers in Ethereum are encoded as big-endian integers, of lengths that are
multiples of 8 bits.
● The data are separated by fixed length. No label is included for any field in
transaction serialization.

● There is no “from” data in the address identifying the originator EOA. That is because
the EOA’s public key can be derived from the v,r,s components of the ECDSA
signature. The address can be derived from the public key.
The Transaction Nonce
Transaction Nonce


Transaction Nonce (Cont..)






Gap in Nonces, Duplicate and confirmation
How does one get gas
Transaction GAS






Gas Price


Gas Limit


Getting Started with MetaMask
Getting Started with MetaMask
Switching Networks
Switching Networks
Getting Some Test Ether
Ethereum Client


Ethereum Network







Should I run full Node?




Remote Client





Remote Client and Wallet
Ethereum Improvement Proposals - EIP
Smart Contact
• Smart Contract (or cryptocontract) is a computer
program that directly and automatically controls the
transfer of digital assets between the parties under
certain conditions.
• A smart contract works in the same way as a traditional
contract while also automatically enforcing the contract.
• Smart contracts are programs that execute exactly as
they are set up(coded, programmed) by their creators.
Just like a traditional contract is enforceable by law,
smart contracts are enforceable by code.
Features of Smart Contracts
• Distributed
• Deterministic
• Immutable
• Autonomy
• Customizable
• Transparent
• Trustless
• Self-verifying
• Self-enforcing
Features of Smart Contracts
• Distributed: Everyone on the network is guaranteed to have a
copy of all the conditions of the smart contract and they
cannot be changed by one of the parties. A smart contract is
replicated and distributed by all the nodes connected to the
network.

• Deterministic: Smart contracts can only perform functions for


which they are designed only when the required conditions
are met. The final outcome will not vary, no matter who
executes the smart contract.

• Immutable: Once deployed smart contract cannot be


changed, it can only be removed as long as the functionality is
implemented previously.

• Autonomy: There is no third party involved. The contract is


made by you and shared between the parties.
Features of Smart Contracts
• Customizable: Smart contracts have the ability for
modification or we can say customization before being
launched to do what the user wants it to do.

• Transparent: Smart contracts are always stored on a public


distributed ledger called blockchain due to which the code is
visible to everyone, whether or not they are participants in the
smart contract.

• Trustless: These are not required by third parties to verify the


integrity of the process or to check whether the required
conditions are met.

• Self-verifying: These are self-verifying due to automated


possibilities.

• Self-enforcing: These are self-enforcing when the conditions


and rules are met at all stages.
Capabilities of Smart Contracts
• Accuracy

• Automation

• Speed

• Backup

• Security

• Savings

• Manages information

• Multi-signature accounts
Capabilities of Smart Contracts
• Accuracy: Smart contracts are accurate to the limit a
programmer has accurately coded them for execution.

• Automation: Smart contracts can automate the tasks/


processes that are done manually.

• Speed: Smart contracts use software code to automate tasks,


thereby reducing the time it takes to maneuver through all the
human interaction-related processes. Because everything is
coded, the time taken to do all the work is the time taken for
the code in the smart contract to execute.

• Backup: Every node in the blockchain maintains the shared


ledger, providing probably the best backup facility.
Capabilities of Smart Contracts
• Security: Cryptography can make sure that the assets are safe
and sound. Even if someone breaks the encryption, the hacker
will have to modify all the blocks that come after the block
which has been modified.

• Savings: Smart contracts save money as they eliminate the


presence of intermediaries in the process. Also, the money
spent on the paperwork is minimal to zero.

• Manages information: Smart contract manages users’


agreement, and stores information about an application like
domain registration, membership records, etc.

• Multi-signature accounts: Smart contracts support multi-


signature accounts to distribute funds as soon as all the
parties involved confirm the agreement.
How Do Smart Contracts Work?
A smart contract is just a digital contract with the security coding
of the blockchain.

• It has details and permissions written in code that require an


exact sequence of events to take place to trigger the
agreement of the terms mentioned in the smart contract.

• It can also include the time constraints that can introduce


deadlines in the contract.

• Every smart contract has its address in the blockchain. The


contract can be interacted with by using its address
presuming the contract has been broadcasted on the network.
How do Smart Contract Work?
• Identify Agreement: Multiple parties identify the cooperative
opportunity and desired outcomes and agreements could include
business processes, asset swaps, etc.
• Set conditions: Smart contracts could be initiated by parties
themselves or when certain conditions are met like financial market
indices, events like GPS locations, etc.
• Code business logic: A computer program is written that will be
executed automatically when the conditional parameters are met.
• Encryption and blockchain technology: Encryption provides secure
authentication and transfer of messages between parties relating to
smart contracts.
• Execution and processing: In blockchain iteration, whenever
consensus is reached between the parties regarding authentication
and verification then the code is executed and the outcomes are
memorialized for compliance and verification.
• Network updates: After smart contracts are executed, all the nodes
on the network update their ledger to reflect the new state. Once
the record is posted and verified on the blockchain network, it
cannot be modified, it is in append mode only.
Application of Smart Contracts
• Real Estate
• Vehicle ownership
• Music Industry
• Government elections
• Management
• Healthcare
• Etc.
Advantages of Smart Contracts
• Recordkeeping
• Autonomy
• Reduce fraud
• Fault-tolerance
• Enhanced trust
• Cost-efficiency
Advantages of Smart Contracts
• Recordkeeping: All contract transactions are stored in
chronological order in the blockchain and can be accessed
along with the complete audit trail. However, the parties
involved can be secured cryptographically for full privacy.

• Autonomy: There are direct dealings between parties. Smart


contracts remove the need for intermediaries and allow for
transparent, direct relationships with customers.

• Reduce fraud: Fraudulent activity detection and reduction.


Smart contracts are stored in the blockchain. Forcefully
modifying the blockchain is very difficult as it’s computation-
intensive. Also, a violation of the smart contract can be
detected by the nodes in the network and such a violation
attempt is marked invalid and not stored in the blockchain.
Advantages of Smart Contracts
• Fault-tolerance: Since no single person or entity is in control
of the digital assets, one-party domination and situation of
one part backing out do not happen as the platform is
decentralized and so even if one node detaches itself from the
network, the contract remains intact.

• Enhanced trust: Business agreements are automatically


executed and enforced. Plus, these agreements are immutable
and therefore unbreakable and undeniable.

• Cost-efficiency: The application of smart contracts eliminates


the need for intermediaries(brokers, lawyers, notaries,
witnesses, etc.) leading to reduced costs. Also eliminates
paperwork leading to paper saving and money-saving.
Challenges of Smart Contracts
• No regulations: A lack of international regulations focusing on
blockchain technology(and related technology like smart contracts,
mining, and use cases like cryptocurrency) makes these
technologies difficult to oversee.

• Difficult to implement: Smart contracts are also complicated to


implement because it’s still a relatively new concept and research is
still going on to understand the smart contract and its implications
fully.

• Immutable: They are practically immutable. Whenever there is a


change that has to be incorporated into the contract, a new
contract has to be made and implemented in the blockchain.

• Alignment: Smart contracts can speed the execution of the process


that span multiple parties irrespective of the fact whether the
smart contracts are in alignment with all the parties’ intention and
understanding.
Life Cycle of Smart Contract
• Phases of Smart Contract Life Cycle
• Following are the four phases of the smart contracts life
cycle in the blockchain ecosystem:

– Create
– Freeze
– Execute
– Finalize
Life Cycle of Smart Contract
• Create : Contract reiteration and negotiation constitute a
significant part of the first phase. First, the parties must
agree on the contract’s overall content and goals. This
can be done online or offline. This is similar to traditional
contract negotiations. On the blockchain being used to
draw up the smart contract, all participants must have a
wallet. Once the contents of the smart contract have
been finalized, they must be converted into code.

• The following tasks are done in this phase:

– Negotiation of multiple parties.


– Smart contract’s design, implementation, and validation.
Life Cycle of Smart Contract
• Create : Contract reiteration and negotiation constitute a
significant part of the first phase.
• First, the parties must agree on the contract’s overall
content and goals. This can be done online or offline.
This is similar to traditional contract negotiations.
• On the blockchain being used to draw up the smart
contract, all participants must have a wallet.
• Once the contents of the smart contract have been
finalized, they must be converted into code.

• The following tasks are done in this phase:

– Negotiation of multiple parties.


– Smart contract’s design, implementation, and validation.
Life Cycle of Smart Contract
• Freeze/ Deployment: Validation of the transactions on a
blockchain is done by a set of computers across the network called
nodes.
• These nodes are the blockchain miners.
• A small fee must be paid to the miners in exchange for this service
to keep the ecosystem from being flooded with smart contracts.
• The smart contract and its participants become open to the public
on the public ledger during the ‘freeze’ phase.
• Digital assets of both involved parties in the smart contracts are
locked via freezing the corresponding digital wallets, and nodes
operate as a governance board that verifies whether the
preconditions for smart contract execution have been satisfied.
• The following tasks are done in this phase:
– Smart Contracts are stored on the blockchain.
– Freezing of digital assets of involved parties.
Life Cycle of Smart Contract
• Execute: Participating nodes read contracts that are stored
on the distributed ledger.
• The integrity of a smart contract is verified by the
authenticating nodes, and the code is executed by the smart
contract’s interference engine (or by the compiler).
• When the inputs for the execution from one party are
received in the form of coins ,the interference engine creates
a transaction triggered by the met criteria.
• Now the new transaction data is added to the blockchain and
to ensure fulfillment according to the agreed-upon terms in
the Smart contract the governing nodes now verify it again.
‘Consensus mechanism’ governs this verification process.
• The following tasks are done in this phase:
– Evaluation of smart contact condition
– Auto execute smart contact statement triggered
Life Cycle of Smart Contract
• Finalize: After a smart contract has been executed, the new
states of all involved parties are updated.
• Now the updated state information and resulting transactions
are put in the distributed ledger of the blockchain and the
consensus mechanism verifies that the assets transferred by
the first party have been received and unfreezes the assets for
the receiving party.
• The following tasks are done in this phase:
– State updating and digital assets allocated.
– Unfreezing of digital assets received from the first party.
Life Cycle of Smart Contract
Web 3.Js
• Ethereum
– It is a cryptocurrency platform in the market just like Bitcoin.
– It is an open-source & decentralized blockchain featuring working on smart
contracts. It has its own cryptocurrency known as ether.
– The smart contracts in Ethereum are written in solidity.
• TestRPC
– The Ethereum TestRPC is like a manual emulator for blockchain.
– It provides blockchain interaction without running on an actual Ethereum
node.
– It also provides all the features required for testing of your blockchain. It is
based on Node.js.
• Web3.js
– Web3.js is an Ethereum-based JavaScript API that allows us to interact with a
local or remote Ethereum node using different servers such as HTTP.
– It interacts with the Ethereum blockchain and can retrieve data from the
blockchain as required by the developer.
– Through JSON RPC it communicates with Ethereum nodes.
Introduction to Programming:- Solidity
Programming
i)Solidity is a high-level programming language designed for
implementing smart contracts.

ii)It is statically-typed object-oriented(contract-oriented) language.

iii)Solidity is highly influenced by Python, c++, and JavaScript


which runs on the Ethereum Virtual
Machine(EVM).

iv)Solidity supports complex user-defined programming, libraries


and inheritance.

v)Solidity is primary language for blockchains running platforms.

vi)Solidity can be used to creating contracts like voting, blind


auctions, crowdfunding, multi- signature wallets, etc.
Solidity Programming:- Ethereum
Ethereum is a decentralized open-source platform based
on blockchain domain, used to run smart contracts i.e.
applications that execute the program exactly as it was
programmed without the possibility of any fraud, interference
from a third party, censorship, or downtime.
It serves a platform for nearly 2,60,000 different
cryptocurrencies.
Ether is a cryptocurrency generated by ethereum miners,
used to reward for the computations performed to secure the
blockchain.
Solidity Programming:- Ethereum Virtual Machine
(EVM)
Ethereum Virtual Machine abbreviated as EVM is a
runtime environment for executing smart contracts in
ethereum.
It focuses widely on providing security and execution of
untrusted code using an international network of public
nodes.
EVM is specialized to prevent Denial-of-service attack
and confirms that the program does not have any access
to each other’s state, also ensures that the
communication is established without any potential
interference.
Solidity Programming:- Solidity Types
Solidity is a statically typed language, which implies that the
type of each of the variables should be specified.
Data types allow the compiler to check the correct usage of the
variables.
The declared types have some default values called Zero-State,
for example for bool the default value is False.
Likewise other statically typed languages Solidity has Value
types and Reference types
Solidity Programming:- Value Types
Value type variables store their own data. These are the basic data types provided by
solidity. These types of variables are always passed by value. The variables are copied wherever
they are used in function arguments or assignment.
Value types data types used in solidity are as follows
Boolean: This data type accepts only two values True or False.
Integer: This data type is used to store integer values, int and uint are used to declare signed and
unsigned integers respectively.
Fixed Point Numbers: These data types are not fully supported in solidity yet, as per the
Solidity documentation. They can be declared as fixed and unfixed for signed and unsigned
fixed-point numbers of varying sizes respectively.
Address: Address hold a 20-byte value which represents the size of an Ethereum address. An
address can be used to get balance or to transfer a balance by balance and transfer method
respectively.
Bytes and Strings: Bytes are used to store a fixed-sized character set while the string is used to
store the character set equal to or more than a byte. The length of bytes is from 1 to 32, while the
string has a dynamic length. Byte has an advantage that it uses less gas, so better to use when we
know the length of data.
Enums: It is used to create user-defined data types, used to assign a name to an integral constant
which makes the contract more readable, maintainable, and less prone to errors. Options of
enums can be represented by unsigned integer values starting from 0.
Solidity Programming:- Value Types (Example)
// Solidity program to demonstrate
// value types
pragma solidity ^ 0.8.1;

// Creating a contract
contract Types {

// Initializing Bool variable


bool public boolean = false;

// Initializing Integer variable


int32 public int_var = -123456;

// Initializing String variable


string public str = “Vidyalankar”;

// Initializing Byte variable


bytes1 public b = "a";

// Defining an enumerator
enum my_enum { cmpn_, _for, _cmpn }

// Defining a function to return


// values stored in an enumerator
function Enum() public pure returns(
my_enum) {
return my_enum._cmpn;
}
}
Solidity Programming:- Reference Types
Reference type variables store the location of the data. They don’t share
the data directly. With the help of reference type, two different variables can refer
to the same location where any change in one variable can affect the other one.
Reference types used in solidity are as follows

Arrays: An array is a group of variables of the same data type in which variable
has a particular location known as an index. By using the index location, the
desired variable can be accessed. The array size can be fix or dynamic.

Struct: Solidity allows users to create and define their own type in the form of
structures. The structure is a group of different types even though it’s not possible
to contain a member of its own type. The structure is a reference type variable
which can contain both value type and reference type.

Mapping: Mapping is a most used reference type, that stores the data in a key-
value pair where a key can be any value types. It is like a hash table or dictionary
as in any other programming language, where data can be retrieved by key.
Solidity Programming:- Reference Types (Example)
// Solidity program to demonstrate
// Reference Types
pragma solidity ^0.8.1;

// Creating a contract
contract mapping_example {

// Defining an array
uint[5] public array
= [uint(1), 2, 3, 4, 5] ;

// Defining a Structure
struct student {
string name;
string subject;
uint8 marks;
}

// Creating a structure object


student public std1;

// Defining a function to return


// values of the elements of the structure
function structure() public returns(
string memory, string memory, uint){
std1.name = “VIT”;
std1.subject = “Computer”;
std1.marks = 72;
return (
std1.name, std1.subject, std1.marks);
}

// Creating a mapping
mapping (address => student) result;
address[] student_result;
}
Solidity Programming:- Solidity – Variables

Solidity supports three types of variables.

State Variables − Variables whose values are permanently stored in


a contract storage.

Local Variables − Variables whose values are present till function is


executing.

Global Variables − Special variables exists in the global namespace


used to get information about the blockchain.
Solidity Programming:- Solidity – Variables

State Variables:- Variables whose values are permanently stored in


a contract storage.
pragma solidity ^0.8.1;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10; // Using State variable
}
}
Solidity Programming:- Solidity – Variables

Local Variables:- Variables whose values are available only within a


function where it is defined.

pragma solidity ^0.8.1;


contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return storedData; //access the state variable
}
}
Solidity Programming:- Solidity – Variables
Global Variables:- These are special variables which exist in global
workspace and provide information about the blockchain and
transaction properties.
Name Returns

blockhash(uint blockNumber) Hash of the given block - only


returns (bytes32) works for 256 most recent,
excluding current, blocks
block.coinbase (address payable) Current block miner's address

block.difficulty (uint) Current block difficulty


block.gaslimit (uint) Current block gaslimit
block.number (uint) Current block number
block.timestamp (uint) Current block timestamp as
seconds since unix epoch
gasleft() returns (uint256) Remaining gas
msg.data (bytes calldata) Complete calldata
msg.sender (address payable) Sender of the message (current
caller)
msg.sig (bytes4) First four bytes of the calldata
(function identifier)
msg.value (uint) Number of wei sent with the
message
now (uint) Current block timestamp
tx.gasprice (uint) Gas price of the transaction
tx.origin (address payable) Sender of the transaction
Solidity Programming:- Solidity - Variable Scope

Scope of local variables is limited to function in which they are


defined but State variables can have three types of scopes.

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.
Solidity Programming:- Solidity - Operators

Solidity supports the following types of operators.

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

You might also like