Solidity – Abstract Contracts ”; Previous Next Abstract Contract is one which contains at least one function without any implementation. Such a contract is used as a base contract. Generally an abstract contract contains both implemented as well as abstract functions. Derived contract will implement the abstract function and use the existing functions as and when required. In case, a derived contract is not implementing the abstract function then this derived contract will be marked as abstract. Example Try the following code to understand how the abstract contracts works in Solidity. pragma solidity ^0.5.0; contract Calculator { function getResult() public view returns(uint); } contract Test is Calculator { function getResult() public view returns(uint) { uint a = 1; uint b = 2; uint result = a + b; return result; } } Run the above program using steps provided in Solidity First Application chapter. Output 0: uint256: 3 Print Page Previous Next Advertisements ”;
Category: solidity
Solidity – Style Guide
Solidity – Style Guide ”; Previous Next Style Guide helps to maintain code layout consistent and make code more readable. Following are the best practices following while writing contracts with Solidity. Code Layout Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs. Two Blank Lines Rule − Use 2 Blank lines between two contract definitions. pragma solidity ^0.5.0; contract LedgerBalance { //… } contract Updater { //… } One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines. pragma solidity ^0.5.0; contract A { function balance() public pure; function account() public pure; } contract B is A { function balance() public pure { // … } function account() public pure { // … } } Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code. Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one. function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); variable = function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); event multipleArguments( address sender, address recipient, uint256 publicKey, uint256 amount, bytes32[] options ); MultipleArguments( sender, recipient, publicKey, amount, options ); Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably. Imports − Import statements should be placed at the top of the file just after pragma declaration. Order of Functions − Functions should be grouped as per their visibility. pragma solidity ^0.5.0; contract A { constructor() public { // … } function() external { // … } // External functions // … // External view functions // … // External pure functions // … // Public functions // … // Internal functions // … // Private functions // … } Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace. pragma solidity ^0.5.0; contract Coin { struct Bank { address owner; uint balance; } } if (x < 3) { x += 1; } else if (x > 7) { x -= 1; } else { x = 5; } if (x < 3) x += 1; else x -= 1; Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. function kill() public onlyowner { selfdestruct(owner); } Mappings − Avoid whitespaces while declaring mapping variables. mapping(uint => uint) map; mapping(address => bool) registeredAddresses; mapping(uint => mapping(bool => Data[])) public data; mapping(uint => mapping(uint => s)) data; Variable declaration − Avoid whitespaces while declaring array variables. uint[] x; // not unit [] x; String declaration − Use double quotes to declare a string instead of single quote. str = “foo”; str = “Hamlet says, ”To be or not to be…””; Order of Layout Elements should be layout in following order. Pragma statements Import statements Interfaces Libraries Contracts Within Interfaces, libraries or contracts the order should be as − Type declarations State variables Events Functions Naming conventions Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc. Contract and Library name should match their file names. In case of multiple contracts/libraries in a file, use name of core contract/library. Owned.sol pragma solidity ^0.5.0; // Owned.sol contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { //…. } function transferOwnership(address newOwner) public onlyOwner { //… } } Congress.sol pragma solidity ^0.5.0; // Congress.sol import “./Owned.sol”; contract Congress is Owned, TokenRecipient { //… } Struct Names − Use CapWords Style like SmartCoin. Event Names − Use CapWords Style like Deposit, AfterTransfer. Function Names − Use mixedCase Style like initiateSupply. Local and State variables − Use mixedCase Style like creatorAddress, supply. Constants − Use all capital letters with underscore to seperate words like MAX_BLOCKS. Modifier Names − Use mixCase Style like onlyAfter. Enum Names − Use CapWords Style like TokenGroup. Print Page Previous Next Advertisements ”;
Solidity – Comments
Solidity – Comments ”; Previous Next 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++ /* * 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; } Print Page Previous Next Advertisements ”;
Solidity – Strings
Solidity – Strings ”; Previous Next Solidity supports String literal using both double quote (“) and single quote (”). It provides string as a data type to declare a variable of type String. pragma solidity ^0.5.0; contract SolidityTest { string data = “test”; } In above example, “test” is a string literal and data is a string variable. More preferred way is to use byte types instead of String as string operation requires more gas as compared to byte operation. Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32 literal. pragma solidity ^0.5.0; contract SolidityTest { bytes32 data = “test”; } Escape Characters Sr.No. Character & Description 1 n Starts a new line. 2 \ Backslash 3 ” Single Quote 4 “ Double Quote 5 b Backspace 6 f Form Feed 7 r Carriage Return 8 t Tab 9 v Vertical Tab 10 xNN Represents Hex value and inserts appropriate bytes. 11 uNNNN Represents Unicode value and inserts UTF-8 sequence. Bytes to String Conversion Bytes can be converted to String using string() constructor. bytes memory bstr = new bytes(10); string message = string(bstr); Example Try the following code to understand how the string works in Solidity. 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; 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); } } Run the above program using steps provided in Solidity First Application chapter. Output 0: string: 3 Print Page Previous Next Advertisements ”;
Solidity – Environment Setup
Solidity – Environment Setup ”; Previous Next This chapter 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 # 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. 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 commandlineinterfaceVersion: 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. Print Page Previous Next Advertisements ”;
Solidity – Quick Guide
Solidity – Quick Guide ”; Previous Next Solidity – Overview 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. Solidity – Environment Setup This chapter 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 # 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. 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 commandlineinterfaceVersion: 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 – 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; } } 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 Solidity – First Application We”re using Remix IDE to
Solidity – Inheritance
Solidity – Inheritance ”; Previous Next 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. Example pragma solidity ^0.5.0; contract C { //private state variable uint private data; //public state variable uint public info; //constructor constructor() public { info = 10; } //private function function increment(uint a) private pure returns(uint) { return a + 1; } //public function function updateData(uint a) public { data = a; } function getData() public view returns(uint) { return data; } function compute(uint a, uint b) internal pure returns (uint) { return a + b; } } //Derived Contract contract E is C { uint private result; C private c; constructor() public { c = new C(); } function getComputedResult() public { result = compute(3, 5); } function getResult() public view returns(uint) { return result; } function getData() public view returns(uint) { return c.info(); } } Run the above program using steps provided in Solidity First Application chapter. Run various method of Contracts. For E.getComputedResult() followed by E.getResult() shows − Output 0: uint256: 8 Print Page Previous Next Advertisements ”;
Solidity – Restricted Access
Solidity – Restricted Access ”; Previous Next Restricted Access to a Contract is a common practice. By Default, a contract state is read-only unless it is specified as public. We can restrict who can modify the contract”s state or call a contract”s functions using modifiers. We will create and use multiple modifiers as explained below − onlyBy − once used on a function then only the mentioned caller can call this function. onlyAfter − once used on a function then that function can be called after certain time period. costs − once used on a function then caller can call this function only if certain value is provided. Example pragma solidity ^0.5.0; contract Test { address public owner = msg.sender; uint public creationTime = now; modifier onlyBy(address _account) { require( msg.sender == _account, “Sender not authorized.” ); _; } function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; } modifier onlyAfter(uint _time) { require( now >= _time, “Function called too early.” ); _; } function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) { delete owner; } modifier costs(uint _amount) { require( msg.value >= _amount, “Not enough Ether provided.” ); _; if (msg.value > _amount) msg.sender.transfer(msg.value – _amount); } function forceOwnerChange(address _newOwner) public payable costs(200 ether) { owner = _newOwner; if (uint(owner) & 0 == 1) return; } } Print Page Previous Next Advertisements ”;
Solidity – View Functions
Solidity – View Functions ”; Previous Next 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. Getter method are by default view functions. See the example below using a view function. Example pragma solidity ^0.5.0; contract Test { function getResult() public view returns(uint product, uint sum){ uint a = 1; // local variable uint b = 2; product = a * b; sum = a + b; } } Run the above program using steps provided in Solidity First Application chapter. Output 0: uint256: product 2 1: uint256: sum 3 Print Page Previous Next Advertisements ”;
Solidity – Arrays
Solidity – Arrays ”; Previous Next 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. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index. In Solidity, an array can be of compile-time fixed size or of dynamic size. For storage array, it can have different types of elements as well. In case of memory array, element type can not be mapping and in case it is to be used as function parameter then element type should be an ABI type. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array of fixed size in Solidity, the programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid Solidity data type. For example, to declare a 10-element array called balance of type uint, use this statement − uint balance[10]; To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows − type[] arrayName; Initializing Arrays You can initialize Solidity array elements either one by one or using a single statement as follows − uint balance[3] = [1, 2, 3]; The number of values between braces [ ] can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array − If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − uint balance[] = [1, 2, 3]; You will create exactly the same array as you did in the previous example. balance[2] = 5; The above statement assigns element number 3rd in the array a value of 5. Creating dynamic memory arrays Dynamic memory arrays are created using new keyword. uint size = 3; uint balance[] = new uint[](size); Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − uint salary = balance[2]; The above statement will take 3rd element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − Members length − length returns the size of the array. length can be used to change the size of dynamic array be setting it. push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array. Example Try the following code to understand how the arrays works in Solidity. 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); } } Print Page Previous Next Advertisements ”;