0% found this document useful (0 votes)
52 views

Module 4 - Ethereum

Ethereum is a blockchain platform that allows developers to build decentralized applications and smart contracts. It has two types of accounts - externally owned accounts controlled by private keys and contract accounts controlled by code. Smart contracts on Ethereum use a programming language called Solidity and are executed by a decentralized virtual machine called the Ethereum Virtual Machine. Ethereum enables various applications like banking systems, voting systems, and games like chess where money or assets can be held in smart contracts and distributed according to the contract terms.

Uploaded by

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

Module 4 - Ethereum

Ethereum is a blockchain platform that allows developers to build decentralized applications and smart contracts. It has two types of accounts - externally owned accounts controlled by private keys and contract accounts controlled by code. Smart contracts on Ethereum use a programming language called Solidity and are executed by a decentralized virtual machine called the Ethereum Virtual Machine. Ethereum enables various applications like banking systems, voting systems, and games like chess where money or assets can be held in smart contracts and distributed according to the contract terms.

Uploaded by

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

CSE – IV Year – II Semester –

A5656 – Block Chain Technology


Module – 4 – Ethereum
Features of Ethereum: Smart Ethereum is often called Blockchain 2.0 Ethereum has two types of accounts: An

Ethereum
Contracts,EVM,Ether- externally owned account (EOA), and a
Cryptocurrency,Decentralized Contract account
applications(Daaps),Decentralized
autonomous organizations(DAOs) Ethereum is a blockchain based distributed computing
What is Ethereum platform that enables developers to build and deploy their
decentralized applications.

Ethereum is an ambitious altcoin that aims to provide


a Turing‐complete programming language for
writing scripts or “contracts”.
Ethereum is the most notable: it introduced several novel
technical ideas, held a successful crowd‐funding campaign,
raising $20 million over several months, and adopted
aggressive choices for parameters such as block time.
The Ethereum network is currently famous for allowing the implementation of smart contracts.
Smart contracts can be thought of as ‘cryptographic bank lockers’ which contain certain values.

Real-World Application of Ethereum : Banking systems: Due to the


