Smart Contract Language Solidity Tutorial Series 8 - Solidity API

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

write in front

Solidity is the Ethereum smart contract programming language. Before reading this article, you should have some understanding of Ethereum and smart contracts.
If you don't know it yet, I suggest you first look at what Ethereum is.

Welcome to subscribe to the blockchain technology column to read more comprehensive analysis articles.

The Solidity API is mainly represented by the special variables and functions built into Solidity. They exist in the global namespace and are mainly divided into the following categories:
1. Properties related to blocks and transactions
2. Error handling
3. Math and encryption functions
4. Address related
5. Contract related

Explain in detail below

Block And Transaction Properties

Used to provide some current information on the blockchain.

  • block.blockhash(uint blockNumber) returns (bytes32): Returns the hash value of the given block number, only the last 256 blocks are supported, and the current block is not included.
  • block.coinbase (address): The 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 block.
  • block.timestamp (uint): Unix timestamp of the current block (in seconds since 1970/1/1 00:00:00 UTC)
  • msg.data (bytes): Complete call data (calldata).
  • msg.gas (uint): The current gas remaining.
  • msg.sender (address): The address of the current call originator.
  • msg.sig (bytes4): The first four bytes of the call data (calldata) (for example: function identifier).
  • msg.value (uint): The ether attached to this message, in wei.
  • now (uint): timestamp of the current block (alias for block.timestamp)
  • tx.gasprice (uint) : The gas price of the transaction.
  • tx.origin (address): sender of the transaction (full call chain)

Note:
All member values ​​of msg, such as msg.sender, the value of msg.value can change due to each external function call or library function call (because msg is a global variable related to the call).

Block.timestamp, now and block.blockhash should not be used to generate a random number (unless you really need to), these values ​​are influenced to some extent by miners (for example in gambling contracts, dishonest miners may Try again to choose a hash that works for you).

For consecutive blocks on the same chain, the timestamp of the current block is always greater than the timestamp of the previous block.

For scalability reasons, you can only look up the last 256 blocks, all others will return 0.

error handling

  • assert(bool condition)
    is used to judge internal errors and throw an exception if the condition is not met
  • require(bool condition):
    used to judge input or external component errors, throw an exception when the conditions are not met
  • revert():
    terminates execution and restores the changed state

Math and encryption functions

  • addmod(uint x, uint y, uint k) returns (uint):
    computes (x + y) % k, addition supports arbitrary precision and does not overflow at 2**256, since version 0.5.0 asserts k ! = 0.
  • mulmod(uint x, uint y, uint k) returns (uint):
    computes (x * y) % k, multiplication supports arbitrary precision and does not overflow at 2**256, since version 0.5.0 asserts k ! = 0.
  • keccak256(…) returns (bytes32):
    Calculate the HASH value using Ethereum's (Keccak-256). Pack parameters tightly.
  • sha256(...) returns (bytes32):
    Calculates the hash value using SHA-256, tightly packing parameters.
  • sha3(…) returns (bytes32):
    alias for keccak256
  • ripemd160(...) returns (bytes20):
    Calculate the HASH value using RIPEMD-160. Pack parameters tightly.
  • ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address):
    Recover the address associated with the public key via elliptic curve signature, or return zero on error. It can be used to verify the signature data. If the returned result is the signer's public key address, then the data is correct.

    The ecrecover function requires four parameters, the hash result value of the signed data, r, s, and v from the signature result string respectively.
    r = signature[0:64]
    s = signature[64:128]
    v = signature[128:130]
    where v takes out the value either 00 or 01. To use it, we first convert it to an integer and add 27, so we get 27 or 28. v will be filled with 27 or 28 when the function is called.


    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
keccak256("ab", "c")
keccak256("abc")

keccak256(0x616263)  // hex
keccak256(6382179)
keccak256(97, 98, 99)   //ascii

address related

  • .balance (uint256):
    The balance of Address, in wei.

  • .transfer(uint256 amount):
    Send a given amount of ether to an address, in wei. Throws an exception on failure.

  • .send(uint256 amount) returns (bool):
    Send the given amount of ether to an address, in wei, returns false on failure.

  • .call(...) returns (bool):
    Initiate the underlying call. Returns false on failure.

  • .callcode(...) returns (bool):
    Initiate the underlying callcode call, returning false on failure.
    Use is discouraged and may be removed in the future.

  • .delegatecall(...) returns (bool):
    initiates the underlying delegatecall call, returns false on failure

For more information, refer to the address section .

Warning : the send() execution has some risks: if the depth of the call stack exceeds 1024 or the gas runs out, the transaction will fail. Therefore, in order to be safe, the return value of send must be checked, and if the transaction fails, the ether will be refunded. It would be better to 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):
    Destroy the current contract and send all its funds to the given address.
  • suicide(address recipient):
    alias for selfdestruct

In addition, all functions in the current contract can be called, including the current function itself.

Reference documentation

Explain the blockchain in simple terms - learn blockchain systematically and create the best blockchain technology blog.
If you want to have closer communication with me, you can choose to join my knowledge planet (planet members can join the WeChat technology exchange group)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325376589&siteId=291194637