builtins.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. Builtin Functions and Variables
  2. ===============================
  3. .. _builtins:
  4. The Solidity language has a number of built-in variables and functions which give
  5. access to the chain environment or pre-defined functions. Some of these functions will
  6. be different on different chains.
  7. Block and transaction
  8. _____________________
  9. The functions and variables give access to block properties like block
  10. number and transaction properties like gas used, and value sent.
  11. gasleft() returns (uint64)
  12. ++++++++++++++++++++++++++
  13. Returns the amount of gas remaining the current transaction.
  14. .. note::
  15. ``gasleft()`` is not available on Solana.
  16. Gasprice is not used on Solana. There is compute budget which may not be
  17. exceeded, but there is no charge based on compute units used.
  18. blockhash(uint64 block) returns (bytes32)
  19. +++++++++++++++++++++++++++++++++++++++++
  20. Returns the blockhash for a particular block. This not possible for the current
  21. block, or any block except for the most recent 256. Do not use this a source of
  22. randomness unless you know what you are doing.
  23. .. note::
  24. This function is not available on Parity Substrate. When using Parity Substrate,
  25. use ``random()`` as a source of random data.
  26. .. note::
  27. This function is not available on Solana. There is the
  28. `recent block hashes account <https://edge.docs.solana.com/developing/runtime-facilities/sysvars#recentblockhashes>`_
  29. that looks useful at first glance, however it is not usable because:
  30. - This account is `deprecated <https://github.com/solana-labs/solana/pull/18875>`_.
  31. - It does not give any slot of block number, so it is not possible to provide a matching
  32. function signature.
  33. random(bytes subject) returns (bytes32)
  34. +++++++++++++++++++++++++++++++++++++++
  35. Returns random bytes based on the subject. The same subject for the same transaction
  36. will return the same random bytes, so the result is deterministic. The chain has
  37. a ``max_subject_len``, and if *subject* exceeds that, the transaction will be aborted.
  38. .. note::
  39. This function is only available on Parity Substrate.
  40. ``msg`` properties
  41. ++++++++++++++++++
  42. uint128 ``msg.value``
  43. The amount of value sent with a transaction, or 0 if no value was sent.
  44. bytes ``msg.data``
  45. The raw ABI encoded arguments passed to the current call.
  46. bytes4 ``msg.sig``
  47. Function selector from the ABI encoded calldata, e.g. the first four bytes. This
  48. might be 0 if no function selector was present. In Ethereum, constructor calls do not
  49. have function selectors but in Parity Substrate they do.
  50. address ``msg.sender``
  51. The sender of the current call. This is either the address of the contract
  52. that called the current contract, or the address that started the transaction
  53. if it called the current contract directly.
  54. ``tx`` properties
  55. +++++++++++++++++
  56. .. _gasprice:
  57. uint128 ``tx.gasprice``
  58. The price of one unit of gas. This field cannot be used on Parity Substrate,
  59. see the warning box below.
  60. .. note::
  61. ``tx.gasprice`` is not available on Solana.
  62. gasprice is not used on Solana. There is compute budget which may not be
  63. exceeded, but there is no charge based on compute units used.
  64. uint128 ``tx.gasprice(uint64 gas)``
  65. The total price of `gas` units of gas.
  66. .. warning::
  67. On Parity Substrate, the cost of one gas unit may not be an exact whole round value. In fact,
  68. if the gas price is less than 1 it may round down to 0, giving the incorrect appearance gas is free.
  69. Therefore, avoid the ``tx.gasprice`` member in favour of the function ``tx.gasprice(uint64 gas)``.
  70. To avoid rounding errors, pass the total amount of gas into ``tx.gasprice(uint64 gas)`` rather than
  71. doing arithmetic on the result. As an example, **replace** this bad example:
  72. .. code-block:: solidity
  73. // BAD example
  74. uint128 cost = num_items * tx.gasprice(gas_per_item);
  75. with:
  76. .. code-block:: solidity
  77. uint128 cost = tx.gasprice(num_items * gas_per_item);
  78. Note this function is not available on the Ethereum Foundation Solidity compiler.
  79. address ``tx.origin``
  80. The address that started this transaction. Not available on Parity Substrate or Solana.
  81. AccountInfo[] ``tx.accounts``
  82. Only available on Solana. See :ref:`account_info`. Here is an example:
  83. .. code-block:: solidity
  84. import {AccountInfo} from 'solana';
  85. contract SplToken {
  86. function get_token_account(address token) internal view returns (AccountInfo) {
  87. for (uint64 i = 0; i < tx.accounts.length; i++) {
  88. AccountInfo ai = tx.accounts[i];
  89. if (ai.key == token) {
  90. return ai;
  91. }
  92. }
  93. revert("token not found");
  94. }
  95. function total_supply(address token) public view returns (uint64) {
  96. AccountInfo account = get_token_account(token);
  97. return account.data.readUint64LE(33);
  98. }
  99. }
  100. address ``tx.program_id``
  101. The address or account of the currently executing program. Only available on
  102. Solana.
  103. ``block`` properties
  104. ++++++++++++++++++++++
  105. Some block properties are always available:
  106. uint64 ``block.number``
  107. The current block number.
  108. uint64 ``block.timestamp``
  109. The time in unix epoch, i.e. seconds since the beginning of 1970.
  110. Do not use either of these two fields as a source of randomness unless you know what
  111. you are doing.
  112. The other block properties depend on which chain is being used.
  113. .. note::
  114. Solana requires the `clock account <https://edge.docs.solana.com/developing/runtime-facilities/sysvars#clock>`_
  115. to present in the account for the instruction to use any of the ``block`` fields.
  116. On Solana, ``block.number`` gives the slot number rather than the block height.
  117. For processing, you want to use the slot rather the block height. Slots
  118. include empty blocks, which do not count towards the block height.
  119. Solana
  120. ~~~~~~
  121. uint64 ``block.slot``
  122. The current slot. This is an alias for ``block.number``.
  123. Parity Substrate
  124. ~~~~~~~~~~~~~~~~
  125. uint128 ``block.tombstone_deposit``
  126. The amount needed for a tombstone. Without it, contracts will disappear
  127. completely if the balance runs out.
  128. uint128 ``block.minimum_deposit``
  129. The minimum amonut needed to create a contract. This does not include
  130. storage rent.
  131. Ethereum
  132. ~~~~~~~~
  133. uint64 ``block.gaslimit``
  134. The current block gas limit.
  135. address payable ``block.coinbase``
  136. The current block miner's address.
  137. uint256 ``block.difficulty``
  138. The current block's difficulty.
  139. Error handling
  140. ______________
  141. assert(bool)
  142. ++++++++++++
  143. Assert takes a boolean argument. If that evaluates to false, execution is aborted.
  144. .. code-block:: solidity
  145. contract c {
  146. constructor(int x) {
  147. assert(x > 0);
  148. }
  149. }
  150. revert() or revert(string)
  151. ++++++++++++++++++++++++++
  152. revert aborts execution of the current contract, and returns to the caller. revert()
  153. can be called with no arguments, or a single `string` argument, which is called the
  154. `ReasonCode`. This function can be called at any point, either in a constructor or
  155. a function.
  156. If the caller is another contract, it can use the `ReasonCode` in a :ref:`try-catch`
  157. statement.
  158. .. code-block:: solidity
  159. contract x {
  160. constructor(address foobar) {
  161. if (a == address(0)) {
  162. revert("foobar must a valid address");
  163. }
  164. }
  165. }
  166. require(bool) or require(bool, string)
  167. ++++++++++++++++++++++++++++++++++++++
  168. This function is used to check that a condition holds true, or abort execution otherwise. So,
  169. if the first `bool` argument is `true`, this function does nothing, however
  170. if the `bool` arguments is `false`, then execution is aborted. There is an optional second
  171. `string` argument which is called the `ReasonCode`, which can be used by the caller
  172. to identify what the problem is.
  173. .. code-block:: solidity
  174. contract x {
  175. constructor(address foobar) {
  176. require(foobar != address(0), "foobar must a valid address");
  177. }
  178. }
  179. ABI encoding and decoding
  180. _________________________
  181. The ABI encoding depends on the target being compiled for. Substrate uses the
  182. `SCALE Codec <https://docs.substrate.io/reference/scale-codec/>`_.
  183. abi.decode(bytes, (*type-list*))
  184. ++++++++++++++++++++++++++++++++
  185. This function decodes the first argument and returns the decoded fields. *type-list* is a comma-separated
  186. list of types. If multiple values are decoded, then a destructure statement must be used.
  187. .. code-block:: solidity
  188. uint64 foo = abi.decode(bar, (uint64));
  189. .. code-block:: solidity
  190. (uint64 foo1, bool foo2) = abi.decode(bar, (uint64, bool));
  191. If the arguments cannot be decoded, contract execution will abort. This can happen if the encoded
  192. length is too short, for example.
  193. abi.encode(...)
  194. +++++++++++++++
  195. ABI encodes the arguments to bytes. Any number of arguments can be provided.
  196. .. code-block:: solidity
  197. uint16 x = 241;
  198. bytes foo = abi.encode(x);
  199. On Substrate, foo will be ``hex"f100"``. On Ethereum this will be ``hex"00000000000000000000000000000000000000000000000000000000000000f1"``.
  200. abi.encodeWithSelector(bytes4 selector, ...)
  201. ++++++++++++++++++++++++++++++++++++++++++++
  202. ABI encodes the arguments with the function selector first. After the selector, any number of arguments
  203. can be provided.
  204. .. code-block:: solidity
  205. bytes foo = abi.encodeWithSelector(hex"01020304", uint16(0xff00), "ABCD");
  206. On Substrate, foo will be ``hex"0403020100ff"``. On Ethereum this will be ``hex"01020304000000000000000000000000000000000000000000000000000000000000ff00"``.
  207. abi.encodeWithSignature(string signature, ...)
  208. ++++++++++++++++++++++++++++++++++++++++++++++
  209. ABI encodes the arguments with the ``bytes4`` hash of the signature. After the signature, any number of arguments
  210. can be provided. This is equivalent to ``abi.encodeWithSignature(bytes4(keccak256(signature)), ...)``.
  211. .. code-block:: solidity
  212. bytes foo = abi.encodeWithSignature("test2(uint64)", uint64(257));
  213. On Substrate, foo will be ``hex"296dacf0_0101_0000__0000_0000"``. On Ethereum this will be ``hex"296dacf0_0000000000000000000000000000000000000000000000000000000000000101"``.
  214. abi.encodePacked(...)
  215. +++++++++++++++++++++
  216. ABI encodes the arguments to bytes. Any number of arguments can be provided. The packed encoding only
  217. encodes the raw data, not the lengths of strings and arrays. For example, when encoding ``string`` only the string
  218. bytes will be encoded, not the length. It is not possible to decode packed encoding.
  219. .. code-block:: solidity
  220. bytes foo = abi.encodePacked(uint16(0xff00), "ABCD");
  221. On Substrate, foo will be ``hex"00ff41424344"``. On Ethereum this will be ``hex"ff0041424344"``.
  222. abi.encodeCall(function, ...)
  223. +++++++++++++++++++++++++++++
  224. ABI encodes the function call to the function which should be specified as ``ContractName.FunctionName``. The arguments
  225. are cast and checked against the function specified as the first argument.
  226. .. code-block:: solidity
  227. contract c {
  228. function f1() public {
  229. bytes foo = abi.encodeCall(c.bar, 102, true);
  230. }
  231. function bar(int a, bool b) public {}
  232. }
  233. Cryptography
  234. ____________
  235. keccak256(bytes)
  236. ++++++++++++++++
  237. This returns the ``bytes32`` keccak256 hash of the bytes.
  238. ripemd160(bytes)
  239. ++++++++++++++++
  240. This returns the ``bytes20`` ripemd160 hash of the bytes.
  241. sha256(bytes)
  242. +++++++++++++
  243. This returns the ``bytes32`` sha256 hash of the bytes.
  244. blake2_128(bytes)
  245. +++++++++++++++++
  246. This returns the ``bytes16`` blake2_128 hash of the bytes.
  247. .. note::
  248. This function is only available on Parity Substrate.
  249. blake2_256(bytes)
  250. +++++++++++++++++
  251. This returns the ``bytes32`` blake2_256 hash of the bytes.
  252. .. note::
  253. This function is only available on Parity Substrate.
  254. signatureVerify(address public_key, bytes message, bytes signature)
  255. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  256. Verify the ed25519 signature given the public key, message, and signature. This
  257. function returns ``true`` if the signature matches, ``false`` otherwise.
  258. The transactions which executes this function, needs an
  259. `ed25519 program <https://edge.docs.solana.com/developing/runtime-facilities/programs#ed25519-program>`_
  260. instruction with matching public key, message, and signature.
  261. In order to examine the instruction, the
  262. `instructions sysvar <https://edge.docs.solana.com/developing/runtime-facilities/sysvars#instructions>`_
  263. needs be in the accounts for the Solidity instruction as well.
  264. .. note::
  265. This function is only available on Solana.
  266. Mathematical
  267. ____________
  268. addmod(uint x, uint y, uint, k) returns (uint)
  269. ++++++++++++++++++++++++++++++++++++++++++++++
  270. Add x to y, and then divides by k. x + y will not overflow.
  271. mulmod(uint x, uint y, uint, k) returns (uint)
  272. ++++++++++++++++++++++++++++++++++++++++++++++
  273. Multiply x with y, and then divides by k. x * y will not overflow.
  274. Encoding and decoding values from bytes buffer
  275. ______________________________________________
  276. The ``abi.encode()`` and friends functions do not allow you to write or read data
  277. from an arbitrary offset, so the Solang dialect has the following functions. These
  278. methods are available on a ``bytes`` type.
  279. These functions are inspired by the `node buffer api <https://nodejs.org/api/buffer.html>`_.
  280. .. code-block:: solidity
  281. contract c {
  282. function f() public returns (bytes) {
  283. bytes data = new bytes(10);
  284. data.writeUint32LE(102, 0);
  285. data.writeUint64LE(0xdeadcafe, 4);
  286. return data;
  287. }
  288. function g(bytes data) public returns (uint64) {
  289. return data.readUint64LE(1);
  290. }
  291. }
  292. readInt8(uint32 offset)
  293. +++++++++++++++++++++++
  294. Read a signed ``int8`` from the specified offset.
  295. readInt16LE(uint32 offset)
  296. ++++++++++++++++++++++++++
  297. Read a signed ``int16`` from the specified offset in little endian order.
  298. readInt32LE(uint32 offset)
  299. ++++++++++++++++++++++++++
  300. Read a signed ``int32`` from the specified offset in little endian order.
  301. readInt64LE(uint32 offset)
  302. ++++++++++++++++++++++++++
  303. Read a signed ``int64`` from the specified offset in little endian order.
  304. readInt128LE(uint32 offset)
  305. +++++++++++++++++++++++++++
  306. Read a signed ``int128`` from the specified offset in little endian order.
  307. readInt256LE(uint32 offset)
  308. +++++++++++++++++++++++++++
  309. Read a signed ``int256`` from the specified offset in little endian order.
  310. readUint16LE(uint32 offset)
  311. +++++++++++++++++++++++++++
  312. Read an unsigned ``uint16`` from the specified offset in little endian order.
  313. readUint32LE(uint32 offset)
  314. +++++++++++++++++++++++++++
  315. Read an unsigned ``uint32`` from the specified offset in little endian order.
  316. readUint64LE(uint32 offset)
  317. +++++++++++++++++++++++++++
  318. Read an unsigned ``uint64`` from the specified offset in little endian order.
  319. readUint128LE(uint32 offset)
  320. ++++++++++++++++++++++++++++
  321. Read an unsigned ``uint128`` from the specified offset in little endian order.
  322. readUint256LE(uint32 offset)
  323. ++++++++++++++++++++++++++++
  324. Read an unsigned ``uint256`` from the specified offset in little endian order.
  325. readAddress(uint32 offset)
  326. ++++++++++++++++++++++++++
  327. Read an ``address`` from the specified offset.
  328. writeInt8(int8 value, uint32 offset)
  329. ++++++++++++++++++++++++++++++++++++
  330. Write a signed ``int8`` to the specified offset.
  331. writeInt16LE(int16 value, uint32 offset)
  332. ++++++++++++++++++++++++++++++++++++++++
  333. Write a signed ``int16`` to the specified offset in little endian order.
  334. writeInt32LE(int32 value, uint32 offset)
  335. ++++++++++++++++++++++++++++++++++++++++
  336. Write a signed ``int32`` to the specified offset in little endian order.
  337. writeInt64LE(int64 value, uint32 offset)
  338. ++++++++++++++++++++++++++++++++++++++++
  339. Write a signed ``int64`` to the specified offset in little endian order.
  340. writeInt128LE(int128 value, uint32 offset)
  341. ++++++++++++++++++++++++++++++++++++++++++
  342. Write a signed ``int128`` to the specified offset in little endian order.
  343. writeInt256LE(int256 value, uint32 offset)
  344. ++++++++++++++++++++++++++++++++++++++++++
  345. Write a signed ``int256`` to the specified offset in little endian order.
  346. writeUint16LE(uint16 value, uint32 offset)
  347. ++++++++++++++++++++++++++++++++++++++++++
  348. Write an unsigned ``uint16`` to the specified offset in little endian order.
  349. writeUint32LE(uint32 value, uint32 offset)
  350. ++++++++++++++++++++++++++++++++++++++++++
  351. Write an unsigned ``uint32`` to the specified offset in little endian order.
  352. writeUint64LE(uint64 value, uint32 offset)
  353. ++++++++++++++++++++++++++++++++++++++++++
  354. Write an unsigned ``uint64`` to the specified offset in little endian order.
  355. writeUint128LE(uint128 value, uint32 offset)
  356. ++++++++++++++++++++++++++++++++++++++++++++
  357. Write an unsigned ``uint128`` to the specified offset in little endian order.
  358. writeUint256LE(uint256 value, uint32 offset)
  359. ++++++++++++++++++++++++++++++++++++++++++++
  360. Write an unsigned ``uint256`` to the specified offset in little endian order.
  361. writeAddress(address value, uint32 offset)
  362. ++++++++++++++++++++++++++++++++++++++++++
  363. Write an ``address`` to the specified offset.
  364. writeString(string value, uint32 offset)
  365. ++++++++++++++++++++++++++++++++++++++++++++
  366. Write the characters of a ``string`` to the specified offset. This function does not
  367. write the length of the string to the buffer.
  368. writeBytes(bytes value, uint32 offset)
  369. ++++++++++++++++++++++++++++++++++++++++++
  370. Write the bytes of a Solidity dynamic bytes type ``bytes`` to the specified offset.
  371. This function does not write the length of the byte array to the buffer.
  372. Miscellaneous
  373. _____________
  374. print(string)
  375. +++++++++++++
  376. print() takes a string argument.
  377. .. code-block:: solidity
  378. contract c {
  379. constructor() {
  380. print("Hello, world!");
  381. }
  382. }
  383. .. note::
  384. print() is not available with the Ethereum Foundation Solidity compiler.
  385. When using Substrate, this function is only available on development chains.
  386. If you use this function on a production chain, the contract will fail to load.
  387. .. _selfdestruct:
  388. selfdestruct(address payable recipient)
  389. +++++++++++++++++++++++++++++++++++++++
  390. The ``selfdestruct()`` function causes the current contract to be deleted, and any
  391. remaining balance to be sent to `recipient`. This functions does not return, as the
  392. contract no longer exists.
  393. .. note::
  394. This function does not exist on Solana.
  395. String formatting using ``"{}".format()``
  396. +++++++++++++++++++++++++++++++++++++++++
  397. Sometimes it is useful to convert an integer to a string, e.g. for debugging purposes. There is
  398. a format builtin function for this, which is a method on string literals. Each ``{}`` in the
  399. string will be replaced with the value of an argument to format().
  400. .. code-block:: solidity
  401. function foo(int arg1, bool arg2) public {
  402. print("foo entry arg1:{} arg2:{}".format(arg1, arg2));
  403. }
  404. Assuming `arg1` is 5355 and `arg2` is true, the output to the log will be ``foo entry arg1:5355 arg2:true``.
  405. The types accepted by format are ``bool``, ``uint``, ``int`` (any size, e.g. ``int128`` or ``uint64``), ``address``,
  406. ``bytes`` (fixed and dynamic), and ``string``. Enums are also supported, but will print the ordinal value
  407. of the enum. The ``uint`` and ``int`` types can have a format specifier. This allows you to convert to
  408. hexadecimal ``{:x}`` or binary ``{:b}``, rather than decimals. No other types
  409. have a format specifier. To include a literal ``{`` or ``}``, replace it with ``{{`` or ``}}``.
  410. .. code-block:: solidity
  411. function foo(int arg1, uint arg2) public {
  412. // print arg1 in hex, and arg2 in binary
  413. print("foo entry {{arg1:{:x},arg2:{:b}}}".format(arg1, arg2));
  414. }
  415. Assuming `arg1` is 512 and `arg2` is 196, the output to the log will be ``foo entry {arg1:0x200,arg2:0b11000100}``.
  416. .. warning::
  417. Each time you call the ``format()`` some specialized code is generated, to format the string at
  418. runtime. This requires loops and so on to do the conversion.
  419. When formatting integers in to decimals, types larger than 64 bits require expensive division.
  420. Be mindful this will increase the gas cost. Larger values will incur a higher gas cost.
  421. Alternatively, use a hexadecimal ``{:x}`` format specifier to reduce the cost.