decentralized nature of the Ethereum blockchain it becomes challenging
for hackers to gain unauthorized access to the network. It also makes
payments on the Ethereum network secure, so banks are using Ethereum
as a channel for making payments.
Voting: Voting systems are adopting Ethereum. The results of polls are
available publicly, ensuring a transparent fair system thus eliminating
voting malpractices.
Ethereum
Smart Contract Programming Model
The term smart contract was first used to describe the use of
computer systems (or other automated means) to enforce
contracts.
As an example, you could think of a vending machine as a
mechanical smart contract that enforces an agreement between you
and the machine’s owner involving the purchase of a candy bar.
In Ethereum, a contract is a program that lives on the block chain.
Anybody can create an Ethereum contract, for a small fee, by
uploading its program code in a special transaction. This contract is
written in byte code and executed by a special Ethereum‐specific
virtual machine, usually just called EVM. Once uploaded, the
contract will live on the block chain. It has its own balance of funds,
other users can make procedure calls through whatever API the program
exposes, and the contract can send and receive money.
Ethereum
A simple example: Namecoin in Ethereum
We claimed that Ethereum can be used to implement any
application‐specific altcoin’s functionality. As a simple example,
we can show how to implement Namecoin‐style functionality in a
very simple Ethereum contract.
One example implementation is shown in Figure 4.1. It is coded in
Solidity, Ethereum’s high‐level programming language for defining
contracts. This contract implements a crude name/value store or name
registry, in which names are assigned values once and for all. The
contract defines a data variable, registryTable, which is a mapping from
32‐byte strings to public keys. initially, it maps every string to the null
address 0x0000000000...000. This contract also defines a single entry
point, called “claimName”. This entry point accepts a single argument,
name. First, the contract makes sure that the caller has sent a value of at
least 10 wei, wei being the smallest currency unit in Ethereum. If
insufficient funds have been sent, the contract terminates with an error
Ethereum
(the “throw” statement does this) and no action is taken. If sufficient
funds are sent and the name is not yet taken, then it is permanently
assigned the value of whichever address invoked this function.
contract NameRegistry {
mapping(bytes32 => address) public registryTable;
function claimName(bytes32 name) {
if (msg.value < 10) {
throw;
}
if (registryTable[name] == 0) {
registryTable[name] = msg.sender;
}
}
}
Figure 4.1: A simple Ethereum smart contract implementing a
name registry
Ethereum
Every call must specify up front how much gas it is willing to spend (the
“gas limit”). If this value is hit (running out of gas), execution halts, all
changes to the program’s state are undone, and the miner pockets the gas
anyway. So it’s very important not to run out of gas.
The gas requirement means that very expensive computations are not
suitable for Ethereum. The system is not designed to be a
cloud‐computing service where you to pay others to do a difficult
computation that you’re unable to do yourself. Services like Amazon’s
Elastic Compute Cloud or Microsoft’s Azure provide millions of
times more bang for your buck.
On the other hand, Ethereum is suitable for implementing
security protocol logic. Essentially, it provides a service that
two (or more) anonymous parties can count on to behave as
specified.
Ethereum
That’s all this contract can do in 8 lines of code. But we could add all of
the other features of Namecoin with a little more work. For example, we
could store more data with each mapping than just the address of the
entity that claimed it. We could require name owners to re‐register
periodically by storing a “last updated” time and allowing other users
to claim names that haven’t been updated in a long time.
Gas, incentives, and security. Unlike Bitcoin, Ethereum
supports loops, although we didn’t need them in our first example.
That should immediately raise alarm bells.
If there are loops, there can be infinite loops. In general, Ethereum
contracts might run forever for a variety of reasons. A famous result in
computer science (the undecidability of the Halting Problem)
states that there’s no algorithm that can look at a program’s source code
and always correctly determine if it will run forever or not. So how can
we prevent contracts from running forever?
Ethereum
The security of Ethereum’s block chain is not nearly as
well‐established as Bitcoin’s. Theoretically, the system is much more
complex and therefore harder to reason about mathematically.
Practically, Ethereum hasn’t been around for very long and hasn’t been
subject to the same kind of scrutiny as Bitcoin. In particular, there are
concerns that the cost of transaction processing throws Bitcoin‐style
incentive arguments out of whack, similar to our discussion about
merge mining. When transaction processing is a nontrivial fraction of a
miner’s total cost, the system favors larger miners since this cost is
independent of hash power.
More importantly, the gas payment goes only to the miner who initially
includes the transaction in a block. But all miners building on that block
must also validate the transaction, and they don’t get paid for doing so.
This means they have an incentive to skip validation.
Ethereum
A second example: chess in Ethereum. We still haven’t said much
about what you can do with Ethereum that’s new, so let’s look at a
second example.
Suppose Alice wants to challenge Bob to a game of chess with money on
the line. The only problem is that Alice and Bob live in different countries
and neither trusts each other to pay if they lose. This is a problem
Ethereum can solve.
Alice will write an Ethereum program that implements the rules of
chess and upload it to Ethereum. She’ll send the contract a quantity of
ether equal to the amount she wants to bet. Bob can see this contract, and
if he decides to accept the challenge, he can start the game by sending his
own betting stake to the contract. Before doing this, Bob should make
sure the contract is correctly written in that it implements chess and will
ultimately send all of its value to the winning player.
Ethereum
Once both players have sent their stake in, the contract should check that
the stakes are equal, assuming they’re making an even wager. At this point
the game is afoot, and there should be no way for either player to extract
the money from the contract without actually winning the game, or for
anyone else to extract the money under any circumstance.
Alice and Bob will take turns sending transactions to the contract which
indicate the next move they’d like to play. The contract, of course, must
ensure that each move is sent in only by the player whose turn it is to
move, and not by the other player or by someone else entirely. Remember
that every transaction (which causes the contract to execute a function) is
signed by the caller, so the contract can ensure this.
The contract will also have to check all of the rules of chess. If a player
tries to move a pawn three spaces, that will have to be rejected.
Ethereum
Eventually, the game will end. After each move, the contract must check
if either player is mated, or if the game is a draw by stalemate or one of
the other drawing conditions in chess. Players should also be able to send
in a move indicating their resignation. When the game ends, the contract
can terminate itself and send all of the money to the winning player. or
split the money in case of a draw.
Other applications. Playing chess might be fun, but the real
excitement for Ethereum is about financial applications. Many of the
applications including prediction markets, smart property,
escrowed payments, micropayment channels, and mixing
services can all be implemented in Ethereum. There are subtleties
to all of these applications, but they are all possible and in most cases are
much simpler to implement than the types of bolt‐on protocols we’ve
seen with Bitcoin. There are also a host of other applications, like auctions
and order books which people are enthusiastic about using Ethereum to
implement.
Ethereum
State and account balances in Ethereum.
There are two ways to design a ledger: account‐based and
transaction‐based. In a transaction‐based ledger like Bitcoin, the
block chain stores only transactions (plus a small amount of metadata in
the block headers).
To make it easier to validate transactions, Bitcoin treats coins as
immutable, and transaction outputs must be spent in their entirety, with
change addresses used if necessary.
Effectively, transactions operate on a global state which is a list of
UTXOs, but this state is never made explicit in the Bitcoin protocol
and is simply something miners create on their own to speed up
verification.
Ethereum, on the other hand, uses an account‐based model.
Since Ethereum already stores a data structure mapping contract
addresses to state, it is natural to also store the account balance of every
regular address (also called an owned address) in the system.
Ethereum
This means that instead of representing payments using an acyclic
transaction graph where each transaction spends some inputs and creates
some outputs, Ethereum just stores a balance for each address like a
traditional bank might store the balance of each account number.
Data structures in Ethereum
Ethereum has data structures for record-keeping. Specifically, every block
contains a digest of the current state (balance and transaction count) of
every address as well as the state (balance and storage) of every contract.
Each contract’s storage tree maps arbitrary 256‐bit addresses to 256‐bit
words, making for a whopping 2^256 ⨉ 256 = 2^264 bytes of
storage. Of course, you could never fill up all of this storage, but that’s
the theoretical space. The digest makes it easy to prove that a given
address has a given balance or storage state. For example, Alice can prove
to Bob what her balance is without Bob having to scan the entire block
chain to verify the proof.
Ethereum
The simple binary Merkle tree used in Bitcoin would work for this
purpose as it allows efficient proofs of inclusion (provided
miners ensure that no tree will include two different states for
the same address). But we also want fast lookups and the ability to
efficiently update an address’s value.
To do this Ethereum uses a slightly more complicated tree
structure called a Patricia tree , also known as a prefix tree,
trie, or radix tree.
Each Ethereum block includes the root of a Merkle Patricia tree
committing to the state of every address, including contract addresses.
Each contract’s state, in turn, includes a tree committing to the entire
state of its storage.
Ethereum
Another tricky issue with an account‐based ledger is
preventing replay attacks. In Bitcoin, since every transaction
consumes its input UTXOs, the same signed transaction can never be
valid twice.
With Ethereum’s design, we need to make sure that if Alice signs a
transaction saying “pay 1 ether to Bob”, Bob can’t broadcast the
transaction over and over again until Alice’s account is drained.
To avoid this, every account in Ethereum has a transaction counter
tracking how many transactions it has sent.
The statement Alice really signs is “I authorize my n’ th transaction
to be a payment of 1 ether to Bob.” This transaction can’t be
replayed because after it is processed, Alice’s transaction counter will
increment and is part of the global state.
Ethereum
Ethereum project:
Ethereum was initially described in late 2013 and launched its
first release, dubbed Frontier, in 2015. Ethereum utilized a pre‐sale,
making units of the ether currency publicly available for a fixed price in
Bitcoin, with all of the proceeds going to the Ethereum Foundation. This is
a slower pace of development compared to many altcoins, but it reflects
that fact that Ethereum is much more complex.
In addition to EVM (Ethereum Virtual Machine), a new programming
model, and new data structures, Ethereum made significant changes to
Bitcoin’s consensus protocol as well. The block time is targeted at 12
seconds instead of 10 minutes. To lessen the impact of stale blocks, which
comprise a larger fraction of blocks in Ethereum than in Bitcoin,
Ethereum uses an alternative protocol called GHOST to
compute the consensus branch. It also uses a different proof‐of‐work.
Currently, it’s a mix of hash functions designed to be memory hard, though
in the future Ethereum plans to switch to a proof‐of‐stake system.
Ethereum
Ethereum project:
The Ethereum project is stewarded by a non‐profit foundation and is
relatively centralized in planning and decision making.
There is an announced schedule of future versions of the protocol that
will introduce changes based on early Ethereum experience.
These will be hard forks by design, and furthermore, every Ethereum
contract will be destroyed in between versions.
So Ethereum is still very much an experimental system with
major changes planned.
They compete, cooperate, and interact in various ways, some cooperative,
some harmful.
It’s also possible that in the future, there will be technical ways for
transactions in one block chain to explicitly refer to transactions in
another block chain.
Ethereum, Solidity, EVM
Ethereum is a decentralized ie., Block chain platform that runs smart
contracts i.e. applications that run exactly as programmed without any
possibility of downtime, censorship,
object-oriented
fraud or third-party interference.
Solidity is a contract-oriented, high-level programming
language for implementing smart contracts.
Solidity is highly influenced by C++, Python and JavaScript and has
been designed to target the Ethereum Virtual Machine (EVM).
Solidity is statically typed, supports inheritance, libraries and complex
user-defined types programming language. Solidity is the primary language for
blockchains running platforms.

