Solidity

Solidity Cheatsheet

Solidity Cheatsheet Main Tips

  • This Solidity tutorial contains a cheatsheet with tips, tricks and references you can use to speed up development of contracts.
  • Additionally, this tutorial contains some information about things that have not been mentioned in tutorials prior to this.

Solidity Cheatsheet Tips and Tricks

  • To delete all elements on an array, use delete on it.
  • For struct elements, you should use shorter types, as well as sorting them so that short types would be grouped together. By doing this, you can decrease the gas costs, by combining multiple SSTORE operations into one. (SSTORE costs 5000 or 20000 gas, making it worth optimizing to decrease costs). The gas price estimator, along with the optimizer enabled, can help you check too!
  • By making the state variables of your contracts public, you have your compiler create getters automatically
  • In case you tend to check conditions on input, or make a lot of statements at the beginning of your functions, try Function Modifiers to make the job easier.
  • If there is a function called send in your contract, but you would like to use the built-in send function as well, you can access it via address(contractVar).send(amount)
  • Storage structs can be initialized using a single assignment, for example: myId = myStruct({x: 2,y: 4});

Solidity Cheatsheet Order of Precedence of Operators

The following is the order of precedence for operators, listed in order of evaluation.

These operators go first in the order of precedence:

  • Parentheses
  • Member access
  • New Expression
  • Array subscripting
  • Postfix decrement and increment
  • Function-like call

After these operators, the following are considered:

  • Logical NOT
  • Bitwise NOT
  • Unary minus and plus
  • Unary operations
  • Prefix decrement and increment

Here’s a list of operators that go after these first two levels of precedence.

The operators are presented in an order from those higher in the order of precedence, to those that are lower:

  • Exponentiation
  • Multiplication, modulo and division
  • Substraction and addition
  • Bitwise shift operator
  • Bitwise AND
  • Bitwise XOR
  • Bitwise OR
  • Inequality operator
  • Equality operator
  • Logical AND
  • Logical OR
  • Ternary operator
  • Assignment operators
  • Comma operator

 


Solidity Cheatsheet Global Variables

  • block.blockhash(uint numberOfBlock) returns (bytes32): hash which belongs to the given block – will only work for 256 of the most recent blocks, not including current
  • block.difficulty (uint): difficulty of the current block
  • block.coinbase (address): miner’s address of the current block
  • block.number (uint): number of the current block
  • block.gaslimit (uint): gaslimit of the current block
  • block.timestamp (uint): timestamp of the current block as seconds passed since the unix epoch
  • msg.gas (uint): gas that remains
  • msg.data (bytes): complete calldata
  • msg.value (uint): amount of wei which was sent along with the message
  • msg.sender (address): message sender (current call)
  • msg.sig (bytes4): calldata’s first four bytes (i.e. function identifier)
  • now (uint): timestamp of the current block (alias for block.timestamp)
  • tx.origin (address): sender of the transaction (whole call chain)
  • assert(bool condition): execution abort and state change revert whether condition is false or not (used for internal errors)
  • require(bool condition): execution abort and revert state change revert whether condition is false or not (used for malformed inputs or errors in external components)
  • revert(): execution abort and state change revert
  • keccak256(…) returns (bytes32): computes the Ethereum-SHA-3 (similar to Keccak-256) hash associated with the (tightly packed) arguments
  • sha3(…) returns (bytes32): alias for keccak256
  • sha256(…) returns (bytes32): computes the SHA-256 (tightly packed) argument hash
  • ripemd160(…) returns (bytes20): computes the RIPEMD-160(tightly packed) argument hash
  • ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) returns (address): recovers the address linked with the public key of the elliptic curve signature, if an error occurs, zero is returned
  • addmod(uint a, uint b, uint k) returns (uint): computes (a + b) % k in case the addition gets executed using arbitrary precision, thus not wrapping around 2**256
  • mulmod(uint a, uint b, uint k) returns (uint): computes (a * b) % k in case the multiplication gets executed using arbitrary precision, thus not wrapping around 2**256
  • this (type of the current contract): the current contract that is explicitly convertible to address
  • super: contract that is higher by one level in the inheritance hierarchy
  • selfdestruct(address recipient): destroys the contract that it is stated in, sending the funds that were in the destroyed contract to the specified address
  • suicide(address recipient): alias for selfdestruct
  • <address>.balance (uint256): returns balance of a specified Address in Wei
  • <address>.send(uint256 amount) returns (bool): sends specified number of Wei to the Address, on failure will return false
  • <address>.transfer(uint256 amount): send specified number of Wei to Address, on failure will throw

 


Solidity Cheatsheet Function Visibility Specifiers

function functionName() <visibility specifier> returns (bool) { return true; }
  • public: externally and internally visible (will create a getter function in case of storage/state variables)
  • private: visible inside the current contract exclusively
  • external: visible externally exclusively (for use on functions only) – i.e. may only be message-called (using this.functionName)
  • internal: visible exclusivley internally

 


