Solidity – Function Modifiers ”; Previous Next Function Modifiers are used to modify the behaviour of a function. For example to add a prerequisite to a function. First we create a modifier with or without parameter. contract Owner { modifier onlyOwner { require(msg.sender == owner); _; } modifier costs(uint price) { if (msg.value >= price) { _; } } } The function body is inserted where the special symbol “_;” appears in the definition of a modifier. So if condition of modifier is satisfied while calling this function, the function is executed and otherwise, an exception is thrown. See the example below − pragma solidity ^0.5.0; contract Owner { address owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier costs(uint price) { if (msg.value >= price) { _; } } } contract Register is Owner { mapping (address => bool) registeredAddresses; uint price; constructor(uint initialPrice) public { price = initialPrice; } function register() public payable costs(price) { registeredAddresses[msg.sender] = true; } function changePrice(uint _price) public onlyOwner { price = _price; } } Print Page Previous Next Advertisements ”;
Category: Computer Programming
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 – Loops
Solidity – Loops ”; Previous Next While writing a contract, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines. Solidity supports all the necessary loops to ease down the pressure of programming. Sr.No Loops & Description 1 While Loop The most basic loop in Solidity is the while loop which would be discussed in this chapter. 2 do…while Loop The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. 3 For Loop The for loop is the most compact form of looping. It includes the following three important parts. 4 Loop Control Solidity provides full control to handle loops and switch statements. Print Page Previous Next Advertisements ”;
Solidity – Operators
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
Scala Collections – Quick Guide ”; Previous Next Scala Collections – Overview Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items. For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones. This chapter throws light on the most commonly used collection types and most frequently used operations over those collections. Sr.No Collections with Description 1 Scala Lists Scala”s List[T] is a linked list of type T. 2 Scala Sets A set is a collection of pairwise different elements of the same type. 3 Scala Maps A Map is a collection of key/value pairs. Any value can be retrieved based on its key. 4 Scala Tuples Unlike an array or list, a tuple can hold objects with different types. 5 Scala Options Option[T] provides a container for zero or one element of a given type. 6 Scala Iterators An iterator is not a collection, but rather a way to access the elements of a collection one by one. Scala Collections – Environment Setup Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java -version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java -version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.8.0_31 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.8.0_31bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ”scala-2.13.1-installer.jar”. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java -jar scala-2.13.1-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java -jar scala-2.13.1-installer.jar Output − Welcome to the installation of Scala 2.13.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the following − Platform Command Output Windows >scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc. Linux $scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc.tut
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 ”;
Scala Collections – flatMap
Scala Collections – FlatMap Method ”; Previous Next flatMap() method is method of TraversableLike trait, it takes a predicate, applies it to each element of the collection and returns a new collection of elements returned by the predicate. Syntax The following is the syntax of flatMap method. def flatMap[B](f: (A) ? GenTraversableOnce[B]): TraversableOnce[B] Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition. Usage Below is an example program of showing how to use flatMap method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 5, 10) //apply operation val result = list.flatMap{x => List(x,x+1)} //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(1, 2, 5, 6, 10, 11) Print Page Previous Next Advertisements ”;