Solidity Fast Learning…

This document is for Solidity that you can use to write Smart Contracts for Ethereum based blockchain.

This guide is not intended to teach you Solidity from the ground up, but to help developers with basic knowledge who may struggle to get familiar with Smart Contracts and Blockchain because of the Solidity concepts used.

Version pragma

will compile with a compiler version >= 0.4.21 and < 0.5.0.

Import files

or

Types

Boolean

: or

Operators:

  • Logical : (logical negation), (AND), (OR)
  • Comparisons : (equality), (inequality)

Integer

Unsigned :

Signed :

Operators:

  • Comparisons: , , , , and
  • Bit operators: , , (bitwise exclusive or) and (bitwise negation)
  • Arithmetic operators: , , unary , unary , , , , (exponentiation), (left shift) and (right shift)

Address

: Holds an Ethereum address (20 byte value).

Operators:

  • Comparisons: , , , , and

Methods:

balance

  • : balance of the Address in Wei

transfer and send

  • : send given amount of Wei to Address, throws on failure
  • : send given amount of Wei to Address, returns false on failure

call

  • : issue low-level CALL, returns false on failure

delegatecall

  • : issue low-level DELEGATECALL, returns false on failure

Delegatecall uses the code of the target address, taking all other aspects (storage, balance, …) from the calling contract. The purpose of delegatecall is to use library code which is stored in another contract. The user has to ensure that the layout of storage in both contracts is suitable for delegatecall to be used.

contract A {
uint value;
address public sender;
address a = "0x"; // address of contract B
function makeDelegateCall(uint _value) {
a.delegatecall(bytes4(keccak256("setValue(uint)")), _value); // Value of A is modified
}
}

contract B {
uint value;
address public sender;
setValue(uint _value) {
value = _value;
sender = msg.sender; // msg.sender is preserved in delegatecall. It was not available in callcode.
}
}

gas() option is available for call, callcode and delegatecall. value() option is not supported for delegatecall.

callcode

  • : issue low-level CALLCODE, returns false on failure

Prior to homestead, only a limited variant called was available that did not provide access to the original and values.

Array

Arrays can be dynamic or have a fixed size.

uint[] dynamicSizeArray;uint[7] fixedSizeArray;

Fixed byte arrays

, , , ..., .

Operators:

Comparisons: , , , , , (evaluate to bool) Bit operators: , , (bitwise exclusive or), (bitwise negation), (left shift), (right shift) Index access: If x is of type bytesI, then x[k] for 0 <= k < I returns the k th byte (read-only).

Members

  • : read-only

Dynamic byte arrays

: Dynamically-sized array. It is similar to , but it is packed tightly in calldata. Not a value-type!

: Dynamically-sized UTF-8-encoded string. It is equal to but does not allow length or index access. Not a value-type!

Enum

Enum works just like in every other language.

enum ActionChoices { 
GoLeft,
GoRight,
GoStraight,
SitStill
}
ActionChoices choice = ActionChoices.GoStraight;

Struct

New types can be declared using struct.

struct Funder {
address addr;
uint amount;
}
Funder funders;

Mapping

Declared as

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value.

key can be almost any type except for a mapping, a dynamically sized array, a contract, an enum, or a struct. value can actually be any type, including mappings.

Control Structures

Most of the control structures from JavaScript are available in Solidity except for and .

Functions

Structure

Access modifiers

  • - Accessible from this contract, inherited contracts and externally
  • - Accessible only from this contract
  • - Accessible only from this contract and contracts inheriting from it
  • - Cannot be accessed internally, only externally. Recommended to reduce gas. Access internally with .

Parameters

Input parameters

Parameters are declared just like variables and are variables.

function f(uint _a, uint _b) {}

Output parameters

Output parameters are declared after the keyword

function f(uint _a, uint _b) returns (uint _sum) {
_sum = _a + _b;
}

Output can also be specified using statement. In that case, we can omit parameter name .

Multiple return types are possible with .

Constructor

Function that is executed during contract deployment. Defined using the keyword.

contract C {
address owner;
uint status;
constructor(uint _status) {
owner = msg.sender;
status = _status;
}
}

Function Calls

Internal Function Calls

Functions of the current contract can be called directly (internally — via jumps) and also recursively

contract C {
function funA() returns (uint) {
return 5;
}

function FunB(uint _a) returns (uint ret) {
return funA() + _a;
}
}

External Function Calls

and (where c is a contract instance) are also valid function calls, but, the function will be called “externally”, via a message call.

and can also be used with external function calls.

Named Calls

Function call arguments can also be given by name in any order as below.

function f(uint a, uint b) {  }function g() {
f({b: 1, a: 2});
}

Unnamed function parameters

Parameters will be present on the stack, but are not accessible.

function f(uint a, uint) returns (uint) {
return a;
}

Function type

Pass function as a parameter to another function. Similar to and

