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

Solidity Programming

Uploaded by

vaishnavishitre
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Solidity Programming

Uploaded by

vaishnavishitre
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Solidity programming

• 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.
a 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 storedDa

• 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;
• }
•}
• Pragma
• The first line is a pragma directive which tells that the source code is
written for Solidity version 0.4.0 or anything newer that does not
break functionality up to, but not including, version 0.6.0.
• Contract
• A Solidity contract is a collection of code (its functions) and data (its
state) that resides at a specific address on the Ethereum blockchain.
• Importing Files
• import "filename";
Reserved Keywords
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
• 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 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.
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.
State Variable
• pragma solidity ^0.5.0;
• contract SolidityTest {
• uint storedData; // State variable
• constructor() public {
• storedData = 10; // Using State variable
• }
•}
Local Variable
• 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 storedData; //access the state variable
• }
• }
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.
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;
}
}
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 - Arrays
• Array is a data structure, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
• type arrayName [ arraySize ];
pragma solidity ^0.5.0;

contract test {
function testArray() public pure{
uint len = 7;

//dynamic array
uint[] memory a = new uint[](7);

//bytes is same as byte[]


bytes memory b = new bytes(len);

assert(a.length == 7);
assert(b.length == len);

//access array variable


a[6] = 8;

//test array variable


assert(a[6] == 8);

//static array
uint[3] memory c = [uint(1) , 2, 3];
assert(c.length == 3);
}
}
Solidity - Enums
• pragma solidity ^0.5.0;

• contract test {
• enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
• FreshJuiceSize choice;
• FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

• function setLarge() public {


• choice = FreshJuiceSize.LARGE;
• }
• function getChoice() public view returns (FreshJuiceSize) {
• return choice;
• }
• function getDefaultChoice() public pure returns (uint) {
• return uint(defaultChoice);
• }
• }
Solidity - Structs
• pragma solidity ^0.5.0;

• contract test {
• struct Book {
• string title;
• string author;
• uint book_id;
• }
• Book book;

• function setBook() public {


• book = Book('Learn Java', 'TP', 1);
• }
• function getBookId() public view returns (uint) {
• return book.book_id;
• }
• }
Solidity - Mapping
• Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type.
• pragma solidity ^0.5.0;

• contract LedgerBalance {
• mapping(address => uint) public balances;

• function updateBalance(uint newBalance) public {


• balances[msg.sender] = newBalance;
• }
• }
• contract Updater {
• function updateBalance() public returns (uint) {
• LedgerBalance ledgerBalance = new LedgerBalance();
• ledgerBalance.updateBalance(10);
• return ledgerBalance.balances(address(this));
• }
• }
Solidity - Functions
• pragma solidity ^0.5.0;

• contract Test {
• function getResult() public view returns(uint){
• uint a = 1; // local variable
• uint b = 2;
• uint result = a + b;
• return result;
• }
•}
Solidity - Function Modifiers
• Function Modifiers are used to modify the behaviour of a function. • contract Register is Owner {
• pragma solidity ^0.5.0;
• mapping (address => bool) registeredAddresses;
• contract Owner { • uint price;
• address owner; • constructor(uint initialPrice) public { price =
• constructor() public { initialPrice; }
• owner = msg.sender;

• }
• modifier onlyOwner { • function register() public payable costs(price) {
• require(msg.sender == owner); • registeredAddresses[msg.sender] = true;
• _;
• }
• }
• modifier costs(uint price) { • function changePrice(uint _price) public
• if (msg.value >= price) { onlyOwner {
• _; • price = _price;
• }
• }
• }
• } • }
Solidity - View Functions
• View functions ensure that they will not modify the state. A function can be declared as view. The following statements if present in the
function are considered modifying the state and compiler will throw warning in such cases.

• Modifying state variables.

• Emitting events.

• Creating other contracts.

• Using selfdestruct.

• Sending Ether via calls.

• Calling any function which is not marked view or pure.

• Using low-level calls.

• Using inline assembly containing certain opcodes.


Solidity - Pure Functions
• Pure functions ensure that they not read or modify the state. A function can be declared as pure. The following
statements if present in the function are considered reading the state and compiler will throw warning in such
cases.

• Reading state variables.

• Accessing address(this).balance or <address>.balance.

• Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read).

• Calling any function not marked pure.

• Using inline assembly that contains certain opcodes.

• Pure functions can use the revert() and require() functions to revert potential state changes if an error occurs.
• pragma solidity ^0.5.0;

• contract Test {
• function getResult() public pure returns(uint product, uint sum){
• uint a = 1;
• uint b = 2;
• product = a * b;
• sum = a + b;
• }
•}
Solidity - Fallback Function
• Fallback function is a special function available to a contract. It has following features −

• It is called when a non-existent function is called on the contract.

• It is required to be marked external.

• It has no name.

• It has no arguments

• It can not return any thing.