You can use Solidity to create contracts for uses such as voting, crowd
funding, blind auctions, and multi-signature wallets.
The EthereumVirtual Machine (EVM)
The Ethereum Virtual Machine, also known as EVM, is the
runtime environment for smart contracts in Ethereum. The Ethereum
Virtual Machine focuses on providing security and executing untrusted
it provides a secure and reliable way to run decentralized
code by computers all over the world. applications (DApps) on the blockchain.
The EVM is required because it provides a common Example of EVM in action is the popular DApp, Uniswap.It's a decentralized

EVM and Smart Contract


platform for developers to write smart contracts in high- exchange that allows users to trade Ethereum-based tokens without the
level programming languages such as Solidity, which is need for centralized intermediary. It achieves this by running on Ethereum
then compiled to bytecode that can be executed on EVM. blockchain and utilizing the EVM to execute its smart contract code.

The EVM specialized in preventing Denial-of-service attacks and


ensures that programs do not have access to each other's state, ensuring
communication can be established without any potential interference.
The Ethereum Virtual Machine has been designed to serve as a
runtime environment for smart contracts based on Ethereum.
What is Smart Contract?
A Smart Contract (or cryptocontract) is a computer program that directly and automatically controls the transfer of digital
A smart
assets between the contract is aconditions.Smart
parties under certain computer protocol
contracts are programsintended toasdigitally
that execute exactly they are set
up(coded, programmed) by their creators.The bitcoin network was the first to use some sort of smart contract by using
facilitate,
them verify,
to transfer value or enforce
from one person thecontract
to another. A smart negotiation or performance
is just a digital contract with the security coding ofof
the blockchain. There are some common smart contract platforms like Ethereum, Solana, Polkadot. Features of Smart
a contract.
Contracts: Distributed, Deterministic, Immutable, Customizable, Self-verifying, Self-enforcing .