pragma solidity ^0.4.18;contract Oracle {
struct Request {
bytes data;
function(bytes memory) external callback;
}
Request[] requests;
event NewRequest(uint);
function query(bytes data, function(bytes memory) external callback) {
requests.push(Request(data, callback));
NewRequest(requests.length - 1);
}
function reply(uint requestID, bytes response) {
// Here goes the check that the reply comes from a trusted source
requests[requestID].callback(response);
}
}
contract OracleUser {
Oracle constant oracle = Oracle(0x1234567); // known contract
function buySomething() {
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(bytes response) {
require(msg.sender == address(oracle));
}
}

Function Modifier

Modifiers can automatically check a condition prior to executing the function.

modifier onlyOwner {
require(msg.sender == owner);
_;
}
function close() onlyOwner {
selfdestruct(owner);
}

View or Constant Functions

Functions can be declared or in which case they promise not to modify the state, but can read from them.

function f(uint a) view returns (uint) {
return a * b; // where b is a storage variable
}

The compiler does not enforce yet that a method is not modifying state.

Pure Functions

Functions can be declared in which case they promise not to read from or modify the state.

function f(uint a) pure returns (uint) {
return a * 42;
}

Payable Functions

Functions that receive are marked as function.

Fallback Function

A contract can have exactly one unnamed function. This function cannot have arguments and cannot return anything. It is executed on a call to the contract if none of the other functions match the given function identifier (or if no data was supplied at all).

function() {
// Do something
}

Contracts

Creating contracts using

Contracts can be created from another contract using keyword. The source of the contract has to be known in advance.

contract A {
function add(uint _a, uint _b) returns (uint) {
return _a + _b;
}
}
contract C {
address a;
function f(uint _a) {
a = new A();
}
}

Contract Inheritance

Solidity supports multiple inheritance and polymorphism.

contract owned {
function owned() { owner = msg.sender; }
address owner;
}
contract mortal is owned {
function kill() {
if (msg.sender == owner) selfdestruct(owner);
}
}
contract final is mortal {
function kill() {
super.kill(); // Calls kill() of mortal.
}
}

Multiple inheritance

contract A {}
contract B {}
contract C is A, B {}

Constructor of base class

contract A {
uint a;
constructor(uint _a) { a = _a; }
}
contract B is A(1) {
constructor(uint _b) A(_b) {
}
}

Abstract Contracts

Contracts that contain implemented and non-implemented functions. Such contracts cannot be compiled, but they can be used as base contracts.

pragma solidity ^0.4.0;contract A {
function C() returns (bytes32);
}
contract B is A {
function C() returns (bytes32) { return "c"; }
}

Interface

are similar to abstract contracts, but they have restrictions:

  • Cannot have any functions implemented.
  • Cannot inherit other contracts or interfaces.
  • Cannot define constructor.
  • Cannot define variables.
  • Cannot define structs.
  • Cannot define enums.
pragma solidity ^0.4.11;interface Token {
function transfer(address recipient, uint amount);
}

Events

Events allow the convenient usage of the EVM logging facilities, which in turn can be used to “call” JavaScript callbacks in the user interface of a dapp, which listen for these events.

Up to three parameters can receive the attribute indexed, which will cause the respective arguments to be searched for.

All non-indexed arguments will be stored in the data part of the log.

pragma solidity ^0.4.0;contract ClientReceipt {
event Deposit(
address indexed _from,
bytes32 indexed _id,
uint _value
);
function deposit(bytes32 _id) payable {
emit Deposit(msg.sender, _id, msg.value);
}
}

Library

Libraries are similar to contracts, but they are deployed only once at a specific address, and their code is used with ().

library arithmatic {
function add(uint _a, uint _b) returns (uint) {
return _a + _b;
}
}
contract C {
uint sum;
function f() {
sum = arithmatic.add(2, 3);
}
}

Using — For

can be used to attach library functions to any type.

library arithmatic {
function add(uint _a, uint _b) returns (uint) {
return _a + _b;
}
}
contract C {
using arithmatic for uint;

uint sum;
function f(uint _a) {
sum = _a.add(3);
}
}

Error Handling

  • : throws if the condition is not met - to be used for internal errors.
  • : throws if the condition is not met - to be used for errors in inputs or external components.
  • : abort execution and revert state changes
function sendHalf(address addr) payable returns (uint balance) {
require(msg.value % 2 == 0); // Only allow even numbers
uint balanceBeforeTransfer = this.balance;
addr.transfer(msg.value / 2);
assert(this.balance == balanceBeforeTransfer - msg.value / 2);
return this.balance;
}

Catching exceptions is not yet possible.

Global variables

Block variables

  • : hash of the given block - only works for the 256 most recent blocks excluding current
  • : current block miner’s address
  • : current block difficulty
  • : current block gaslimit
  • : current block number
  • : current block timestamp as seconds since unix epoch
  • : current block timestamp (alias for )

Transaction variables

  • : complete calldata
  • : remaining gas
  • : sender of the message (current call)
  • : first four bytes of the calldata (i.e. function identifier)
  • : number of wei sent with the message
  • : gas price of the transaction
  • : sender of the transaction (full call chain)

Mathematical and Cryptographic Functions

  • : compute (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2**256.
  • : compute (x * y) % k where the multiplication is performed with arbitrary precision and does not wrap around at 2**256.
  • : compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments
  • : compute the SHA-256 hash of the (tightly packed) arguments
  • : alias to keccak256
  • : compute RIPEMD-160 hash of the (tightly packed) arguments
  • : recover the address associated with the public key from elliptic curve signature or return zero on error (example usage)

Contract Related

  • : the current contract, explicitly convertible to Address
  • : destroy the current contract, sending its funds to the given Address
  • : alias to selfdestruct. Soon to be deprecated.