expressions.rst 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. Expressions
  2. ===========
  3. Solidity resembles the C family of languages. Expressions can use the following operators.
  4. Arithmetic operators
  5. ____________________
  6. The binary operators ``-``, ``+``, ``*``, ``/``, ``%``, and ``**`` are supported, and also
  7. in the assignment form ``-=``, ``+=``, ``*=``, ``/=``, and ``%=``. There is a
  8. unary operator ``-``.
  9. .. code-block:: solidity
  10. uint32 fahrenheit = celsius * 9 / 5 + 32;
  11. Parentheses can be used too, of course:
  12. .. code-block:: solidity
  13. uint32 celsius = (fahrenheit - 32) * 5 / 9;
  14. Operators can also come in the assignment form.
  15. .. code-block:: solidity
  16. balance += 10;
  17. The exponation (or power) can be used to multiply a number N times by itself, i.e.
  18. x :superscript:`y`. This can only be done for unsigned types.
  19. .. code-block:: solidity
  20. uint64 thousand = 1000;
  21. uint64 billion = thousand ** 3;
  22. No overflow checking is generated in `unchecked` blocks, like so:
  23. .. include:: ../examples/expression_unchecked.sol
  24. :code: solidity
  25. Bitwise operators
  26. _________________
  27. The ``|``, ``&``, ``^`` are supported, as are the shift operators ``<<``
  28. and ``>>``. These are also available in the assignment form ``|=``, ``&=``,
  29. ``^=``, ``<<=``, and ``>>=``. Lastly there is a unary operator ``~`` to
  30. invert all the bits in a value.
  31. Logical operators
  32. _________________
  33. The logical operators ``||``, ``&&``, and ``!`` are supported. The ``||`` and ``&&``
  34. short-circuit. For example:
  35. .. code-block:: javascript
  36. bool foo = x > 0 || bar();
  37. bar() will not be called if the left hand expression evaluates to true, i.e. x is greater
  38. than 0. If x is 0, then bar() will be called and the result of the ``||`` will be
  39. the return value of bar(). Similarly, the right hand expressions of ``&&`` will not be
  40. evaluated if the left hand expression evaluates to ``false``; in this case, whatever
  41. ever the outcome of the right hand expression, the ``&&`` will result in ``false``.
  42. .. code-block:: javascript
  43. bool foo = x > 0 && bar();
  44. Now ``bar()`` will only be called if x *is* greater than 0. If x is 0 then the ``&&``
  45. will result in false, irrespective of what bar() would return, so bar() is not
  46. called at all. The expression elides execution of the right hand side, which is also
  47. called *short-circuit*.
  48. Conditional operator
  49. ____________________
  50. The ternary conditional operator ``? :`` is supported:
  51. .. code-block:: javascript
  52. uint64 abs = foo > 0 ? foo : -foo;
  53. Comparison operators
  54. ____________________
  55. It is also possible to compare values. For, this the ``>=``, ``>``, ``==``, ``!=``, ``<``, and ``<=``
  56. is supported. This is useful for conditionals.
  57. The result of a comparison operator can be assigned to a bool. For example:
  58. .. code-block:: javascript
  59. bool even = (value % 2) == 0;
  60. It is not allowed to assign an integer to a bool; an explicit comparison is needed to turn it into
  61. a bool.
  62. Increment and Decrement operators
  63. _________________________________
  64. The post-increment and pre-increment operators are implemented by reading the variable's
  65. value before or after modifying it. ``i++``returns the value of ``i`` before incrementing,
  66. and ``++i`` returns the value of ``i`` after incrementing.
  67. this
  68. ____
  69. The keyword ``this`` evaluates to the current contract. The type of this is the type of the
  70. current contract. It can be cast to ``address`` or ``address payable`` using a cast.
  71. .. tabs::
  72. .. group-tab:: Polkadot
  73. .. include:: ../examples/polkadot/expression_this.sol
  74. :code: solidity
  75. .. group-tab:: Solana
  76. .. include:: ../examples/solana/expression_this.sol
  77. :code: solidity
  78. Function calls made via this are function calls through the external call mechanism; i.e. they
  79. have to serialize and deserialise the arguments and have the external call overhead. In addition,
  80. this only works with public functions.
  81. .. tabs::
  82. .. group-tab:: Polkadot
  83. .. include:: ../examples/polkadot/expression_this_external_call.sol
  84. :code: solidity
  85. .. group-tab:: Solana
  86. .. include:: ../examples/solana/expression_this_external_call.sol
  87. :code: solidity
  88. .. note::
  89. On Solana, ``this`` returns the program account. If you are looking for the data account, please
  90. use ``tx.accounts.dataAccount.key``.
  91. type(..) operators
  92. __________________
  93. For integer values, the minimum and maximum values the types can hold are available using the
  94. ``type(...).min`` and ``type(...).max`` operators. For unsigned integers, ``type(..).min``
  95. will always be 0.
  96. .. include:: ../examples/type_operator.sol
  97. :code: solidity
  98. The `EIP-165 <https://eips.ethereum.org/EIPS/eip-165>`_ interface value can be retrieved using the
  99. syntax ``type(...).interfaceId``. This is only permitted on interfaces. The interfaceId is simply
  100. an bitwise XOR of all function selectors in the interface. This makes it possible to uniquely identify
  101. an interface at runtime, which can be used to write a `supportsInterface()` function as described
  102. in the EIP.
  103. The contract code for a contract, i.e. the binary WebAssembly or Solana SBF, can be retrieved using the
  104. ``type(c).creationCode`` and ``type(c).runtimeCode`` fields, as ``bytes``. On EVM,
  105. the constructor code is in the ``creationCode`` and all the functions are in
  106. the ``runtimeCode``. Polkadot and Solana use the same
  107. code for both, so those fields will evaluate to the same value.
  108. .. include:: ../examples/retrieve_contract_code.sol
  109. :code: solidity
  110. .. note::
  111. ``type().creationCode`` and ``type().runtimeCode`` are compile time constants.
  112. It is not possible to access the code for the current contract. If this were possible,
  113. then the contract code would need to contain itself as a constant array, which would
  114. result in an contract of infinite size.
  115. Ether, Sol, and time units
  116. __________________________
  117. Any decimal numeric literal constant can have a unit denomination. For example
  118. ``10 minutes`` will evaluate to 600, i.e. the constant will be multiplied by the
  119. multiplier listed below. The following units are available:
  120. ============ =========================
  121. Unit Multiplier
  122. ``seconds`` 1
  123. ``minutes`` 60
  124. ``hours`` 3600
  125. ``days`` 86400
  126. ``weeks`` 604800
  127. ``lamports`` 1
  128. ``sol`` 1_000_000_000
  129. ``wei`` 1
  130. ``gwei`` 1_000_000_000
  131. ``ether`` 1_000_000_000_000_000_000
  132. ============ =========================
  133. Note that the Ethereum currency denominations ``ether``, ``gwei``, and ``wei`` are available when not
  134. compiling for Ethereum, but they will produce warnings.
  135. Casting
  136. _______
  137. Solidity is very strict about the sign of operations, and whether an assignment can truncate a
  138. value. You can force the compiler to accept truncations or sign changes by adding an
  139. explicit cast.
  140. Some examples:
  141. .. code-block:: solidity
  142. function abs(int bar) public returns (int64) {
  143. if (bar > 0) {
  144. return bar;
  145. } else {
  146. return -bar;
  147. }
  148. }
  149. The compiler will say:
  150. .. code-block:: none
  151. implicit conversion would truncate from int256 to int64
  152. Now you can work around this by adding a cast to the argument to return ``return int64(bar);``,
  153. however it is idiomatic to match the return value type with the argument type. Instead, implement
  154. multiple overloaded abs() functions, so that there is an ``abs()`` for each type.
  155. It is allowed to cast from a ``bytes`` type to ``int`` or ``uint`` (or vice versa), only if the length
  156. of the type is the same. This requires an explicit cast.
  157. .. code-block:: solidity
  158. bytes4 selector = "ABCD";
  159. uint32 selector_as_uint = uint32(selector);
  160. If the length also needs to change, then another cast is needed to adjust the length. Truncation and
  161. extension is different for integers and bytes types. Integers pad zeros on the left when extending,
  162. and truncate on the right. bytes pad on right when extending, and truncate on the left. For example:
  163. .. code-block:: solidity
  164. bytes4 start = "ABCD";
  165. uint64 start1 = uint64(uint4(start));
  166. // first cast to int, then extend as int: start1 = 0x41424344
  167. uint64 start2 = uint64(bytes8(start));
  168. // first extend as bytes, then cast to int: start2 = 0x4142434400000000
  169. A similar example for truncation:
  170. .. code-block:: javascript
  171. uint64 start = 0xdead_cafe;
  172. bytes4 start1 = bytes4(uint32(start));
  173. // first truncate as int, then cast: start1 = hex"cafe"
  174. bytes4 start2 = bytes4(bytes8(start));
  175. // first cast, then truncate as bytes: start2 = hex"dead"
  176. Since ``byte`` is an array of one byte, a conversion from ``byte`` to ``uint8`` requires a cast. This is
  177. because ``byte`` is an alias for ``bytes1``.