Units and Globally Available Variables

Ether Units

A literal number can take a suffix ofwei,gwei orether to specify a subdenomination of Ether, where Ether numbers without a postfix are assumed to be Wei.

assert(1wei==1);assert(1gwei==1e9);assert(1ether==1e18);

The only effect of the subdenomination suffix is a multiplication by a power of ten.

Note

The denominationsfinney andszabo have been removed in version 0.7.0.

Time Units

Suffixes likeseconds,minutes,hours,days andweeksafter literal numbers can be used to specify units of time where seconds are the baseunit and units are considered naively in the following way:

  • 1==1seconds

  • 1minutes==60seconds

  • 1hours==60minutes

  • 1days==24hours

  • 1weeks==7days

Take care if you perform calendar calculations using these units, becausenot every year equals 365 days and not even every day has 24 hoursbecause ofleap seconds.Due to the fact that leap seconds cannot be predicted, an exact calendarlibrary has to be updated by an external oracle.

Note

The suffixyears has been removed in version 0.5.0 due to the reasons above.

These suffixes cannot be applied to variables. For example, if you want tointerpret a function parameter in days, you can in the following way:

functionf(uintstart,uintdaysAfter)public{if(block.timestamp>=start+daysAfter*1days){// ...}}

Special Variables and Functions

There are special variables and functions which always exist in the globalnamespace and are mainly used to provide information about the blockchainor are general-use utility functions.

Block and Transaction Properties

  • blockhash(uintblockNumber)returns(bytes32): hash of the given block whenblocknumber is one of the 256 most recent blocks; otherwise returns zero

  • block.basefee (uint): current block’s base fee (EIP-3198 andEIP-1559)

  • block.chainid (uint): current chain id

  • block.coinbase (addresspayable): current block miner’s address

  • block.difficulty (uint): current block difficulty

  • block.gaslimit (uint): current block gaslimit

  • block.number (uint): current block number

  • block.timestamp (uint): current block timestamp as seconds since unix epoch

  • gasleft()returns(uint256): remaining gas

  • msg.data (bytescalldata): complete calldata

  • msg.sender (address): sender of the message (current call)

  • msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier)

  • msg.value (uint): number of wei sent with the message

  • tx.gasprice (uint): gas price of the transaction

  • tx.origin (address): sender of the transaction (full call chain)

Note

The values of all members ofmsg, includingmsg.sender andmsg.value can change for everyexternal function call.This includes calls to library functions.

Note

Do not rely onblock.timestamp orblockhash as a source of randomness,unless you know what you are doing.

Both the timestamp and the block hash can be influenced by miners to some degree.Bad actors in the mining community can for example run a casino payout function on a chosen hashand just retry a different hash if they did not receive any money.

The current block timestamp must be strictly larger than the timestamp of the last block,but the only guarantee is that it will be somewhere between the timestamps of twoconsecutive blocks in the canonical chain.

Note

The block hashes are not available for all blocks for scalability reasons.You can only access the hashes of the most recent 256 blocks, all othervalues will be zero.

Note

The functionblockhash was previously known asblock.blockhash, which was deprecated inversion 0.4.22 and removed in version 0.5.0.

Note

The functiongasleft was previously known asmsg.gas, which was deprecated inversion 0.4.21 and removed in version 0.5.0.

Note

In version 0.7.0, the aliasnow (forblock.timestamp) was removed.

ABI Encoding and Decoding Functions

  • abi.decode(bytesmemoryencodedData,(...))returns(...): ABI-decodes the given data, while the types are given in parentheses as second argument. Example:(uinta,uint[2]memoryb,bytesmemoryc)=abi.decode(data,(uint,uint[2],bytes))

  • abi.encode(...)returns(bytesmemory): ABI-encodes the given arguments

  • abi.encodePacked(...)returns(bytesmemory): Performspacked encoding of the given arguments. Note that packed encoding can be ambiguous!

  • abi.encodeWithSelector(bytes4selector,...)returns(bytesmemory): ABI-encodes the given arguments starting from the second and prepends the given four-byte selector

  • abi.encodeWithSignature(stringmemorysignature,...)returns(bytesmemory): Equivalent toabi.encodeWithSelector(bytes4(keccak256(bytes(signature))),...)`

Note

These encoding functions can be used to craft data for external function calls without actuallycalling an external function. Furthermore,keccak256(abi.encodePacked(a,b)) is a wayto compute the hash of structured data (although be aware that it is possible tocraft a “hash collision” using different function parameter types).

See the documentation about theABI and thetightly packed encoding for details about the encoding.

Members of bytes

Error Handling

See the dedicated section onassert and require formore details on error handling and when to use which function.

assert(boolcondition)

causes a Panic error and thus state change reversion if the condition is not met - to be used for internal errors.

require(boolcondition)

reverts if the condition is not met - to be used for errors in inputs or external components.

require(boolcondition,stringmemorymessage)

reverts if the condition is not met - to be used for errors in inputs or external components. Also provides an error message.

revert()

abort execution and revert state changes

revert(stringmemoryreason)

abort execution and revert state changes, providing an explanatory string

Mathematical and Cryptographic Functions

addmod(uintx,uinty,uintk)returns(uint)

compute(x+y)%k where the addition is performed with arbitrary precision and does not wrap around at2**256. Assert thatk!=0 starting from version 0.5.0.

mulmod(uintx,uinty,uintk)returns(uint)

compute(x*y)%k where the multiplication is performed with arbitrary precision and does not wrap around at2**256. Assert thatk!=0 starting from version 0.5.0.

keccak256(bytesmemory)returns(bytes32)

compute the Keccak-256 hash of the input

Note

There used to be an alias forkeccak256 calledsha3, which was removed in version 0.5.0.

sha256(bytesmemory)returns(bytes32)

compute the SHA-256 hash of the input

ripemd160(bytesmemory)returns(bytes20)

compute RIPEMD-160 hash of the input

ecrecover(bytes32hash,uint8v,bytes32r,bytes32s)returns(address)

recover the address associated with the public key from elliptic curve signature or return zero on error.The function parameters correspond to ECDSA values of the signature:

  • r = first 32 bytes of signature

  • s = second 32 bytes of signature

  • v = final 1 byte of signature

ecrecover returns anaddress, and not anaddresspayable. Seeaddress payable forconversion, in case you need to transfer funds to the recovered address.

For further details, readexample usage.

Warning

If you useecrecover, be aware that a valid signature can be turned into a different valid signature withoutrequiring knowledge of the corresponding private key. In the Homestead hard fork, this issue was fixedfor _transaction_ signatures (seeEIP-2), butthe ecrecover function remained unchanged.

This is usually not a problem unless you require signatures to be unique oruse them to identify items. OpenZeppelin have aECDSA helper library that you can use as a wrapper forecrecover without this issue.

Note

When runningsha256,ripemd160 orecrecover on aprivate blockchain, you might encounter Out-of-Gas. This is because these functions are implemented as “precompiled contracts” and only really exist after they receive the first message (although their contract code is hardcoded). Messages to non-existing contracts are more expensive and thus the execution might run into an Out-of-Gas error. A workaround for this problem is to first send Wei (1 for example) to each of the contracts before you use them in your actual contracts. This is not an issue on the main or test net.

Members of Address Types

<address>.balance (uint256)

balance of theAddress in Wei

<address>.code (bytesmemory)

code at theAddress (can be empty)

<address>.codehash (bytes32)

the codehash of theAddress

<addresspayable>.transfer(uint256amount)

send given amount of Wei toAddress, reverts on failure, forwards 2300 gas stipend, not adjustable

<addresspayable>.send(uint256amount)returns(bool)

send given amount of Wei toAddress, returnsfalse on failure, forwards 2300 gas stipend, not adjustable

<address>.call(bytesmemory)returns(bool,bytesmemory)

issue low-levelCALL with the given payload, returns success condition and return data, forwards all available gas, adjustable

<address>.delegatecall(bytesmemory)returns(bool,bytesmemory)

issue low-levelDELEGATECALL with the given payload, returns success condition and return data, forwards all available gas, adjustable

<address>.staticcall(bytesmemory)returns(bool,bytesmemory)

issue low-levelSTATICCALL with the given payload, returns success condition and return data, forwards all available gas, adjustable

For more information, see the section onAddress.

Warning

You should avoid using.call() whenever possible when executing another contract function as it bypasses type checking,function existence check, and argument packing.

Warning

There are some dangers in usingsend: The transfer fails if the call stack depth is at 1024(this can always be forced by the caller) and it also fails if the recipient runs out of gas. So in orderto make safe Ether transfers, always check the return value ofsend, usetransfer or even better:Use a pattern where the recipient withdraws the money.

Warning

Due to the fact that the EVM considers a call to a non-existing contract to always succeed,Solidity includes an extra check using theextcodesize opcode when performing external calls.This ensures that the contract that is about to be called either actually exists (it contains code)or an exception is raised.

The low-level calls which operate on addresses rather than contract instances (i.e..call(),.delegatecall(),.staticcall(),.send() and.transfer())do not include thischeck, which makes them cheaper in terms of gas but also less safe.

Note

Prior to version 0.5.0, Solidity allowed address members to be accessed by a contract instance, for examplethis.balance.This is now forbidden and an explicit conversion to address must be done:address(this).balance.

Note

If state variables are accessed via a low-level delegatecall, the storage layout of the two contractsmust align in order for the called contract to correctly access the storage variables of the calling contract by name.This is of course not the case if storage pointers are passed as function arguments as in the case forthe high-level libraries.

Note

Prior to version 0.5.0,.call,.delegatecall and.staticcall only returned thesuccess condition and not the return data.

Note

Prior to version 0.5.0, there was a member calledcallcode with similar but slightly differentsemantics thandelegatecall.

Contract Related

this (current contract’s type)

the current contract, explicitly convertible toAddress

selfdestruct(addresspayablerecipient)

Destroy the current contract, sending its funds to the givenAddressand end execution.Note thatselfdestruct has some peculiarities inherited from the EVM:

  • the receiving contract’s receive function is not executed.

  • the contract is only really destroyed at the end of the transaction andrevert s might “undo” the destruction.

Furthermore, all functions of the current contract are callable directly including the current function.

Note

Prior to version 0.5.0, there was a function calledsuicide with the samesemantics asselfdestruct.

Type Information

The expressiontype(X) can be used to retrieve information about the typeX. Currently, there is limited support for this feature (X can be eithera contract or an integer type) but it might be expanded in the future.

The following properties are available for a contract typeC:

type(C).name

The name of the contract.

type(C).creationCode

Memory byte array that contains the creation bytecode of the contract.This can be used in inline assembly to build custom creation routines,especially by using thecreate2 opcode.This property cannot be accessed in the contract itself or anyderived contract. It causes the bytecode to be included in the bytecodeof the call site and thus circular references like that are not possible.

type(C).runtimeCode

Memory byte array that contains the runtime bytecode of the contract.This is the code that is usually deployed by the constructor ofC.IfC has a constructor that uses inline assembly, this might bedifferent from the actually deployed bytecode. Also note that librariesmodify their runtime bytecode at time of deployment to guard againstregular calls.The same restrictions as with.creationCode also apply for thisproperty.

In addition to the properties above, the following properties are availablefor an interface typeI:

type(I).interfaceId:

Abytes4 value containing theEIP-165interface identifier of the given interfaceI. This identifier is defined as theXOR of allfunction selectors defined within the interface itself - excluding all inherited functions.

The following properties are available for an integer typeT:

type(T).min

The smallest value representable by typeT.

type(T).max

The largest value representable by typeT.