• It can be defined one per contract.

• If not marked payable, it will throw exception if contract receives plain ether without data.
pragma solidity ^0.5.0;

contract Test {
uint public x ;
function() external { x = 1; }
}
contract Sink {
function() external payable { }
}
contract Caller {
function callTest(Test test) public returns (bool) {
(bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
require(success);
// test.x is now 1

address payable testPayable = address(uint160(address(test)));

// Sending ether to Test contract,


// the transfer will fail, i.e. this returns false here.
return (testPayable.send(2 ether));
}
function callSink(Sink sink) public returns (bool) {
address payable sinkPayable = address(sink);
return (sinkPayable.send(2 ether));
}
}
Solidity - Contracts
• Contract in Solidity is similar to a Class in C++. A Contract have following
properties.

• Constructor − A special function declared with constructor keyword which


will be executed once per contract and is invoked when a contract is created.

• State Variables − Variables per Contract to store the state of the contract.

• Functions − Functions per Contract which can modify the state variables to
alter the state of a contract.
Visibility Quantifiers
• Following are various visibility quantifiers for functions/state variables of a contract.

• external − External functions are meant to be called by other contracts. They cannot be used for
internal call. To call external function within contract this.function_name() call is required. State
variables cannot be marked as external.

• public − Public functions/ Variables can be used both externally and internally. For public state
variable, Solidity automatically creates a getter function.

• internal − Internal functions/ Variables can only be used internally or by derived contracts.

• private − Private functions/ Variables can only be used internally and not even by derived
contracts.
Solidity - Inheritance
• Inheritance is a way to extend functionality of a contract. Solidity supports both single as well as
multiple inheritance. Following are the key highlighsts.

• A derived contract can access all non-private members including internal methods and state
variables. But using this is not allowed.

• Function overriding is allowed provided function signature remains same. In case of difference
of output parameters, compilation will fail.

• We can call a super contract's function using super keyword or using super contract name.

• In case of multiple inheritance, function call using super gives preference to most derived
contract.
Multi-level Inheritance
• Multi-level inheritance is similar to the single level, but the difference
is, it has levels of parent-child relationships. The child contract—
derived from a parent contract—also acts as a parent contract of
another contract. Take a look at the following diagram:
Hierarchical Inheritance
• In hierarchical inheritance, the base contract has over one derived
contract. This inheritance is useful when one common functionality is
used in multiple places. The following diagram is displayed the type
hierarchical, where a single contract is a parent of multiple child
contracts.
Multiple Inheritance
• Unlike C# and Java, Solidity supports multiple-inheritance. The single
contract can be inherited from more than one contract. Here, in the
following diagram, shown is the multiple-inheritance.
Solidity - Error Handling
• Solidity provides various functions for error handling. Generally when an error occurs, the state is reverted back to its
original state. Other checks are to prevent unauthorized code access. Following are some of the important methods used in
error handling −

• assert(bool condition) − In case condition is not met, this method call causes an invalid opcode and any changes done to
state got reverted. This method is to be used for internal errors.

• require(bool condition) − In case condition is not met, this method call reverts to original state. - This method is to be used
for errors in inputs or external components.

• require(bool condition, string memory message) − In case condition is not met, this method call reverts to original state. -
This method is to be used for errors in inputs or external components. It provides an option to provide a custom message.

• revert() − This method aborts the execution and revert any changes done to the state.

• revert(string memory reason) − This method aborts the execution and revert any changes done to the state. It provides an
option to provide a custom message.
Assert Statement
• Its syntax is similar to the require statement. It returns a boolean value after the
evaluation of the condition. Based on the return value either the program will continue
its execution or it will throw an exception. Instead of returning the unused gas, the
assert statement consumes the entire gas supply and the state is then reversed to the
original state. Assert is used to check the current state and function conditions before
the execution of the contract. Below are some cases with assert type exceptions :

• When an assert is called with a condition that results in false.


• When a zero-initialized variable of a function is called.
• When a large or a negative value is converted to an enum.
• When a value is divided or modulo by zero.
• When accessing an array in an index which is too big or negative.
Revert Statement
• This statement is similar to the require statement.
• It does not evaluate any condition and does not depends on any state or
statement.
• It is used to generate exceptions, display errors, and revert the function call.
• This statement contains a string message which indicates the issue related
to the information of the exception.
• Calling a revert statement implies an exception is thrown, the unused gas is
returned and the state reverts to its original state.
• Revert is used to handle the same exception types as require handles, but
with little bit more complex logic.
• pragma solidity ^0.5.0;

• contract Vendor {
• address public seller;
• modifier onlySeller() {
• require(
• msg.sender == seller,
• "Only seller can call this."
• );
• _;
• }
• function sell(uint amount) public payable onlySeller {
• if (amount > msg.value / 2 ether)
• revert("Not enough Ether provided.");
• // Perform the sell operation.
• }
• }

You might also like