Smart Contract Language Solidity tutorial Series 8-solidity API (special variables and functions)

Source: Internet
Author: User
Tags aliases assert

Solidity API is mainly manifested as solidity built-in special variables and functions, they exist in the global namespace, mainly divided into the following categories:

    1. Properties related to blocks and transactions
    2. About error Handling
    3. About math and encryption features
    4. Address related
    5. Contract related

Below is a detailed explanation of

Blocks and trading attributes (block and Transaction properties)

Used to provide some current information about the blockchain.

    • Block.blockhash (UINT Blocknumber) returns (BYTES32): Returns the hash value for a given chunk number, only the last 256 chunks are supported, and does not contain the current chunk.
    • Block.coinbase: Address of the current block miner.
    • Block.difficulty (UINT): the difficulty of the current block.
    • Block.gaslimit (UINT): The gaslimit of the current block.
    • Block.number (UINT): The block number of the current chunk.
    • Block.timestamp (UINT): The Unix timestamp of the current block (the number of seconds elapsed since 1970/1/1 00:00:00 UTC)
    • Msg.data (bytes): Full invocation data (Calldata).
    • Msg.gas (UINT): gas currently remaining.
    • Msg.sender: The address of the current call initiator.
    • Msg.sig (BYTES4): The first four bytes of the call data (Calldata) (for example, the function identifier).
    • Msg.value (UINT): This message comes with the etheric currency, in units of Wei.
    • Now (UINT): Timestamp of the current block (alias of Block.timestamp)
    • Tx.gasprice (UINT): The gas price of a trade.
    • Tx.origin (address): The sender of the transaction (full call chain)

Attention:
All member values of MSG, such as the value of Msg.sender,msg.value, can be changed because of each external function call, or library function calls (because MSG is the global variable that is associated with the call).

Should not be based on Block.timestamp, now and Block.blockhash to produce a random number (unless you really need to), these values are partly affected by miners (for example, in a gambling contract, dishonest miners may try to choose a hash of their own favor).

The timestamp (timestamp) of the current chunk will always be greater than the timestamp of the previous chunk for contiguous chunks on the same chain.

For extensibility reasons, you can only check the last 256 blocks, and all the others will return 0.

Error handling
    • ASSERT (bool condition)

Used to determine an internal error that throws an exception if the condition is not satisfied

    • Require (bool condition):
      Used to determine an input or external component error that throws an exception if the condition is not met

    • Revert ():
      Terminates execution and restores the changed state

Math and encryption functions
    • Addmod (uint x, uint y, uint k) returns (UINT):
      Calculates (x + y)% K, the addition supports arbitrary precision and does not overflow at 2**256, starting with 0.5.0 to assert K! = 0.
    • Mulmod (uint x, uint y, uint k) returns (UINT):
      Calculate (x * y)% K, the multiplication supports arbitrary precision and does not overflow at 2**256, starting with the 0.5.0 version asserts K! = 0.
    • KECCAK256 (...) returns (BYTES32):
      Use Ethereum (Keccak-256) to calculate the hash value. Tightly packed parameters.
    • SHA256 (...) returns (BYTES32):
      Use SHA-256 to calculate hash values and tightly package parameters.
    • SHA3 (...) returns (BYTES32):
      Aliases for keccak256
    • RIPEMD160 (...) returns (BYTES20):
      Use RIPEMD-160 to calculate the hash value. Tightly packed parameters.
    • Ecrecover (bytes32 hash, Uint8 V, Bytes32 R, Bytes32 s) returns (address):
      The address associated with the public key is recovered by an elliptic curve signature, or zero is returned on error. can be used to verify the signature data, if the return result is the signer's public key address, then the data is correct.

The Ecrecover function requires four parameters and requires a hash result value of the signed data, r,s,v from the signature result string, respectively.
r = signature[0:64]
s = signature[64:128]
v = signature[128:130]
Where v takes out a value of 00 or 01. To use it, we'll first turn it into an integer, plus 27, so we'll get 27 or 28. When the function is called, V fills in 27 or 28.

In JavaScript, here is an example:

  • var msg = ' 0x8cbac5e4d803be2a3a5cd3dbe7174504c6dd0c1c '
  • var hash = WEB3.SHA3 (msg)
  • var sig = Web3.eth.sign (Address, h). Slice (2)
  • var r = ' 0x${sig.slice (0, + )} '
  • var s = ' 0x${sig.slice (+ + )} '
  • var v = web3.todecimal (Sig.slice ( +)) +

Tightly packed parameters (tightly packed) means that parameters do not complement, are directly connected, and the next few are equal.

    • keccak256 ("AB", "C")
    • keccak256 ("abc")
    • keccak256 (0x616263) //Hex
    • keccak256 (6382179)
    • KECCAK256 (98, //ascii )

If a fill is required, you can use an explicit type conversion: keccak256 ("\x00\x12") is the same as keccak256 (UInt16 (0x12)).

Note that constants will be packaged using the minimum number of bytes required to store them, such as keccak256 (0) = = keccak256 (uint8 (0)) and keccak256 (0x12345678) = = keccak256 (UInt32 (0x12345678 ))

Out-of-gas error may occur when running sha256,ripemd160 or ecrecover on private blockchain (private). Because the private chain implements a precompiled contract, the contract does not really exist until the first message is received (although their contract code is hard-coded). Sending a message to a nonexistent contract can cause out-of-gas problems. One solution (workaround) is to initialize each of these contracts by sending 1 Wei to them before you actually use them. There is no such problem on the official and test chain.

Address related
    • . Balance (uint256):
      The balance of address, in Wei.

    • . Transfer (uint256 amount):
      Sends a given number of ether to an address, in Wei units. Throws an exception if it fails.

    • . Send (uint256 amount) returns (BOOL):
      Sends a given number of ether to an address, in Wei, and returns false on failure.

    • . Call (...) returns (BOOL):
      Initiates the underlying call invocation. returns false on failure.

    • . Callcode (...) returns (BOOL):
      Initiates the underlying Callcode call and returns false on failure.
      Discourage use and may be removed in the future.

    • . Delegatecall (...) returns (BOOL):
      Initiates the underlying Delegatecall call and returns false on failure

For more information, refer to the address article.

Warning: Send () carries some risks: if the depth of the call stack exceeds 1024 or gas consumption, the transaction will fail. Therefore, to ensure security, the return value of send must be checked, and if the transaction fails, the etheric currency is rolled back. It would be better if you use transfer.

Contract related
    • This (the type of the current contract):
      Represents the current contract, which can be explicitly converted to address
    • Selfdestruct (Address recipient):
      Destroys the current contract and sends all its funds to the given address.
    • Suicide (address recipient):
      Aliases for Selfdestruct

In addition, all functions in the current contract can support calls, including the current function itself.

Round circle block chain brings together a large number of blockchain teachers, to take the tutor on duty system, for students to solve technical problems in real-time. Please pay attention to the circle-radius blockchain Knowledge planet and mentor. (For training inquiries, please contact the Captain 13826054890 mobile phone number)

The author tiny Xiong, focusing on blockchain bottom-up research and ethereum development. Is the circle of the block chain mentor, more bear Teacher's articles and videos please pay attention to round circle ring public number.

Smart Contract Language Solidity tutorial Series 8-solidity API (special variables and functions)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.