Smart contracts allow the performance of credible transactions


without third parties.These transactions are trackable and irreversible.
The concept of smart contracts was first proposed by Nick Szabo in
1994.
Szabo is a legal scholar and cryptographer known for laying
the groundwork for digital currency.
Ex:Let's say 2 people want to bet on outcome of a football game, but they don't trust each other. They could create a smart contract

Solidity
that specifies the terms of the bet,such as the teams playing,the amount of the wager and the deadline for the bet. They would then
transfer their bet to the smart contract,which would hold it until end of the game.The smart contract would then automatically pay out
the winnings to the winner, based on the outcome of the game, without the need for a middleman to handle the transaction.
Solidity - Environment Setup
It explains how we can setup Solidity compiler on CentOS machine. If
you do not have a Linux machine then you can use our Online Compiler
for small contracts and for quickly learning Solidity.
Method 1 - npm / Node.js
This is the fastest way to install Solidity compiler on your CentoS
Machine.We have following steps to install Solidity Compiler.
Install Node.js
First make sure you have node.js available on your CentOS machine. If it
is not available then install it using the following commands.
# First install epel-release
$sudo yum install epel-release
# Now install nodejs
$sudo yum install nodejs
# Next install npm (Nodejs Package Manager )
$sudo yum install npm
Solidity
# Finally verify installation
$npm –version
If everything has been installed then you will see an output something like
this − 3.10.10
Install solc
Once you have Node.js package manager installed then you can proceed
to install Solidity compiler as below.
$sudonpm install -g solc
The above command will install solcjs program and will make it available
globally through out the system. Now you can test your Solidity compiler
by issuing following command.
$solcjs-version
If everything goes fine, then this will print something as follows.
0.5.2+commit.1df8f40c.Emscripten.clang
Now you are ready to use solcjs which has fewer features than the
standard Solidity compiler but it will give you a good starting point.
Solidity
Method 2 - Docker Image
You can pull a Docker image and start using it to start with Solidity
programming. Following are the simple steps. Following is the command
to pull a Solidity Docker Image.
$docker pull ethereum/solc:stable
Once a docker image is downloaded we can verify it using the following
command.
$docker run ethereum/solc:stable-version
This will print something as follows
$ docker run ethereum/solc:stable -version
solc, the solidity compiler command line interfaceVersion:
0.5.2+commit.1df8f40c.Linux.g++
Method 3: Binary Packages Installation
If you are willing to install full fledged compiler on your Linux machine,
then please check official website Installing the Solidity Compiler.
Solidity
Solidity - Basic Syntax
A Solidity source files can contain an any number of contract
definitions, import directives and pragma directives.
Let's start with a simple source file of Solidity.
Following is an example of a Solidity file.
pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
Solidity – Pragma and Contract
Pragma
InThe first
Solidity, line
a pragma is a is a pragma
statement directive
that tells the compiler which which
version oftells that
the Solidity the
language source
to code
use for compiling theis
contract. It's important to specify the correct version to ensure that the contract works as intended, as different versions of
written
Solidity may havefor Solidity
different
pragma solidity ^0.8.0;
featuresversion
and syntax. 0.4.0 or anything newer that does not break

