Smart Contract Language Solidity tutorial series 8-solidity API

Source: Internet
Author: User
Tags assert

This is the Solidity Tutorial series article 8th introduces the solidity API, which mainly manifests as built-in special variables and functions that exist in the global namespace.

Write in front

Solidity is the Ethereum Smart Contract programming language, you should know about Ethereum and smart contracts before reading this article.
If you don't understand, it's recommended that you look at Ethereum first.

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).

You should not generate a random number based on Block.timestamp, now and Block.blockhash (unless you really need to), these values are affected to some extent by miners (for example, in XXX contracts, Dishonest miners may try to choose a hash for their own advantage.

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.

Use JavaScript to express the following:

    var msg = ‘0x8CbaC5e4d803bE2A3A5cd3DbE7174504c6DD0c1C‘    var hash = web3.sha3(msg)    var sig = web3.eth.sign(address, h).slice(2)    var r = `0x${sig.slice(0, 64)}`    var s = `0x${sig.slice(64, 128)}`    var v = web3.toDecimal(sig.slice(128, 130)) + 27

Subscribe to the Blockchain Technology column for a complete example of use.

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)//hexkeccak256 (6382179) keccak256 (A, 98, a)//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 ) to run sha256,ripemd160 or ecrecover on the private blockchain (private) may cause out-of-gas error. 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 addresses, in Wei units. *. 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 units, and returns false on failure. *. Call (...) returns (BOOL): initiates the underlying calls. 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, returns false** warning on Failure **:send () carries some risks: if the depth of the call stack exceeds 1024 or gas consumption, Trading will fail. So, 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 (type of 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): Selfdestruct alias In addition, all functions in the current contract can support calls, including the current function itself. # # Reference Document * [Special Variables and Functions] (https://solidity.readthedocs.io/en/develop/ Units-and-global-variables.html#units-and-globally-available-variables) * [in Layman's blockchain] (https://learnblockchain.cn/) -Learn blockchain to build the best Blockchain technology blog.

Smart Contract Language Solidity tutorial series 8-solidity API

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.