Show Menu
Cheatography

Solidity based Ethereum Cheat Sheet by

Code for write Smart Contracts for Ethereum blockchain.

Solidity v.0.5.2­-0.6.0.

#Import files

import "­fil­ena­me";

import * as symbolName from "­fil­ena­me"; or import "­fil­ena­me" as symbol­Name;

import {symbol1 as alias, symbol2} from "­fil­ena­me";

#Types

Boolean

bool : true or false

#Opera­tors:

Logical : ! (logical negation), && (AND), || (OR)
Compar­isons : == (equal­ity), != (inequ­ality)

Integer

Unsigned : uint8 | uint16 | uint32 | uint64 | uint128 | uint25­6(uint)

Signed : int8 | int16 | int32 | int64 | int128 | int256­(int)

#Opera­tors:

Compar­isons: <=, <, ==, !=, >= and >
Bit operators: &, |, ^ (bitwise exclusive or) and ~ (bitwise negation)
Arithmetic operators: +, -, unary -, unary +, , /, %, * (expon­ent­iat­ion), << (left shift) and >> (right shift)

#Address

address: Holds an Ethereum address (20 byte value). address payable : Same as address, but includes additional methods transfer and send

#Opera­tors:

Compar­isons: <=, <, ==, !=, >= and >

#Methods:

balance

<ad­dre­ss>.ba­lance (uint256): balance of the Address in Wei

transfer and send

<ad­dre­ss>.tr­ans­fer­(ui­nt256 amount): send given amount of Wei to Address, throws on failure
<ad­dre­ss>.se­nd(­uint256 amount) returns (bool): send given amount of Wei to Address, returns false on failure

call

<ad­dre­ss>.ca­ll(...) returns (bool): issue low-level CALL, returns false on failure

delega­tecall

<ad­dre­ss>.de­leg­ate­cal­l(...) returns (bool): issue low-level DELEGA­TECALL, returns false on failure

Delega­tecall uses the code of the target address, taking all other aspects (storage, balance, ...) from the calling contract. The purpose of delega­tecall 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 delega­tecall to be used.

contract A {
uint value;
address public sender;
address a = addres­s(0); // address of contract B
function makeDe­leg­ate­Cal­l(uint _value) public {
a.dele­gat­ecall(
abi.en­cod­ePa­cke­d(b­yte­s4(­kec­cak­256­("se­tVa­lue­(ui­nt)­")), _value)
); // Value of A is modified
}
}

contract B {
uint value;
address public sender;
function setVal­ue(uint _value) public {
value = _value;
sender = msg.se­nder; // msg.sender is preserved in delega­tecall. It was not available in callcode.
}
}

gas() option is available for call, callcode and delega­tecall. value() option is not supported for delega­tecall.

callcode

<ad­dre­ss>.ca­llc­ode­(...) returns (bool): issue low-level CALLCODE, returns false on failure

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

#Array

Arrays can be dynamic or have a fixed size.

uint[] dynami­cSi­zeA­rray;

uint[7] fixedS­ize­Array;


Fixed byte arrays

bytes1­(byte), bytes2, bytes3, ..., bytes32.


#Opera­tors:

Compar­isons: <=, <, ==, !=, >=, > (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

.length : read-only

#Dynamic byte arrays

bytes: Dynami­cal­ly-­sized byte array. It is similar to byte[], but it is packed tightly in calldata. Not a value-­type!

string: Dynami­cal­ly-­sized UTF-8-­encoded string. It is equal to bytes but does not allow length or index access. Not a value-­type!
Enum

Enum works just like in every other language.

enum Action­Choices {
GoLeft,
GoRight,
GoStra­ight,
SitStill
}

Action­Choices choice = Action­Cho­ice­s.G­oSt­raight;

#Struct

New types can be declared using struct.

struct Funder {
address addr;
uint amount;
}

Funder funders;

#Mapping

Declared as mappin­g(_­KeyType => _Value­Type)

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

key can be almost any type except for a mapping, a dynami­cally 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 switch and goto.

if else
while
do
for
break
continue
return
? :

#Functions

Structure

function (<p­ara­meter types>) {inter­nal­|ex­ter­nal­|pu­bli­c|p­rivate} [pure|­con­sta­nt|­vie­w|p­ayable] [returns (<r­eturn types>)]

Access modifiers

public - Accessible from this contract, inherited contracts and externally
private - Accessible only from this contract
internal - Accessible only from this contract and contracts inheriting from it
external - Cannot be accessed intern­ally, only extern­ally. Recomm­ended to reduce gas. Access internally with this.f.

#Param­eters

Input parameters

Parameters are declared just like variables and are memory variables.

function f(uint _a, uint _b) {}

Output parameters

Output parameters are declared after the returns keyword

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

Output can also be specified using return statement. In that case, we can omit parameter name returns (uint).

Multiple return types are possible with return (v0, v1, ..., vn).

Constr­uctor

Function that is executed during contract deploy­ment. Defined using the constr­uctor keyword.

contract C {
address owner;
uint status;
constr­uct­or(uint _status) {
owner = msg.se­nder;
status = _status;
}
}

#Function Calls

Internal Function Calls

Functions of the current contract can be called directly (inter­nally - via jumps) and also recurs­ively

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

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

#External Function Calls

this.g(8); and c.g(2); (where c is a contract instance) are also valid function calls, but, the function will be called “exter­nally”, via a message call.

.gas() and .value() 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 access­ible.

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

#Function type

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

pragma solidity ^0.4.18;

contract Oracle {
struct Request {
bytes data;
functi­on(­bytes memory) external callback;
}
Request[] requests;
event NewReq­ues­t(u­int);
function query(­bytes data, functi­on(­bytes memory) external callback) {
reques­ts.p­us­h(R­equ­est­(data, callba­ck));
NewReq­ues­t(r­equ­est­s.l­ength - 1);
}
function reply(uint requestID, bytes response) {
// Here goes the check that the reply comes from a trusted source
reques­ts[­req­ues­tID­].c­all­bac­k(r­esp­onse);
}
}

contract OracleUser {
Oracle constant oracle = Oracle­(0x­123­4567); // known contract
function buySom­eth­ing() {
oracle.qu­ery­("US­D", this.o­rac­leR­esp­onse);
}
function oracle­Res­pon­se(­bytes response) {
requir­e(m­sg.s­ender == addres­s(o­rac­le));
}
}


#Function Modifier

Modifiers can automa­tically check a condition prior to executing the function.

modifier onlyOwner {
requir­e(m­sg.s­ender == owner);
_;
}

function close() onlyOwner {
selfde­str­uct­(ow­ner);
}

#View or Constant Functions

Functions can be declared view or constant 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 view method is not modifying state.

#Pure Functions

Functions can be declared pure 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 Ether are marked as payable 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 new

Contracts can be created from another contract using new 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 Inheri­tance

Solidity supports multiple inheri­tance and polymo­rphism.

contract owned {
function owned() { owner = msg.se­nder; }
address owner;
}

contract mortal is owned {
function kill() {
if (msg.s­ender == owner) selfde­str­uct­(ow­ner);
}
}

contract final is mortal {
function kill() {
super.k­ill(); // Calls kill() of mortal.
}
}

Multiple inheri­tance

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

#Const­ructor of base class

contract A {
uint a;
constr­uct­or(uint _a) { a = _a; }
}

contract B is A(1) {
constr­uct­or(uint _b) A(_b) {
}
}

#Abstract Contracts

Contracts that contain implem­ented and non-im­ple­mented 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

Interfaces are similar to abstract contracts, but they have restri­ctions:

Cannot have any functions implem­ented.
Cannot inherit other contracts or interf­aces.
Cannot define constr­uctor.
Cannot define variables.
Cannot define structs.
Cannot define enums.

pragma solidity ^0.4.11;

interface Token {
function transf­er(­address recipient, uint amount);
}

#Events

Events allow the convenient usage of the EVM logging facili­ties, 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-in­dexed arguments will be stored in the data part of the log.

pragma solidity ^0.4.0;

contract Client­Receipt {
event Deposit(
address indexed _from,
bytes32 indexed _id,
uint _value
);

function deposi­t(b­ytes32 _id) payable {
emit Deposi­t(m­sg.s­ender, _id, msg.va­lue);
}
}

#Library

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

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

contract C {
uint sum;

function f() {
sum = arithm­ati­c.a­dd(2, 3);
}
}

#Using - For

using A for B; 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

assert­(bool condit­ion): throws if the condition is not met - to be used for internal errors.
requir­e(bool condit­ion): throws if the condition is not met - to be used for errors in inputs or external compon­ents.
revert(): abort execution and revert state changes

function sendHa­lf(­address addr) payable returns (uint balance) {
requir­e(m­sg.v­alue % 2 == 0); // Only allow even numbers
uint balanc­eBe­for­eTr­ansfer = this.b­alance;
addr.t­ran­sfe­r(m­sg.v­alue / 2);
assert­(th­is.b­alance == balanc­eBe­for­eTr­ansfer - msg.value / 2);
return this.b­alance;
}

Catching exceptions is not yet possible.

#Global variables

Block variables

block.b­lo­ckh­ash­(uint blockN­umber) returns (bytes32): hash of the given block - only works for the 256 most recent blocks excluding current
block.c­oi­nbase (address): current block miner’s address
block.d­if­ficulty (uint): current block difficulty
block.g­as­limit (uint): current block gaslimit
block.n­umber (uint): current block number
block.t­im­estamp (uint): current block timestamp as seconds since unix epoch
now (uint): current block timestamp (alias for block.t­im­estamp)

#Trans­action variables

msg.data (bytes): complete calldata
msg.gas (uint): remaining gas
msg.sender (address): sender of the message (current call)
msg.sig (bytes4): first four bytes of the calldata (i.e. function identi­fier)
msg.value (uint): number of wei sent with the message
tx.gas­price (uint): gas price of the transa­ction
tx.origin (address): sender of the transa­ction (full call chain)

#Mathe­matical and Crypto­graphic Functions

addmod­(uint x, uint y, uint k) returns (uint): compute (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2**256.
mulmod­(uint x, uint y, uint k) returns (uint): compute (x y) % k where the multip­lic­ation is performed with arbitrary precision and does not wrap around at 2*256.
keccak­256­(...) returns (bytes32): compute the Ethere­um-­SHA-3 (Kecca­k-256) hash of the (tightly packed) arguments
sha256­(...) returns (bytes32): compute the SHA-256 hash of the (tightly packed) arguments
sha3(...) returns (bytes32): alias to keccak256
ripemd­160­(...) returns (bytes20): compute RIPEMD-160 hash of the (tightly packed) arguments
ecreco­ver­(by­tes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address): recover the address associated with the public key from elliptic curve signature or return zero on error (example usage)

#Contract Related

this (current contract’s type): the current contract, explicitly conver­tible to Address
selfde­str­uct­(ad­dress recipi­ent): destroy the current contract, sending its funds to the given Address
suicid­e(a­ddress recipi­ent): alias to selfde­struct. Soon to be deprec­ated.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Blockchain Key Terminologies list - Cheat Sheet