Infunctionality up
this example, we're using to, but
^0.8.0 not
to specify including,
that version
our contract should 0.6.0.
be compiled using version 0.8.0 or higher, but lower
than version 0.9.0.The ^ symbol means that the contract can use any compatible minor version greater than or equal to
A pragma
0.8.0, directive is always local to a source file and if you import
but less than 0.9.0.

another file, the pragma from that file will not automatically apply to the
importing file.
So a pragma for a file which will not compile earlier than version 0.4.0
and it will also not work on a compiler starting from version 0.5.0 will be
written as follows −
pragma solidity ^0.4.0;
Here the second condition is added by using ^.
Solidity Contract The contract keyword is used to define a new contract in Solidity.
A Solidity contract is a collection of code (its functions) and
data (its state) that resides at a specific address on the
Ethereum block chain. The line uintstored Data declares a state
variable called stored Data of type.
Solidity Contract, Importing Files
uint and the functions set and get can be used to modify or retrieve the
value of the variable.
Importing Files
Though above example does not have an import statement but Solidity
supports import statements that are very similar to those available in
JavaScript.
The following statement imports all global symbols from "filename".
import "filename";
The following example creates a new global symbol symbolName whose
members are all the global symbols from "filename".
import * as symbolName from "filename";
To import a file x from the same directory as the current file, use import
"./x" as x;.
If you use import "x" as x; instead, a different file could be referenced in
a global "include directory".
Solidity - Keywords
Reserved Keywords
Following are the reserved keywords in Solidity.
abstract after alias apply
auto case catch copyof
default define final immutable
implements in inline let
macro match mutable null
of override partial promise
reference relocatable sealed sizeof
static supports switch try
typedef typeof unchecked
Solidity – First Application
We're using Remix IDE to Compile and Run our Solidity Code base.