Solidity Cheatsheet Modifiers

  • pure for functions: Does not allow modifying or access of state – not enforced yet.
  • view for functions: Does not allow modifying of state – not enforced yet.
  • payable for functions: Allow function to receive Ether via calls.
  • constant for state variables: Does not allow assignment (except initialization), will not occupy storage slot.
  • constant for functions: Similar to the view modifier.
  • anonymous for events: No event signature storage as topic.
  • indexed for event parameters: Store parameter as topic.

Solidity Cheatsheet Reserved Keywords

The keywords in the list below are reserved keywords, meaning that they cannot be used as identifier.

Those that do not do anything yet are planned to be integrated into the syntax in the future:

  • abstract,
  • case,
  • after,
  • catch,
  • final,
  • default,
  • in,
  • let,
  • inline,
  • match,
  • type,
  • of,
  • null,
  • static,
  • relocatable,
  • try,
  • switch,
  • typeof

Solidity Cheatsheet Language Grammar

Source Unit Grammar

There are three types of source units:

  • Pragma directives
  • Import directives
  • Contract definitions

First, the pragma directives are used to set preferences for compiler.

A pseudocode example of pragma syntax:

'pragma' Identifier ([^;]+) ';'

The import directives define the elements imported into the source file.

A pseudocode example of import directive syntax:

'import' StringLiteral ('as' Identifier)? ';' | 
'import' ('*' | Identifier) ('as' Identifier)? 'from' StringLiteral ';' | 
'import' '{' Identifier ('as' Identifier)? ( ',' Identifier ('as' Identifier)? )* '}' 'from' StringLiteral ';'

The main part of any source file is the contracts that it contains.

A pseudocode example of a contract definition:

( 'contract' | 'library' | 'interface' ) Identifier 
( 'is' InheritanceSpecifier (',' InheritanceSpecifier )* )? 
'{' ContractPart* '}'

Basic Contract Grammar

Contracts normally include:

  • State variable declarations
  • Using For declarations
  • Struct definitions
  • Modifier definitions
  • Function definitions
  • Event definitions
  • Enum definitions

A pseudocode example of a state variable declaration:

TypeName ( 'public' | 'internal' | 'private' | 'constant' )? Identifier ('=' Expression)? ';'

A pseudocode example of a Using For declaration:

'using' Identifier 'for' ('*' | TypeName) ';'

A pseudocode example of a struct definition:

'struct' Identifier '{' ( VariableDeclaration ';' (VariableDeclaration ';')* )? '}'

A pseudocode example of a modifier definition:

'modifier' Identifier ParameterList? Block

A pseudocode example of a modifier invocation:

Identifier ( '(' ExpressionList? ')' )?

A pseudocode example of a function definition:

'function' Identifier? ParameterList ( ModifierInvocation | StateMutability | 'external' | 'public' | 'internal' | 'private' )* ( 'returns' ParameterList )? ( ';' | Block )

A pseudocode example of an event definition:

'event' Identifier IndexedParameterList 'anonymous'? ';'

A pseudocode example of an enum definition and setting an enum’s value:

'enum' Identifier '{' EnumValue? (',' EnumValue)* '}' 
Identifier

Other

A pseudocode example of an inheritance specifier:

UserDefinedTypeName ( '(' Expression ( ',' Expression )* ')' )?

A pseudocode example of an indexed parameter list:

'(' ( TypeName 'indexed'? Identifier? (',' TypeName 'indexed'? Identifier?)* )? ')'

A pseudocode example of a parameter list:

'(' ( TypeName Identifier? (',' TypeName Identifier?)* )? ')'

A pseudocode example of a type name list:

'(' ( TypeName (',' TypeName )* )? ')'

Note: in the form of a semantic restriction, structs and mapping that recursively contain mapping, are disallowed on argument lists.

A pseudocode example of a a variable declaration:

TypeName StorageLocation? Identifier

A pseudocode example of a type name:

ElementaryTypeName | UserDefinedTypeName | Mapping | ArrayTypeName | FunctionTypeName

A pseudocode example of a user defined name:

Identifier ( '.' Identifier )*

A pseudocode example of a mapping declaration:

'mapping' '(' ElementaryTypeName '=>' TypeName ')'

A pseudocode example of an array type name:

TypeName '[' Expression? ']'

A pseudocode example of a function type name:

'function' TypeNameList ( 'internal' | 'external' | StateMutability )* ( 'returns' TypeNameList )?

A pseudocode example of a storage location declaration:

'memory' | 'storage'

A pseudocode example of a state mutability declaration:

'pure' | 'constant' | 'view' | 'payable'

A pseudocode example of a block declaration:

'{' Statement* '}'

A pseudocode example of a statement:

IfStatement | WhileStatement | ForStatement | Block | InlineAssemblyStatement | ( DoWhileStatement | PlaceholderStatement | Continue | Break | Return | Throw | SimpleStatement ) ';'

A pseudocode example of an expression statement:

Expression

A pseudocode example of an if statement:

'if' '(' Expression ')' Statement ( 'else' Statement )?

A pseudocode example of a while statement:

'while' '(' Expression ')' Statement

A pseudocode example of a placeholder statement:

'_'

