Smart Contract Language Solidity Tutorial Series 2-Introduction to address types

Source: Internet
Author: User

Solidity Tutorial Series second article-solidity address type description.
For a complete list of articles in the solidity series, see Category-solidity.

Write in front

Solidity is the Ethereum Smart Contract programming language, before reading this article, you should have an understanding of ethereum, smart contracts, if you do not understand, it is recommended that you first see what Ethereum is

The first half of this article is a reference to the solidity official document (currently the latest version: 0.4.20) for translation, and the latter part is the use of the actual contract code instance description type.

Address Type

Address type addr is a value type,

address : 20 bytes (length of an ethereum address), address type also has members, address is the basis of all contracts
Supported operators:

    • <=, <, = =,! =, >= and >

      Note: Starting with 0.5.0, the contract no longer inherits from the address type, but can still be explicitly converted to an address.

Member of Address type
  • Balance properties and Transfer () functions
    Here is a quick index of the associated member of the address type
    The balance is used to check the balance of the account, transfer () is used to send the etheric currency (in Wei units).
    Such as:

    address x = 0x123;address myAddress = this;if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);

    Note : If X is a contract address, the fallback function of the contract (the fallback function) is executed with the transfer call (this is the EVM feature), and if it fails due to gas consumption or other reasons, the transfer transaction is restored and the contract is thrown off abnormally.

    With regard to the fallback function (fallback function), it is simply a function of no function name in the contract, in the following code case, further explaining the use of the fallback function (fallback).

  • Send () function
    Send corresponds to transfer, but the lower level. If execution fails, transfer does not stop because of an exception, and send returns false.

    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.

  • Call (), Callcode (), and Delegatecall () functions
    To interact with non-ABI protocol contracts, you can use the call () function, which is used to send raw data to another contract, support any number of parameters of any type, and each parameter is packaged into 32 bytes per rule (ABI protocol) and stitched together. An exception is if the first parameter is exactly 4 bytes, in which case it is considered to be used directly according to the function signature specified by the function defined by the ABI protocol. If you want to send only the body of a message, you need to avoid the first parameter being 4 bytes. As in the following example:

    address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;nameReg.call("register", "MyName");nameReg.call(bytes4(keccak256("fun(uint256)")), a);

    The Call function returns a bool value to indicate whether the execution was successful or not. Normal end returns True, which returns false for abnormal termination. However, you cannot get the result data because you need to know in advance the encoding and data size of the returned data (because you do not know the protocol format used by the other party, so you do not know how the returned results are parsed).
    You can also provide a . Gas () decorator for invocation:

    namReg.call.gas(1000000)("register", "MyName");

    Similarly, you can also provide the following etheric coins:

    nameReg.call.value(1 ether)("register", "MyName");

    Decorators can be mixed, and the order of decorator calls doesn't matter.

    nameReg.call.gas(1000000).value(1 ether)("register", "MyName");

    Note: Gas or value modifiers cannot be used on overloaded functions at this time, a workaround is to introduce a special case for gas and value and just re-check whether they Is present at the point of overload resolution. (This sentence I am afraid of inaccurate translation, quoting the original text)

    Also we can use Delegatecall (), which differs from the call method in that only the code executes, while other aspects, such as (storage, balance, etc.) are used for the current contract data. The purpose of the Delegatecall () method is to execute the library code in another contract. So developers need to ensure that the storage variables in the two contracts are compatible to ensure that Delegatecall () can execute smoothly. Prior to the Homestead phase, only one restricted Callcode () method was available, but Callcode did not provide access to msg.sender,msg.value.

    The above three methods call (), Delegatecall (), Callcode () are the underlying message-passing calls, and are best used only as a last resort because they undermine the type safety of solidity.
    . Gas () can be used under call (), Callcode (), and Delegatecall () functions, Delegatecall () does not support. Value ()

    Note: All contracts inherit the address's members, so you can use This.balance to query the balance.
    Callcode is discouraged and will be removed later.

    Warning: All of the above functions are the underlying functions and should be used with exceptional care. When invoking an unknown, potentially malicious contract, when you give control to it, it may return to your contract, so be prepared to respond to a situation where your state variable might be maliciously tampered with when the call returns.

Address Constants (Addr literals)

A hexadecimal constant that can pass the address legality check (checksum test) will be considered an address, such as 0XDCAD3A6D3569DF655070DED06CB7A1B2CCD1D3AF. A 39 to 41-bit hexadecimal constant that cannot be checked by the address legitimacy will prompt a warning to be treated as a normal rational number constant.

Address legality check defined in EIP-55

Contract examples explain contract case code
pragma solidity ^0.4.0;contract AddrTest{    event logdata(bytes data);    function() payable {        logdata(msg.data);    }    function getBalance() returns (uint) {        return this.balance;    }    uint score = 0;    function setScore(uint s) public {        score = s;    }    function getScore() returns ( uint){        return score;    }}contract CallTest{    function deposit() payable {    }    event logSendEvent(address to, uint value);    function transferEther(address towho) payable {        towho.transfer(10);        logSendEvent(towho, 10);    }    function callNoFunc(address addr) returns (bool){        return addr.call("tinyxiong", 1234);    }    function callfunc(address addr) returns (bool){        bytes4 methodId = bytes4(keccak256("setScore(uint256)"));        return addr.call(methodId, 100);    }      function getBalance() returns (uint) {        return this.balance;    }  }
Reference documents

Solidity official documents-type

In-depth blockchain-the system learns blockchain to create the best blockchain technology blog.

Smart Contract Language Solidity Tutorial Series 2-Introduction to address types

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.