Step 1 − Copy the given code in Remix IDE Code Section.

Example:
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Solidity – First Application, Comments
Step 2 − Under CompileTab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.
Output
0: uint256: 3
Solidity - Comments
Solidity supports both C-style and C++-style comments, Thus, any text
between a // and the end of a line is treated as a comment and is ignored
by Solidity Compiler. Any text between the characters /* and */ is
treated as a comment.This may span multiple lines.
Example
The following example shows how to use comments in Solidity.
function getResult() public view returns(uint){
// This is a comment. It is similar to comments in C++
Solidity - Types
/* This is a multi-line comment in solidity
* It is very similar to comments in C Programming */
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
Solidity -Types
While writing program in any language, you need to use various variables
to store various information. Variables are nothing but reserved
memory locations to store values. This means that when you create a
variable you reserve some space in memory.
You may like to store information of various data types like character,
wide character, integer, floating point, double floating point, boolean etc.
Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Solidity – General Value Types
GeneralValue Types
Solidity offers the programmer a rich assortment of built-in as well as
user defined data types. Following table lists down seven basic C++ data
types.
Type Keyword Values
Boolean bool true/false
Integer int/uint Signed and unsigned integers of varying
sizes.
Integer int8 to int256 Signed int from 8 bits to 256 bits. int256 is
the same as int.
Integer uint8 to uint256 Unsigned int from 8 bits to 256 bits.
uint256 is the same as uint.
Fixed Point fixed/unfixed Signed and unsigned fixed point numbers of
Numbers varying sizes.
Solidity
Note: You can also represent the signed and unsigned fixed-point
numbers as fixedMxN / ufixedMxN where M represents the number of
bits taken by type and N represents the decimal points. M should be
divisible by 8 and goes from 8 to 256. N can be from 0 to 80.
Type Keyword Values
Fixed Point Fixed / Signed and unsigned fixed point numbers of varying sizes.
Numbers unfixed
Fixed Point fixedMxN Signed fixed point number where M represents number of
Numbers bits taken by type and N represents the decimal points. M
should be divisible by 8 and goes from 8 to 256. N can be
from 0 to 80. fixed is same as fixed128x18.
Fixed Point ufixedMxN Unsigned fixed point number where M represents number
Numbers of bits taken by type and N represents the decimal points.
M should be divisible by 8 and goes from 8 to 256. N can be
from 0 to 80. ufixed is same as ufixed128x18.
Solidity – address, Variables
address
address holds the 20 byte value representing the size of an Ethereum
address. An address can be used to get the balance using .balance
method and can be used to transfer balance to another address using
.transfer method.
address x = 0x212; address myAddress = this;
if (x.balance < 10 && myAddress.balance >= 10)
x.transfer(10);
Solidity - Variables Inmanipulated
Solidity, variables are used to store data values that can be accessed and
throughout the code.
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 block chain.
Solidity Variables
Solidity is a statically typed language, which means that the state or local
variable type needs to be specified during declaration. Each declared
variable always have a default value based on its type. There is no concept
of "undefined" or "null".
State Variable
Variables whose values are permanently stored in a contract storage.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10; // Using State variable
}
}
LocalVariable
Variables whose values are available only within a function where it is
defined. Function parameters are always local to that function.
Solidity - Variables
pragma solidity ^0.5.0;
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 result; //access the local variable
}
}
Solidity Global Variables
These are special variables which exist in global workspace and provide
information about the block chain and transaction properties.
Name Returns
blockhash(uint blockNumber) returns Hash of the given block - only works for 256 most recent, excluding current, blocks
(bytes32)

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