A pseudocode example of a simple statement:

VariableDefinition | ExpressionStatement

A pseudocode example of a for statement:

'for' '(' (SimpleStatement)? ';' (Expression)? ';' (ExpressionStatement)? ')' Statement

A pseudocode example of a inline assembly statement:

'assembly' StringLiteral? InlineAssemblyBlock

A pseudocode example of a do while statement:

'do' Statement 'while' '(' Expression ')'

A pseudocode example of a continue statement:

'continue'

A pseudocode example of a break statement:

'break'

A pseudocode example of a return statement:

'return' Expression?

A pseudocode example of a throw statement:

'throw'

A pseudocode example of a variable definition:

('var' IdentifierList | VariableDeclaration) ( '=' Expression )?

A pseudocode example of an indentifier list:

'(' ( Identifier? ',' )* Identifier? ')'

Note: See the precedence of these statements by order at the Solidity github.

A pseudocode example of an expression:

Expression ('++' | '--') 
| NewExpression 
| IndexAccess 
| MemberAccess 
| FunctionCall 
| '(' Expression ')' 
| ('!' | '~' | 'delete' | '++' | '--' | '+' | '-') Expression 
| Expression '**' Expression 
| Expression ('*' | '/' | '%') Expression 
| Expression ('+' | '-') Expression 
| Expression ('<<' | '>>') Expression 
| Expression '&' Expression 
| Expression '^' Expression 
| Expression '|' Expression 
| Expression ('<' | '>' | '<=' | '>=') Expression 
| Expression ('==' | '!=') Expression 
| Expression '&&' Expression 
| Expression '||' Expression 
| Expression '?' Expression ':' Expression 
| Expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') Expression 
| PrimaryExpression

A pseudocode example of a primary expression:

BooleanLiteral | NumberLiteral | HexLiteral | StringLiteral | TupleExpression | Identifier | ElementaryTypeNameExpression

A pseudocode example of an expression list:

Expression ( ',' Expression )*

A pseudocode example of a name value list:

Identifier ':' Expression ( ',' Identifier ':' Expression )*

A pseudocode example of a function call:

Expression '(' FunctionCallArguments ')'

A pseudocode example of function call arguments:

'{' NameValueList? '}' | ExpressionList?

A pseudocode example of a new expression:

'new' TypeName

A pseudocode example of member access:

Expression '.' Identifier

A pseudocode example of index access:

Expression '[' Expression? ']'

A pseudocode example of a boolean literal:

'true' | 'false'

A pseudocode example of a number literal:

( HexNumber | DecimalNumber ) (' ' NumberUnit)?

A pseudocode example of a number unit:

'wei' | 'szabo' | 'finney' | 'ether' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'years'

A pseudocode example of a hex literal:

'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'')

A pseudocode example of a string literal:

'"' ([^"\r\n\\] | '\\' .)* '"'

A pseudocode example of an identifier:

[a-zA-Z_$] [a-zA-Z_$0-9]*

A pseudocode example of a hex number:

'0x' [0-9a-fA-F]+

A pseudocode example of a decimal number:

[0-9]+ ( '.' [0-9]* )? ( [eE] [0-9]+ )?

A pseudocode example of a tuple expression:

'(' ( Expression? ( ',' Expression? )* )? ')' | '[' ( Expression ( ',' Expression )* )? ']'

A pseudocode example of an elementary type name expression:

ElementaryTypeName

A pseudocode example of an elementary type name:

'address' | 'bool' | 'string' | 'var' | Int | Uint | Byte | Fixed | Ufixed

A pseudocode example of an integer:

Int ='int8 | 16 | 24 | ... | 240 | 248 | 256'

A pseudocode example of an unsigned integer:

Uint = 'uint8 | 16 | 24 | ... | 240 | 248 | 256'

A pseudocode example of a byte:

Byte = 'byte' | 'bytes'   | 'bytes1 | 2 | 3 | ... | 30 | 31 | 32'

A pseudocode example of a fixed variable:

Fixed = 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ )

A pseudocode example of an unsigned fixed variable:

Ufixed = 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ )

A pseudocode example of an inline assembly block:

InlineAssemblyBlock = '{' AssemblyItem* '}'

A pseudocode example of an assembly item:

Identifier 
| FunctionalAssemblyExpression 
| InlineAssemblyBlock 
| AssemblyLocalBinding 
| AssemblyAssignment 
| AssemblyLabel 
| NumberLiteral 
| StringLiteral 
| HexLiteral

A pseudocode example of an assembly local binding:

'let' Identifier ':=' FunctionalAssemblyExpression

A pseudocode example of an assembly assignment:

( Identifier ':=' FunctionalAssemblyExpression ) | ( '=:' Identifier )

A pseudocode example of an assembly label:

Identifier ':'

A pseudocode example of a functional assembly expression:

Identifier '(' AssemblyItem? ( ',' AssemblyItem )* ')'
Read previous post:
Solidity Source Mappings

Solidity Source Mappings Main Tips The Solidity source mappings are static analysis tools operating on bytecode level, used to keep track of the...

Close