Solidity – Types

Solidity – Types ”; Previous Next 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. Value 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 Numbers fixed/unfixed Signed and unsigned fixed point numbers of varying sizes. Fixed Point Numbers fixed/unfixed Signed and unsigned fixed point numbers of varying sizes. Fixed Point Numbers fixedMxN Signed fixed point number where M represents 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. fixed is same as fixed128x18. Fixed Point Numbers ufixedMxN Unsigned fixed point number where M represents 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. ufixed is same as ufixed128x18. 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. 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); Print Page Previous Next Advertisements ”;

Solidity – Assembly

Solidity – Assembly ”; Previous Next Solidity provides an option to use assembly language to write inline assembly within Solidity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it converts the Solidity code into a Standalone Assembly and then to byte code. We can used the same language used in Inline Assembly to write code in a Standalone assembly. Inline Assembly Inline assembly code can be interleaved within Solidity code base to have more fine-grain control over EVM and is used especially while writing the library functions. An assembly code is written under assembly { … } block. Example Try the following code to understand how a Library works in Solidity. pragma solidity ^0.5.0; library Sum { function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint o_sum) { for (uint i = 0; i < _data.length; ++i) { assembly { o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20)))) } } } } contract Test { uint[] data; constructor() public { data.push(1); data.push(2); data.push(3); data.push(4); data.push(5); } function sum() external view returns(uint){ return Sum.sumUsingInlineAssembly(data); } } Run the above program using steps provided in Solidity First Application chapter. Note − Select Test from dropdown before clicking the deploy button. Output 0: uint256: 15 Print Page Previous Next Advertisements ”;

Solidity – Useful Resources

Solidity – Useful Resources ”; Previous Next The following resources contain additional information on Solidity. Please use them to get more in-depth knowledge on this. Useful Links on Solidity Solidity − Official Website of Solidity and Documentation Solidity Wiki − Wikipedia Reference for Solidity Remix IDE − On-line IDE for Solidity Compilation and Execution To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Solidity – Events

Solidity – Events ”; Previous Next Event is an inheritable member of a contract. An event is emitted, it stores the arguments passed in transaction logs. These logs are stored on blockchain and are accessible using address of the contract till the contract is present on the blockchain. An event generated is not accessible from within contracts, not even the one which have created and emitted them. An event can be declared using event keyword. //Declare an Event event Deposit(address indexed _from, bytes32 indexed _id, uint _value); //Emit an event emit Deposit(msg.sender, _id, msg.value); Example Try the following code to understand how an event works in Solidity. First Create a contract and emit an event. pragma solidity ^0.5.0; contract Test { event Deposit(address indexed _from, bytes32 indexed _id, uint _value); function deposit(bytes32 _id) public payable { emit Deposit(msg.sender, _id, msg.value); } } Then access the contract”s event in JavaScript code. var abi = /* abi as generated using compiler */; var ClientReceipt = web3.eth.contract(abi); var clientReceiptContract = ClientReceipt.at(“0x1234…ab67” /* address */); var event = clientReceiptContract.Deposit(function(error, result) { if (!error)console.log(result); }); It should print details similar to as following − Output { “returnValues”: { “_from”: “0x1111…FFFFCCCC”, “_id”: “0x50…sd5adb20”, “_value”: “0x420042” }, “raw”: { “data”: “0x7f…91385”, “topics”: [“0xfd4…b4ead7”, “0x7f…1a91385″] } } Print Page Previous Next Advertisements ”;

Solidity – Discussion

Discuss Solidity ”; 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). Print Page Previous Next Advertisements ”;

Mathematical Functions

Solidity – Mathematical Functions ”; Previous Next Solidity provides inbuilt mathematical functions as well. Following are heavily used methods − addmod(uint x, uint y, uint k) returns (uint) − computes (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2256. mulmod(uint x, uint y, uint k) returns (uint) − computes (x * y) % k where the addition is performed with arbitrary precision and does not wrap around at 2256. Following example shows the usage of mathematical functions in Solidity. Example pragma solidity ^0.5.0; contract Test { function callAddMod() public pure returns(uint){ return addmod(4, 5, 3); } function callMulMod() public pure returns(uint){ return mulmod(4, 5, 3); } } Run the above program using steps provided in Solidity First Application chapter. Click callAddMod button first and then callMulMod button to see the result. Output 0: uint256: 0 0: uint256: 2 Print Page Previous Next Advertisements ”;

Solidity – Error Handling

Solidity – Error Handling ”; Previous Next 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. Example Try the following code to understand how error handling works in Solidity. 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. } } When revert is called, it will return the hexadecimal data as followed. Output 0x08c379a0 // Function selector for Error(string) 0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset 0x000000000000000000000000000000000000000000000000000000000000001a // String length 0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data Print Page Previous Next Advertisements ”;

Solidity – Pure Functions

Solidity – Pure Functions ”; Previous Next 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. See the example below using a view function. Example 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; } } 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 – Functions

Solidity – Functions ”; Previous Next 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. This section explains how to write your own functions in Solidity. 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 The basic syntax is shown here. function function-name(parameter-list) scope returns() { //statements } Example Try the following example. It defines a function called getResult that takes no parameters − 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; } } 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. 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);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. Output 0: string: 3 Function Parameters Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma. Example Try the following example. We have used a uint2str function here. It takes one parameter. 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);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. Output 0: string: 3 The return Statement A Solidity function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. As in above example, we are using uint2str function to return a string. In Solidity, a function can return multiple values as well. See the example below − 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; //alternative return statement to return //multiple values //return(a*b, 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 – Contracts

Solidity – Contracts ”; Previous Next 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. 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; } } //External Contract contract D { function readData() public returns(uint) { C c = new C(); c.updateData(7); return c.getData(); } } //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 ”;