Solidity Variable Names
While naming your variables in Solidity, keep the following rules in mind.
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.
Example: pragma solidity ^0.5.0;
contract C {
uint public data = 30; uint internal iData= 10;
function x() public returns (uint) {
data = 3; // internal access
return data; }
}
Solidity – Variable Names
contract Caller {
C c = new C();
function f() public view returns (uint) {
return c.data(); //external access
}
}
contract D is C {
function y() public returns (uint) {
iData = 3; // internal access
return iData;
}
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 – Ether Units and Time Units
Solidity - Ether Units
In solidity we can use wei, finney, szabo or ether as a suffix to a literal to
be used to convert various ether based denominations. Lowest unit is wei
and 1e12 represents 1 x 1012.
assert(1 wei == 1); In Solidity, we use ether units to specify amounts of ether and
time units to specify time durations. This is because the
assert(1 szabo == 1e12); Ethereum blockchain uses ether as its native currency and time
is an important factor in many smart contract applications.
assert(1 finney == 1e15);
assert(1 ether == 1e18);
assert(2 ether == 2000 fenny);
Time Units
Similar to currency, Solidity has time units where lowest unit is second
and we can use seconds, minutes, hours, days and weeks as suffix to
denote time.
assert(1 seconds == 1); assert(1 minutes == 60 seconds);
assert(1 hours == 60 minutes);
assert(1 day == 24 hours); assert(1 week == 7 days);
Solidity – Functions
A function is a group of reusable code which can be called anywhere in
your program. This eliminates the need of writing the same code again
and again. It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program into a number of
small and manageable functions.
Like any other advanced programming language, Solidity also
supports all the features necessary to write modular code
using functions.
Function Definition
Before we use a function, we need to define it. The most common way to
define a function in Solidity is by using the function keyword, followed
by a unique function name, a list of parameters (that might be empty),
and a statement block surrounded by curly braces.
Syntax:
function function-name(parameter-list) scope returns() {
//statements
}
Solidity – Functions
Example
Try the following example. It defines a function called getResult that
takes no parameters : In Solidity, a user-defined function is a piece of code that
performs a specific task and can be called from other parts of

pragma solidity ^0.5.0; the code. These functions are defined by the programmer and
can have parameters, return values, and visibility levels. Here is

contract Test { an example of a user-defined function in Solidity:

function getResult() public view returns(uint){


uint a = 1; // local variable pragma solidity ^0.8.0;
contract MathFunctions {
uint b = 2; function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
uint result = a + b; }
}

return result; pragma solidity ^0.8.0;


} contract Test {
MathFunctions mathFunctions = new MathFunctions();
} function testAdd(uint256 a, uint256 b) public view returns (uint256) {
return mathFunctions.add(a, b);
Calling a Function }
}

To invoke a function somewhere later in the Contract, you would simply


need to write the name of that function as shown in the following code.
Try the following code to understand how the string works in Solidity.
Solidity – Functions
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
Solidity – Functions
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);//access local variable
}
}
Run the above program using steps provided in Solidity First Application.
Output:
0: string: 3

You might also like