Solidity – Operators ”; Previous Next What is an Operator? Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ”+” is called the operator. Solidity supports the following types of operators. Arithmetic Operators Comparison Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators Lets have a look on all operators one by one. Arithmetic Operators Solidity supports the following arithmetic operators − Assume variable A holds 10 and variable B holds 20, then − Show Example Sr.No. Operator & Description 1 + (Addition) Adds two operands Ex: A + B will give 30 2 – (Subtraction) Subtracts the second operand from the first Ex: A – B will give -10 3 * (Multiplication) Multiply both operands Ex: A * B will give 200 4 / (Division) Divide the numerator by the denominator Ex: B / A will give 2 5 % (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0 6 ++ (Increment) Increases an integer value by one Ex: A++ will give 11 7 — (Decrement) Decreases an integer value by one Ex: A– will give 9 Comparison Operators Solidity supports the following comparison operators − Assume variable A holds 10 and variable B holds 20, then − Show Example Sr.No. Operator & Description 1 = = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true. Ex: (A == B) is not true. 2 != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true. Ex: (A != B) is true. 3 > (Greater than) Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. Ex: (A > B) is not true. 4 < (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true. Ex: (A < B) is true. 5 >= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A >= B) is not true. 6 <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A <= B) is true. Logical Operators Solidity supports the following logical operators − Assume variable A holds 10 and variable B holds 20, then − Show Example Sr.No. Operator & Description 1 && (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B) is true. 2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A || B) is true. 3 ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. Ex: ! (A && B) is false. Bitwise Operators Solidity supports the following bitwise operators − Assume variable A holds 2 and variable B holds 3, then − Show Example Sr.No. Operator & Description 1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2. 2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3. 3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. Ex: (A ^ B) is 1. 4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4. 5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4. 6 >> (Right Shift) Binary Right Shift Operator. The left operand”s value is moved right by the number of bits specified by the right operand. Ex: (A >> 1) is 1. 7 >>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are always zero. Ex: (A >>> 1) is 1. Assignment Operators Solidity supports the following assignment operators − Show Example Sr.No. Operator & Description 1 = (Simple Assignment ) Assigns values from the right side operand to the left side operand Ex: C = A + B will assign the value of A + B into C 2 += (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. Ex: C += A is equivalent to C = C + A 3 −= (Subtract and Assignment) It subtracts the right operand from the left operand and assigns the result to the left operand. Ex: C -= A is equivalent to C = C – A 4 *= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the left operand. Ex: C *= A is equivalent to C = C * A 5 /= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left operand. Ex: C /= A is equivalent to C = C / A 6 %= (Modules and Assignment) It takes modulus using
Category: solidity
Solidity – Mappings
Solidity – Mapping ”; Previous Next Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type. mapping(_KeyType => _ValueType) Where _KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed. _ValueType − can be any type. Considerations Mapping can only have type of storage and are generally used for state variables. Mapping can be marked public. Solidity automatically create getter for it. Example Try the following code to understand how the mapping type works in Solidity. 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)); } } Run the above program using steps provided in Solidity First Application chapter. First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as − Output { “0”: “uint256: 10″ } Print Page Previous Next Advertisements ”;
Solidity – Structs
Solidity – Structs ”; Previous Next Struct types are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID Defining a Struct To define a Struct, you must use the struct keyword. The struct keyword defines a new data type, with more than one member. The format of the struct statement is as follows − struct struct_name { type1 type_name_1; type2 type_name_2; type3 type_name_3; } Example struct Book { string title; string author; uint book_id; } Accessing a Struct and its variable To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the struct to define variables of structure type. The following example shows how to use a structure in a program. Example Try the following code to understand how the structs works in Solidity. 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; } } Run the above program using steps provided in Solidity First Application chapter. First Click setBook Button to set the value as LARGE then click getBookId to get the selected book id. Output uint256: 1 Print Page Previous Next Advertisements ”;
Solidity – Enums
Solidity – Enums ”; Previous Next Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large. Example Try the following code to understand how the enum works in Solidity. 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); } } Run the above program using steps provided in Solidity First Application chapter. First Click setLarge Button to set the value as LARGE then click getChoice to get the selected choice. Output uint8: 2 Click getDefaultChoice Button to get the default choice. Output uint256: 1 Print Page Previous Next Advertisements ”;
Solidity – Basic Syntax
Solidity – Basic Syntax ”; Previous Next 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; } } 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. A pragma directive is always local to a source file and if you import 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 ^. Contract A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereumblockchain. The line uintstoredData declares a state variable called storedData of type 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”. 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 Print Page Previous Next Advertisements ”;
Solidity – Variables
Solidity – Variables ”; Previous Next 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 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 } } Local Variable Variables whose values are available only within a function where it is defined. Function parameters are always local to that function. 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 } } Example 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 } } Run the above program using steps provided in Solidity First Application chapter. Output 0: uint256: 10 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) returns (bytes32) Hash of the given block – only 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 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. Print Page Previous Next Advertisements ”;
Solidity – Overview
Solidity – Overview ”; Previous Next 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. You can use Solidity to create contracts for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets. What is Ethereum? Ethereum is a decentralized ie. blockchain platform that runs smart contracts i.e. applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference. The Ethereum Virtual 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 code by computers all over the world. The EVM specialised 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 is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. 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. It is fine if you do not understand Smart Contract right now, we will go into more detail later. Print Page Previous Next Advertisements ”;
Solidity – Home
Solidity Tutorial Quick Guide Resources Job Search Discussion 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). Audience This tutorial targets novice developers and those new to Solidity. It guides them in understanding basic through more advanced concepts in Solidity. After completing this tutorial, your firm foundation in Solidity and level of expertise will allow you to begin developing and easily build on your knowledge. Prerequisites The tutorial assumes your familiarity with blockchain, and general programming. Print Page Previous Next Advertisements ”;
Solidity – First Application
Solidity – First Application ”; Previous Next 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; } } Step 2 − Under Compile Tab, 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 Print Page Previous Next Advertisements ”;
Solidity – Variable Scope
Solidity – Variable Scope ”; Previous Next 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. 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; } } 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 } } Print Page Previous Next Advertisements ”;