1.. index:: ! value type, ! type;value 2.. _value-types: 3 4Value Types 5=========== 6 7The following types are also called value types because variables of these 8types will always be passed by value, i.e. they are always copied when they 9are used as function arguments or in assignments. 10 11.. index:: ! bool, ! true, ! false 12 13Booleans 14-------- 15 16``bool``: The possible values are constants ``true`` and ``false``. 17 18Operators: 19 20* ``!`` (logical negation) 21* ``&&`` (logical conjunction, "and") 22* ``||`` (logical disjunction, "or") 23* ``==`` (equality) 24* ``!=`` (inequality) 25 26The operators ``||`` and ``&&`` apply the common short-circuiting rules. This means that in the expression ``f(x) || g(y)``, if ``f(x)`` evaluates to ``true``, ``g(y)`` will not be evaluated even if it may have side-effects. 27 28.. index:: ! uint, ! int, ! integer 29.. _integers: 30 31Integers 32-------- 33 34``int`` / ``uint``: Signed and unsigned integers of various sizes. Keywords ``uint8`` to ``uint256`` in steps of ``8`` (unsigned of 8 up to 256 bits) and ``int8`` to ``int256``. ``uint`` and ``int`` are aliases for ``uint256`` and ``int256``, respectively. 35 36Operators: 37 38* Comparisons: ``<=``, ``<``, ``==``, ``!=``, ``>=``, ``>`` (evaluate to ``bool``) 39* Bit operators: ``&``, ``|``, ``^`` (bitwise exclusive or), ``~`` (bitwise negation) 40* Shift operators: ``<<`` (left shift), ``>>`` (right shift) 41* Arithmetic operators: ``+``, ``-``, unary ``-`` (only for signed integers), ``*``, ``/``, ``%`` (modulo), ``**`` (exponentiation) 42 43For an integer type ``X``, you can use ``type(X).min`` and ``type(X).max`` to 44access the minimum and maximum value representable by the type. 45 46.. warning:: 47 48 Integers in Solidity are restricted to a certain range. For example, with ``uint32``, this is ``0`` up to ``2**32 - 1``. 49 There are two modes in which arithmetic is performed on these types: The "wrapping" or "unchecked" mode and the "checked" mode. 50 By default, arithmetic is always "checked", which mean that if the result of an operation falls outside the value range 51 of the type, the call is reverted through a :ref:`failing assertion<assert-and-require>`. You can switch to "unchecked" mode 52 using ``unchecked { ... }``. More details can be found in the section about :ref:`unchecked <unchecked>`. 53 54Comparisons 55^^^^^^^^^^^ 56 57The value of a comparison is the one obtained by comparing the integer value. 58 59Bit operations 60^^^^^^^^^^^^^^ 61 62Bit operations are performed on the two's complement representation of the number. 63This means that, for example ``~int256(0) == int256(-1)``. 64 65Shifts 66^^^^^^ 67 68The result of a shift operation has the type of the left operand, truncating the result to match the type. 69The right operand must be of unsigned type, trying to shift by a signed type will produce a compilation error. 70 71Shifts can be "simulated" using multiplication by powers of two in the following way. Note that the truncation 72to the type of the left operand is always performed at the end, but not mentioned explicitly. 73 74- ``x << y`` is equivalent to the mathematical expression ``x * 2**y``. 75- ``x >> y`` is equivalent to the mathematical expression ``x / 2**y``, rounded towards negative infinity. 76 77.. warning:: 78 Before version ``0.5.0`` a right shift ``x >> y`` for negative ``x`` was equivalent to 79 the mathematical expression ``x / 2**y`` rounded towards zero, 80 i.e., right shifts used rounding up (towards zero) instead of rounding down (towards negative infinity). 81 82.. note:: 83 Overflow checks are never performed for shift operations as they are done for arithmetic operations. 84 Instead, the result is always truncated. 85 86Addition, Subtraction and Multiplication 87^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 88 89Addition, subtraction and multiplication have the usual semantics, with two different 90modes in regard to over- and underflow: 91 92By default, all arithmetic is checked for under- or overflow, but this can be disabled 93using the :ref:`unchecked block<unchecked>`, resulting in wrapping arithmetic. More details 94can be found in that section. 95 96The expression ``-x`` is equivalent to ``(T(0) - x)`` where 97``T`` is the type of ``x``. It can only be applied to signed types. 98The value of ``-x`` can be 99positive if ``x`` is negative. There is another caveat also resulting 100from two's complement representation: 101 102If you have ``int x = type(int).min;``, then ``-x`` does not fit the positive range. 103This means that ``unchecked { assert(-x == x); }`` works, and the expression ``-x`` 104when used in checked mode will result in a failing assertion. 105 106Division 107^^^^^^^^ 108 109Since the type of the result of an operation is always the type of one of 110the operands, division on integers always results in an integer. 111In Solidity, division rounds towards zero. This means that ``int256(-5) / int256(2) == int256(-2)``. 112 113Note that in contrast, division on :ref:`literals<rational_literals>` results in fractional values 114of arbitrary precision. 115 116.. note:: 117 Division by zero causes a :ref:`Panic error<assert-and-require>`. This check can **not** be disabled through ``unchecked { ... }``. 118 119.. note:: 120 The expression ``type(int).min / (-1)`` is the only case where division causes an overflow. 121 In checked arithmetic mode, this will cause a failing assertion, while in wrapping 122 mode, the value will be ``type(int).min``. 123 124Modulo 125^^^^^^ 126 127The modulo operation ``a % n`` yields the remainder ``r`` after the division of the operand ``a`` 128by the operand ``n``, where ``q = int(a / n)`` and ``r = a - (n * q)``. This means that modulo 129results in the same sign as its left operand (or zero) and ``a % n == -(-a % n)`` holds for negative ``a``: 130 131* ``int256(5) % int256(2) == int256(1)`` 132* ``int256(5) % int256(-2) == int256(1)`` 133* ``int256(-5) % int256(2) == int256(-1)`` 134* ``int256(-5) % int256(-2) == int256(-1)`` 135 136.. note:: 137 Modulo with zero causes a :ref:`Panic error<assert-and-require>`. This check can **not** be disabled through ``unchecked { ... }``. 138 139Exponentiation 140^^^^^^^^^^^^^^ 141 142Exponentiation is only available for unsigned types in the exponent. The resulting type 143of an exponentiation is always equal to the type of the base. Please take care that it is 144large enough to hold the result and prepare for potential assertion failures or wrapping behaviour. 145 146.. note:: 147 In checked mode, exponentiation only uses the comparatively cheap ``exp`` opcode for small bases. 148 For the cases of ``x**3``, the expression ``x*x*x`` might be cheaper. 149 In any case, gas cost tests and the use of the optimizer are advisable. 150 151.. note:: 152 Note that ``0**0`` is defined by the EVM as ``1``. 153 154.. index:: ! ufixed, ! fixed, ! fixed point number 155 156Fixed Point Numbers 157------------------- 158 159.. warning:: 160 Fixed point numbers are not fully supported by Solidity yet. They can be declared, but 161 cannot be assigned to or from. 162 163``fixed`` / ``ufixed``: Signed and unsigned fixed point number of various sizes. Keywords ``ufixedMxN`` and ``fixedMxN``, where ``M`` represents the number of bits taken by 164the type and ``N`` represents how many decimal points are available. ``M`` must be divisible by 8 and goes from 8 to 256 bits. ``N`` must be between 0 and 80, inclusive. 165``ufixed`` and ``fixed`` are aliases for ``ufixed128x18`` and ``fixed128x18``, respectively. 166 167Operators: 168 169* Comparisons: ``<=``, ``<``, ``==``, ``!=``, ``>=``, ``>`` (evaluate to ``bool``) 170* Arithmetic operators: ``+``, ``-``, unary ``-``, ``*``, ``/``, ``%`` (modulo) 171 172.. note:: 173 The main difference between floating point (``float`` and ``double`` in many languages, more precisely IEEE 754 numbers) and fixed point numbers is 174 that the number of bits used for the integer and the fractional part (the part after the decimal dot) is flexible in the former, while it is strictly 175 defined in the latter. Generally, in floating point almost the entire space is used to represent the number, while only a small number of bits define 176 where the decimal point is. 177 178.. index:: address, balance, send, call, delegatecall, staticcall, transfer 179 180.. _address: 181 182Address 183------- 184 185The address type comes in two flavours, which are largely identical: 186 187- ``address``: Holds a 20 byte value (size of an Ethereum address). 188- ``address payable``: Same as ``address``, but with the additional members ``transfer`` and ``send``. 189 190The idea behind this distinction is that ``address payable`` is an address you can send Ether to, 191while a plain ``address`` cannot be sent Ether. 192 193Type conversions: 194 195Implicit conversions from ``address payable`` to ``address`` are allowed, whereas conversions from ``address`` to ``address payable`` 196must be explicit via ``payable(<address>)``. 197 198Explicit conversions to and from ``address`` are allowed for ``uint160``, integer literals, 199``bytes20`` and contract types. 200 201Only expressions of type ``address`` and contract-type can be converted to the type ``address 202payable`` via the explicit conversion ``payable(...)``. For contract-type, this conversion is only 203allowed if the contract can receive Ether, i.e., the contract either has a :ref:`receive 204<receive-ether-function>` or a payable fallback function. Note that ``payable(0)`` is valid and is 205an exception to this rule. 206 207.. note:: 208 If you need a variable of type ``address`` and plan to send Ether to it, then 209 declare its type as ``address payable`` to make this requirement visible. Also, 210 try to make this distinction or conversion as early as possible. 211 212Operators: 213 214* ``<=``, ``<``, ``==``, ``!=``, ``>=`` and ``>`` 215 216.. warning:: 217 If you convert a type that uses a larger byte size to an ``address``, for example ``bytes32``, then the ``address`` is truncated. 218 To reduce conversion ambiguity version 0.4.24 and higher of the compiler force you make the truncation explicit in the conversion. 219 Take for example the 32-byte value ``0x111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFFCCCC``. 220 221 You can use ``address(uint160(bytes20(b)))``, which results in ``0x111122223333444455556666777788889999aAaa``, 222 or you can use ``address(uint160(uint256(b)))``, which results in ``0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc``. 223 224.. note:: 225 The distinction between ``address`` and ``address payable`` was introduced with version 0.5.0. 226 Also starting from that version, contracts do not derive from the address type, but can still be explicitly converted to 227 ``address`` or to ``address payable``, if they have a receive or payable fallback function. 228 229.. _members-of-addresses: 230 231Members of Addresses 232^^^^^^^^^^^^^^^^^^^^ 233 234For a quick reference of all members of address, see :ref:`address_related`. 235 236* ``balance`` and ``transfer`` 237 238It is possible to query the balance of an address using the property ``balance`` 239and to send Ether (in units of wei) to a payable address using the ``transfer`` function: 240 241.. code-block:: solidity 242 :force: 243 244 address payable x = payable(0x123); 245 address myAddress = address(this); 246 if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10); 247 248The ``transfer`` function fails if the balance of the current contract is not large enough 249or if the Ether transfer is rejected by the receiving account. The ``transfer`` function 250reverts on failure. 251 252.. note:: 253 If ``x`` is a contract address, its code (more specifically: its :ref:`receive-ether-function`, if present, or otherwise its :ref:`fallback-function`, if present) will be executed together with the ``transfer`` call (this is a feature of the EVM and cannot be prevented). If that execution runs out of gas or fails in any way, the Ether transfer will be reverted and the current contract will stop with an exception. 254 255* ``send`` 256 257Send is the low-level counterpart of ``transfer``. If the execution fails, the current contract will not stop with an exception, but ``send`` will return ``false``. 258 259.. warning:: 260 There are some dangers in using ``send``: The transfer fails if the call stack depth is at 1024 261 (this can always be forced by the caller) and it also fails if the recipient runs out of gas. So in order 262 to make safe Ether transfers, always check the return value of ``send``, use ``transfer`` or even better: 263 use a pattern where the recipient withdraws the money. 264 265* ``call``, ``delegatecall`` and ``staticcall`` 266 267In order to interface with contracts that do not adhere to the ABI, 268or to get more direct control over the encoding, 269the functions ``call``, ``delegatecall`` and ``staticcall`` are provided. 270They all take a single ``bytes memory`` parameter and 271return the success condition (as a ``bool``) and the returned data 272(``bytes memory``). 273The functions ``abi.encode``, ``abi.encodePacked``, ``abi.encodeWithSelector`` 274and ``abi.encodeWithSignature`` can be used to encode structured data. 275 276Example: 277 278.. code-block:: solidity 279 280 bytes memory payload = abi.encodeWithSignature("register(string)", "MyName"); 281 (bool success, bytes memory returnData) = address(nameReg).call(payload); 282 require(success); 283 284.. warning:: 285 All these functions are low-level functions and should be used with care. 286 Specifically, any unknown contract might be malicious and if you call it, you 287 hand over control to that contract which could in turn call back into 288 your contract, so be prepared for changes to your state variables 289 when the call returns. The regular way to interact with other contracts 290 is to call a function on a contract object (``x.f()``). 291 292.. note:: 293 Previous versions of Solidity allowed these functions to receive 294 arbitrary arguments and would also handle a first argument of type 295 ``bytes4`` differently. These edge cases were removed in version 0.5.0. 296 297It is possible to adjust the supplied gas with the ``gas`` modifier: 298 299.. code-block:: solidity 300 301 address(nameReg).call{gas: 1000000}(abi.encodeWithSignature("register(string)", "MyName")); 302 303Similarly, the supplied Ether value can be controlled too: 304 305.. code-block:: solidity 306 307 address(nameReg).call{value: 1 ether}(abi.encodeWithSignature("register(string)", "MyName")); 308 309Lastly, these modifiers can be combined. Their order does not matter: 310 311.. code-block:: solidity 312 313 address(nameReg).call{gas: 1000000, value: 1 ether}(abi.encodeWithSignature("register(string)", "MyName")); 314 315In a similar way, the function ``delegatecall`` can be used: the difference is that only the code of the given address is used, all other aspects (storage, balance, ...) are taken from the current 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. 316 317.. note:: 318 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. This function was removed in version 0.5.0. 319 320Since byzantium ``staticcall`` can be used as well. This is basically the same as ``call``, but will revert if the called function modifies the state in any way. 321 322All three functions ``call``, ``delegatecall`` and ``staticcall`` are very low-level functions and should only be used as a *last resort* as they break the type-safety of Solidity. 323 324The ``gas`` option is available on all three methods, while the ``value`` option is only available 325on ``call``. 326 327.. note:: 328 It is best to avoid relying on hardcoded gas values in your smart contract code, 329 regardless of whether state is read from or written to, as this can have many pitfalls. 330 Also, access to gas might change in the future. 331 332.. note:: 333 All contracts can be converted to ``address`` type, so it is possible to query the balance of the 334 current contract using ``address(this).balance``. 335 336.. index:: ! contract type, ! type; contract 337 338.. _contract_types: 339 340Contract Types 341-------------- 342 343Every :ref:`contract<contracts>` defines its own type. 344You can implicitly convert contracts to contracts they inherit from. 345Contracts can be explicitly converted to and from the ``address`` type. 346 347Explicit conversion to and from the ``address payable`` type is only possible 348if the contract type has a receive or payable fallback function. The conversion is still 349performed using ``address(x)``. If the contract type does not have a receive or payable 350fallback function, the conversion to ``address payable`` can be done using 351``payable(address(x))``. 352You can find more information in the section about 353the :ref:`address type<address>`. 354 355.. note:: 356 Before version 0.5.0, contracts directly derived from the address type 357 and there was no distinction between ``address`` and ``address payable``. 358 359If you declare a local variable of contract type (``MyContract c``), you can call 360functions on that contract. Take care to assign it from somewhere that is the 361same contract type. 362 363You can also instantiate contracts (which means they are newly created). You 364can find more details in the :ref:`'Contracts via new'<creating-contracts>` 365section. 366 367The data representation of a contract is identical to that of the ``address`` 368type and this type is also used in the :ref:`ABI<ABI>`. 369 370Contracts do not support any operators. 371 372The members of contract types are the external functions of the contract 373including any state variables marked as ``public``. 374 375For a contract ``C`` you can use ``type(C)`` to access 376:ref:`type information<meta-type>` about the contract. 377 378.. index:: byte array, bytes32 379 380Fixed-size byte arrays 381---------------------- 382 383The value types ``bytes1``, ``bytes2``, ``bytes3``, ..., ``bytes32`` 384hold a sequence of bytes from one to up to 32. 385 386Operators: 387 388* Comparisons: ``<=``, ``<``, ``==``, ``!=``, ``>=``, ``>`` (evaluate to ``bool``) 389* Bit operators: ``&``, ``|``, ``^`` (bitwise exclusive or), ``~`` (bitwise negation) 390* Shift operators: ``<<`` (left shift), ``>>`` (right shift) 391* Index access: If ``x`` is of type ``bytesI``, then ``x[k]`` for ``0 <= k < I`` returns the ``k`` th byte (read-only). 392 393The shifting operator works with unsigned integer type as right operand (but 394returns the type of the left operand), which denotes the number of bits to shift by. 395Shifting by a signed type will produce a compilation error. 396 397Members: 398 399* ``.length`` yields the fixed length of the byte array (read-only). 400 401.. note:: 402 The type ``bytes1[]`` is an array of bytes, but due to padding rules, it wastes 403 31 bytes of space for each element (except in storage). It is better to use the ``bytes`` 404 type instead. 405 406.. note:: 407 Prior to version 0.8.0, ``byte`` used to be an alias for ``bytes1``. 408 409Dynamically-sized byte array 410---------------------------- 411 412``bytes``: 413 Dynamically-sized byte array, see :ref:`arrays`. Not a value-type! 414``string``: 415 Dynamically-sized UTF-8-encoded string, see :ref:`arrays`. Not a value-type! 416 417.. index:: address, literal;address 418 419.. _address_literals: 420 421Address Literals 422---------------- 423 424Hexadecimal literals that pass the address checksum test, for example 425``0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF`` are of ``address`` type. 426Hexadecimal literals that are between 39 and 41 digits 427long and do not pass the checksum test produce 428an error. You can prepend (for integer types) or append (for bytesNN types) zeros to remove the error. 429 430.. note:: 431 The mixed-case address checksum format is defined in `EIP-55 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md>`_. 432 433.. index:: literal, literal;rational 434 435.. _rational_literals: 436 437Rational and Integer Literals 438----------------------------- 439 440Integer literals are formed from a sequence of digits in the range 0-9. 441They are interpreted as decimals. For example, ``69`` means sixty nine. 442Octal literals do not exist in Solidity and leading zeros are invalid. 443 444Decimal fractional literals are formed by a ``.`` with at least one number on 445one side. Examples include ``1.``, ``.1`` and ``1.3``. 446 447Scientific notation in the form of ``2e10`` is also supported, where the 448mantissa can be fractional but the exponent has to be an integer. 449The literal ``MeE`` is equivalent to ``M * 10**E``. 450Examples include ``2e10``, ``-2e10``, ``2e-10``, ``2.5e1``. 451 452Underscores can be used to separate the digits of a numeric literal to aid readability. 453For example, decimal ``123_000``, hexadecimal ``0x2eff_abde``, scientific decimal notation ``1_2e345_678`` are all valid. 454Underscores are only allowed between two digits and only one consecutive underscore is allowed. 455There is no additional semantic meaning added to a number literal containing underscores, 456the underscores are ignored. 457 458Number literal expressions retain arbitrary precision until they are converted to a non-literal type (i.e. by 459using them together with a non-literal expression or by explicit conversion). 460This means that computations do not overflow and divisions do not truncate 461in number literal expressions. 462 463For example, ``(2**800 + 1) - 2**800`` results in the constant ``1`` (of type ``uint8``) 464although intermediate results would not even fit the machine word size. Furthermore, ``.5 * 8`` results 465in the integer ``4`` (although non-integers were used in between). 466 467Any operator that can be applied to integers can also be applied to number literal expressions as 468long as the operands are integers. If any of the two is fractional, bit operations are disallowed 469and exponentiation is disallowed if the exponent is fractional (because that might result in 470a non-rational number). 471 472Shifts and exponentiation with literal numbers as left (or base) operand and integer types 473as the right (exponent) operand are always performed 474in the ``uint256`` (for non-negative literals) or ``int256`` (for a negative literals) type, 475regardless of the type of the right (exponent) operand. 476 477.. warning:: 478 Division on integer literals used to truncate in Solidity prior to version 0.4.0, but it now converts into a rational number, i.e. ``5 / 2`` is not equal to ``2``, but to ``2.5``. 479 480.. note:: 481 Solidity has a number literal type for each rational number. 482 Integer literals and rational number literals belong to number literal types. 483 Moreover, all number literal expressions (i.e. the expressions that 484 contain only number literals and operators) belong to number literal 485 types. So the number literal expressions ``1 + 2`` and ``2 + 1`` both 486 belong to the same number literal type for the rational number three. 487 488 489.. note:: 490 Number literal expressions are converted into a non-literal type as soon as they are used with non-literal 491 expressions. Disregarding types, the value of the expression assigned to ``b`` 492 below evaluates to an integer. Because ``a`` is of type ``uint128``, the 493 expression ``2.5 + a`` has to have a proper type, though. Since there is no common type 494 for the type of ``2.5`` and ``uint128``, the Solidity compiler does not accept 495 this code. 496 497.. code-block:: solidity 498 499 uint128 a = 1; 500 uint128 b = 2.5 + a + 0.5; 501 502.. index:: literal, literal;string, string 503.. _string_literals: 504 505String Literals and Types 506------------------------- 507 508String literals are written with either double or single-quotes (``"foo"`` or ``'bar'``), and they can also be split into multiple consecutive parts (``"foo" "bar"`` is equivalent to ``"foobar"``) which can be helpful when dealing with long strings. They do not imply trailing zeroes as in C; ``"foo"`` represents three bytes, not four. As with integer literals, their type can vary, but they are implicitly convertible to ``bytes1``, ..., ``bytes32``, if they fit, to ``bytes`` and to ``string``. 509 510For example, with ``bytes32 samevar = "stringliteral"`` the string literal is interpreted in its raw byte form when assigned to a ``bytes32`` type. 511 512String literals can only contain printable ASCII characters, which means the characters between and including 0x20 .. 0x7E. 513 514Additionally, string literals also support the following escape characters: 515 516- ``\<newline>`` (escapes an actual newline) 517- ``\\`` (backslash) 518- ``\'`` (single quote) 519- ``\"`` (double quote) 520- ``\n`` (newline) 521- ``\r`` (carriage return) 522- ``\t`` (tab) 523- ``\xNN`` (hex escape, see below) 524- ``\uNNNN`` (unicode escape, see below) 525 526``\xNN`` takes a hex value and inserts the appropriate byte, while ``\uNNNN`` takes a Unicode codepoint and inserts an UTF-8 sequence. 527 528.. note:: 529 530 Until version 0.8.0 there were three additional escape sequences: ``\b``, ``\f`` and ``\v``. 531 They are commonly available in other languages but rarely needed in practice. 532 If you do need them, they can still be inserted via hexadecimal escapes, i.e. ``\x08``, ``\x0c`` 533 and ``\x0b``, respectively, just as any other ASCII character. 534 535The string in the following example has a length of ten bytes. 536It starts with a newline byte, followed by a double quote, a single 537quote a backslash character and then (without separator) the 538character sequence ``abcdef``. 539 540.. code-block:: solidity 541 :force: 542 543 "\n\"\'\\abc\ 544 def" 545 546Any Unicode line terminator which is not a newline (i.e. LF, VF, FF, CR, NEL, LS, PS) is considered to 547terminate the string literal. Newline only terminates the string literal if it is not preceded by a ``\``. 548 549Unicode Literals 550---------------- 551 552While regular string literals can only contain ASCII, Unicode literals – prefixed with the keyword ``unicode`` – can contain any valid UTF-8 sequence. 553They also support the very same escape sequences as regular string literals. 554 555.. code-block:: solidity 556 557 string memory a = unicode"Hello "; 558 559.. index:: literal, bytes 560 561Hexadecimal Literals 562-------------------- 563 564Hexadecimal literals are prefixed with the keyword ``hex`` and are enclosed in double 565or single-quotes (``hex"001122FF"``, ``hex'0011_22_FF'``). Their content must be 566hexadecimal digits which can optionally use a single underscore as separator between 567byte boundaries. The value of the literal will be the binary representation 568of the hexadecimal sequence. 569 570Multiple hexadecimal literals separated by whitespace are concatenated into a single literal: 571``hex"00112233" hex"44556677"`` is equivalent to ``hex"0011223344556677"`` 572 573Hexadecimal literals behave like :ref:`string literals <string_literals>` and have the same convertibility restrictions. 574 575.. index:: enum 576 577.. _enums: 578 579Enums 580----- 581 582Enums are one way to create a user-defined type in Solidity. They are explicitly convertible 583to and from all integer types but implicit conversion is not allowed. The explicit conversion 584from integer checks at runtime that the value lies inside the range of the enum and causes a 585:ref:`Panic error<assert-and-require>` otherwise. 586Enums require at least one member, and its default value when declared is the first member. 587Enums cannot have more than 256 members. 588 589The data representation is the same as for enums in C: The options are represented by 590subsequent unsigned integer values starting from ``0``. 591 592Using ``type(NameOfEnum).min`` and ``type(NameOfEnum).max`` you can get the 593smallest and respectively largest value of the given enum. 594 595 596.. code-block:: solidity 597 598 // SPDX-License-Identifier: GPL-3.0 599 pragma solidity ^0.8.8; 600 601 contract test { 602 enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } 603 ActionChoices choice; 604 ActionChoices constant defaultChoice = ActionChoices.GoStraight; 605 606 function setGoStraight() public { 607 choice = ActionChoices.GoStraight; 608 } 609 610 // Since enum types are not part of the ABI, the signature of "getChoice" 611 // will automatically be changed to "getChoice() returns (uint8)" 612 // for all matters external to Solidity. 613 function getChoice() public view returns (ActionChoices) { 614 return choice; 615 } 616 617 function getDefaultChoice() public pure returns (uint) { 618 return uint(defaultChoice); 619 } 620 621 function getLargestValue() public pure returns (ActionChoices) { 622 return type(ActionChoices).max; 623 } 624 625 function getSmallestValue() public pure returns (ActionChoices) { 626 return type(ActionChoices).min; 627 } 628 } 629 630.. note:: 631 Enums can also be declared on the file level, outside of contract or library definitions. 632 633.. index:: ! user defined value type, custom type 634 635.. _user-defined-value-types: 636 637User Defined Value Types 638------------------------ 639 640A user defined value type allows creating a zero cost abstraction over an elementary value type. 641This is similar to an alias, but with stricter type requirements. 642 643A user defined value type is defined using ``type C is V``, where ``C`` is the name of the newly 644introduced type and ``V`` has to be a built-in value type (the "underlying type"). The function 645``C.wrap`` is used to convert from the underlying type to the custom type. Similarly, the 646function ``C.unwrap`` is used to convert from the custom type to the underlying type. 647 648The type ``C`` does not have any operators or bound member functions. In particular, even the 649operator ``==`` is not defined. Explicit and implicit conversions to and from other types are 650disallowed. 651 652The data-representation of values of such types are inherited from the underlying type 653and the underlying type is also used in the ABI. 654 655The following example illustrates a custom type ``UFixed256x18`` representing a decimal fixed point 656type with 18 decimals and a minimal library to do arithmetic operations on the type. 657 658 659.. code-block:: solidity 660 661 // SPDX-License-Identifier: GPL-3.0 662 pragma solidity ^0.8.8; 663 664 // Represent a 18 decimal, 256 bit wide fixed point type using a user defined value type. 665 type UFixed256x18 is uint256; 666 667 /// A minimal library to do fixed point operations on UFixed256x18. 668 library FixedMath { 669 uint constant multiplier = 10**18; 670 671 /// Adds two UFixed256x18 numbers. Reverts on overflow, relying on checked 672 /// arithmetic on uint256. 673 function add(UFixed256x18 a, UFixed256x18 b) internal pure returns (UFixed256x18) { 674 return UFixed256x18.wrap(UFixed256x18.unwrap(a) + UFixed256x18.unwrap(b)); 675 } 676 /// Multiplies UFixed256x18 and uint256. Reverts on overflow, relying on checked 677 /// arithmetic on uint256. 678 function mul(UFixed256x18 a, uint256 b) internal pure returns (UFixed256x18) { 679 return UFixed256x18.wrap(UFixed256x18.unwrap(a) * b); 680 } 681 /// Take the floor of a UFixed256x18 number. 682 /// @return the largest integer that does not exceed `a`. 683 function floor(UFixed256x18 a) internal pure returns (uint256) { 684 return UFixed256x18.unwrap(a) / multiplier; 685 } 686 /// Turns a uint256 into a UFixed256x18 of the same value. 687 /// Reverts if the integer is too large. 688 function toUFixed256x18(uint256 a) internal pure returns (UFixed256x18) { 689 return UFixed256x18.wrap(a * multiplier); 690 } 691 } 692 693Notice how ``UFixed256x18.wrap`` and ``FixedMath.toUFixed256x18`` have the same signature but 694perform two very different operations: The ``UFixed256x18.wrap`` function returns a ``UFixed256x18`` 695that has the same data representation as the input, whereas ``toUFixed256x18`` returns a 696``UFixed256x18`` that has the same numerical value. 697 698.. index:: ! function type, ! type; function 699 700.. _function_types: 701 702Function Types 703-------------- 704 705Function types are the types of functions. Variables of function type 706can be assigned from functions and function parameters of function type 707can be used to pass functions to and return functions from function calls. 708Function types come in two flavours - *internal* and *external* functions: 709 710Internal functions can only be called inside the current contract (more specifically, 711inside the current code unit, which also includes internal library functions 712and inherited functions) because they cannot be executed outside of the 713context of the current contract. Calling an internal function is realized 714by jumping to its entry label, just like when calling a function of the current 715contract internally. 716 717External functions consist of an address and a function signature and they can 718be passed via and returned from external function calls. 719 720Function types are notated as follows: 721 722.. code-block:: solidity 723 :force: 724 725 function (<parameter types>) {internal|external} [pure|view|payable] [returns (<return types>)] 726 727In contrast to the parameter types, the return types cannot be empty - if the 728function type should not return anything, the whole ``returns (<return types>)`` 729part has to be omitted. 730 731By default, function types are internal, so the ``internal`` keyword can be 732omitted. Note that this only applies to function types. Visibility has 733to be specified explicitly for functions defined in contracts, they 734do not have a default. 735 736Conversions: 737 738A function type ``A`` is implicitly convertible to a function type ``B`` if and only if 739their parameter types are identical, their return types are identical, 740their internal/external property is identical and the state mutability of ``A`` 741is more restrictive than the state mutability of ``B``. In particular: 742 743- ``pure`` functions can be converted to ``view`` and ``non-payable`` functions 744- ``view`` functions can be converted to ``non-payable`` functions 745- ``payable`` functions can be converted to ``non-payable`` functions 746 747No other conversions between function types are possible. 748 749The rule about ``payable`` and ``non-payable`` might be a little 750confusing, but in essence, if a function is ``payable``, this means that it 751also accepts a payment of zero Ether, so it also is ``non-payable``. 752On the other hand, a ``non-payable`` function will reject Ether sent to it, 753so ``non-payable`` functions cannot be converted to ``payable`` functions. 754 755If a function type variable is not initialised, calling it results 756in a :ref:`Panic error<assert-and-require>`. The same happens if you call a function after using ``delete`` 757on it. 758 759If external function types are used outside of the context of Solidity, 760they are treated as the ``function`` type, which encodes the address 761followed by the function identifier together in a single ``bytes24`` type. 762 763Note that public functions of the current contract can be used both as an 764internal and as an external function. To use ``f`` as an internal function, 765just use ``f``, if you want to use its external form, use ``this.f``. 766 767A function of an internal type can be assigned to a variable of an internal function type regardless 768of where it is defined. 769This includes private, internal and public functions of both contracts and libraries as well as free 770functions. 771External function types, on the other hand, are only compatible with public and external contract 772functions. 773Libraries are excluded because they require a ``delegatecall`` and use :ref:`a different ABI 774convention for their selectors <library-selectors>`. 775Functions declared in interfaces do not have definitions so pointing at them does not make sense either. 776 777Members: 778 779External (or public) functions have the following members: 780 781* ``.address`` returns the address of the contract of the function. 782* ``.selector`` returns the :ref:`ABI function selector <abi_function_selector>` 783 784.. note:: 785 External (or public) functions used to have the additional members 786 ``.gas(uint)`` and ``.value(uint)``. These were deprecated in Solidity 0.6.2 787 and removed in Solidity 0.7.0. Instead use ``{gas: ...}`` and ``{value: ...}`` 788 to specify the amount of gas or the amount of wei sent to a function, 789 respectively. See :ref:`External Function Calls <external-function-calls>` for 790 more information. 791 792Example that shows how to use the members: 793 794.. code-block:: solidity 795 796 // SPDX-License-Identifier: GPL-3.0 797 pragma solidity >=0.6.4 <0.9.0; 798 799 contract Example { 800 function f() public payable returns (bytes4) { 801 assert(this.f.address == address(this)); 802 return this.f.selector; 803 } 804 805 function g() public { 806 this.f{gas: 10, value: 800}(); 807 } 808 } 809 810Example that shows how to use internal function types: 811 812.. code-block:: solidity 813 814 // SPDX-License-Identifier: GPL-3.0 815 pragma solidity >=0.4.16 <0.9.0; 816 817 library ArrayUtils { 818 // internal functions can be used in internal library functions because 819 // they will be part of the same code context 820 function map(uint[] memory self, function (uint) pure returns (uint) f) 821 internal 822 pure 823 returns (uint[] memory r) 824 { 825 r = new uint[](self.length); 826 for (uint i = 0; i < self.length; i++) { 827 r[i] = f(self[i]); 828 } 829 } 830 831 function reduce( 832 uint[] memory self, 833 function (uint, uint) pure returns (uint) f 834 ) 835 internal 836 pure 837 returns (uint r) 838 { 839 r = self[0]; 840 for (uint i = 1; i < self.length; i++) { 841 r = f(r, self[i]); 842 } 843 } 844 845 function range(uint length) internal pure returns (uint[] memory r) { 846 r = new uint[](length); 847 for (uint i = 0; i < r.length; i++) { 848 r[i] = i; 849 } 850 } 851 } 852 853 854 contract Pyramid { 855 using ArrayUtils for *; 856 857 function pyramid(uint l) public pure returns (uint) { 858 return ArrayUtils.range(l).map(square).reduce(sum); 859 } 860 861 function square(uint x) internal pure returns (uint) { 862 return x * x; 863 } 864 865 function sum(uint x, uint y) internal pure returns (uint) { 866 return x + y; 867 } 868 } 869 870Another example that uses external function types: 871 872.. code-block:: solidity 873 874 // SPDX-License-Identifier: GPL-3.0 875 pragma solidity >=0.4.22 <0.9.0; 876 877 878 contract Oracle { 879 struct Request { 880 bytes data; 881 function(uint) external callback; 882 } 883 884 Request[] private requests; 885 event NewRequest(uint); 886 887 function query(bytes memory data, function(uint) external callback) public { 888 requests.push(Request(data, callback)); 889 emit NewRequest(requests.length - 1); 890 } 891 892 function reply(uint requestID, uint response) public { 893 // Here goes the check that the reply comes from a trusted source 894 requests[requestID].callback(response); 895 } 896 } 897 898 899 contract OracleUser { 900 Oracle constant private ORACLE_CONST = Oracle(address(0x00000000219ab540356cBB839Cbe05303d7705Fa)); // known contract 901 uint private exchangeRate; 902 903 function buySomething() public { 904 ORACLE_CONST.query("USD", this.oracleResponse); 905 } 906 907 function oracleResponse(uint response) public { 908 require( 909 msg.sender == address(ORACLE_CONST), 910 "Only oracle can call this." 911 ); 912 exchangeRate = response; 913 } 914 } 915 916.. note:: 917 Lambda or inline functions are planned but not yet supported. 918