Smart contract tokens compile, deploy, invoke

Source: Internet
Author: User
Tags constant constructor modifier require
first, the smart contract issue token process 1, the Smart Contract token agreement ERC20

Tokens represent digital assets in Ethereum, and not all tokens conform to specific specifications. Tokens based on ERC20 are easier to swap and can be DAPP compatible with a variety of wallets. Standardization is very advantageous, it means that these assets can be used for different platforms and projects, or can only be used in specific situations.

The interface standards that the ERC20 protocol needs to implement are as follows:

Contract ERC20 {

    /* Tokens total *
    /function totalsupply () constant Returns (uint totalsupply);

    /* Account Token query */
    function balanceof (address _owner) constant returns (uint balance);

    /* Token transfer (from your own account) */
    function Transfer (address _to, uint _value) returns (bool success);

    /* Token transfer (from escrow account) */
    function Transferfrom (address _from, address _to, uint _value) returns (bool success);

    /* _spender account set up in your own account *
    /function Approve (address _spender, uint _value) returns (bool success);

    /* Returns the amount that _spender is still allowed to extract from _owner. *
    /function allowance (address _owner, address _spender) constant returns (uint remaining);

    /* Event: Notification of Transfer Events *
    /Event Transfer (address indexed _from, address indexed _to, uint _value);

    /* Event: Delegate settings Event notification *
    /event Approval (address indexed _owner, address indexed _spender, uint _value);
}

A basic and complete token contract for the official function:

/* A relatively well-established token contract */pragma solidity ^0.4.16;

    /* Create a parent class, account Administrator */contract owned {address public owner;
    function owned () public {owner = Msg.sender;
        }/* modifier is a modified flag */modifier Onlyowner {require (Msg.sender = owner);
    _; }/* Modify the Administrator account, Onlyowner representative can only be the user administrator to modify the */function transferownership (address Newowner) onlyowner public {o
    Wner = Newowner; } */* Receiveapproval service contract instructs the token contract to transfer tokens from the sender's account to the account of the service contract (by invoking the service contract's */interface Tokenrecipient {function Receiveapproval ( Address _from, uint256 _value, Address _token, bytes _extradata) public;             } contract the public variable of TOKENERC20 {//tokens (token), string, and the name;           Token name string public symbol;     Token symbol uint8 Public decimals = 18;     Token decimal digits, 18 is the default, try not to change uint256 public totalsupply;

    Total tokens//record the number of tokens in each account mapping (address = uint256) public balanceof; A account exists with B Account funds mapping (address + mapping (address = uint256)) public allowance;

    Transfer Notification Events event Transfer (address indexed from, address indexed to, uint256 value);

    Destroy amount Notification Events event Burn (address indexed from, uint256 value);
    /* Constructor */function TokenERC20 (uint256 initialsupply, String tokenname, String Tokensymbol  public {totalsupply = initialsupply * * * uint256 (decimals);                    Calculates the number of tokens according to decimals balanceof[msg.sender] = totalsupply;                                       The number of tokens given to the generator name = Tokenname;                                   Set the name of the token symbol = Tokensymbol; Set symbol for tokens}/* Private trading function */function _transfer (address _from, address _to, uint _value) Internal {//
        Prevent transfer to 0x0, replace this function with burn require (_to! = 0x0);
        Detect if the sender has sufficient funds require (Balanceof[_from] >= _value);
        Check for overflow (data type overflow) require (balanceof[_to] + _value > balanceof[_to]);
      Save this as a future assertion, and the function will end up with a test  UINT previousbalances = Balanceof[_from] + balanceof[_to];
        Reduced sender Asset Balanceof[_from]-= _value;
        Increase the recipient's assets balanceof[_to] + = _value;
        Transfer (_from, _to, _value);
    Assertion detection, should not be the wrong assert (Balanceof[_from] + balanceof[_to] = = previousbalances); }/* Pass tokens */function transfer (address _to, uint256 _value) public {_transfer (Msg.sender, _to, _valu
    e);  }/* Transfer assets from other accounts */function Transferfrom (address _from, address _to, uint256 _value) public Returns (BOOL success)     {Require (_value <= allowance[_from][msg.sender]);
        Check allowance Allowance[_from][msg.sender]-= _value;
        _transfer (_from, _to, _value);
    return true; }/* Authorizes a third party to transfer tokens from the sender's account and then perform a third-party transfer operation via the Transferfrom () function */function approve (address _spender, uint256 _value) publi
        C Returns (bool success) {Allowance[msg.sender][_spender] = _value;
    return true;
  }

    /*  Set up allowances for other addresses and notify the sender to notify the token contract, the token contract notifies the service contract Receiveapproval, and the service contract instructs the token to transfer the token from the sender's account to the account of the service contract (by invoking the transferfrom of the service contract) */ function Approveandcall (address _spender, uint256 _value, bytes _extradata) public Returns (BOOL Succes
        s) {Tokenrecipient spender = tokenrecipient (_spender);
            if (Approve (_spender, _value)) {Spender.receiveapproval (Msg.sender, _value, this, _extradata);
        return true; }}/** * destroys tokens * * function burn (uint256 _value) public Returns (bool success) {Require (Balan   Ceof[msg.sender] >= _value);            Check If the sender has enough balanceof[msg.sender]-= _value;                      Subtract from the sender totalsupply-= _value;
        Updates totalsupply Burn (Msg.sender, _value);
    return true;
        }/** * Destroys tokens from other accounts */function Burnfrom (address _from, uint256 _value) public Returns (bool success) { Require (BalaNceof[_from] >= _value);    Check If the targeted balance is enough require (_value <= allowance[_from][msg.sender]);                         Check allowance Balanceof[_from]-= _value;             Subtract from the targeted balance allowance[_from][msg.sender]-= _value;                              Subtract from the sender ' s allowance totalsupply-= _value;
        Update totalsupply Burn (_from, _value);
    return true; }}/******************************************//* Advanced tokens Starts here *//**************************
    /Contract Myadvancedtoken is owned, TokenERC20 {uint256 public sellprice;

    uint256 public buyprice;

    /* Freeze Account */mapping (address = bool) public frozenaccount; /* This generates a public event on the blockchain that would notify clients */event Frozenfunds (address target, BOOL

    Frozen); /* Constructor */function MyadvancedtokEn (uint256 initialsupply, String tokenname, String tokensymbol) TokenERC20 (initialsupply, to Kenname, Tokensymbol) public {}/* transfers, added account freezes to parent class */function _transfer (address _from, address _to, uint _value)                               Internal {require (_to! = 0x0); Prevent transfer to 0x0 address.               Use Burn () instead require (Balanceof[_from] >= _value); Check If the sender has enough require (Balanceof[_to] + _value > balanceof[_to]);                     Check for overflows require (!frozenaccount[_from]);                       Check If sender is frozen require (!frozenaccount[_to]);                         Check If recipient is frozen balanceof[_from]-= _value;                           Subtract from the sender balanceof[_to] + = _value;
    Add the same to the recipient Transfer (_from, _to, _value); *//Add funds to a designated account function MinttokenRess target, uint256 mintedamount) onlyowner public {Balanceof[target] + = Mintedamount;
        Totalsupply + = Mintedamount;
        Transfer (0, this, mintedamount);

    Transfer (this, target, mintedamount); }///Thaw Account function Freezeaccount (address target, BOOL freeze) Onlyowner Public {Frozenaccount[ta
        Rget] = freeze;
    Frozenfunds (target, Freeze);
        } function Setprices (uint256 newsellprice, uint256 newbuyprice) onlyowner public {sellprice = Newsellprice;
    Buyprice = Newbuyprice; }//@notice Buy tokens from contract by sending ether function Buy () payable public {UINT Amount = MSG               . Value/buyprice;              Calculates the amount _transfer (this, msg.sender, amount); Makes the transfers} function sell (uint256 amount) public {require (this.balance >= amount * SellP      Rice); Checks if the contract have enough ether to buy _transfER (msg.sender, this, amount);          Makes the transfers Msg.sender.transfer (amount * sellprice); Sends ether to the seller. It ' s important to does this last to avoid recursion attacks}}

2, the token contract compiles, deploys, calls

Tokens are deployed in many ways, local tools are truffle, the official web page compiler remix, and the Ethereum official wallet can also be completed contract deployment. This article mainly introduces the method of compiling, deploying and testing the private chain from the official remix compiler. and add tokens to the official Ethereum wallet to complete the transfer.

Official remix compiler address: http://remix.ethereum.org/

Contract compilation, the step diagram is as follows: writes the contract code to the compiler code editing area. Code debugging information appears on the right side of the compile toolbar that executes "Start to compile" compilation.


Contract deployment, step: Click on the right toolbar run option and the following screen appears. Select the network you want to deploy and select the external account you want to deploy for the contract. After filling in the constructor parameters, click Create to complete the deployment (deploying the network requires a node to mine, an external account with sufficient etheric currency, and the account has been unlocked)


Remix compiler contract invocation sample deployment as shown in the following figure, the function defined within the contract is displayed, and you can invoke the attempt yourself.

As mentioned earlier, the tokens that are deployed in accordance with the ERC20 Agreement are well-compatible, and you can add tokens to the official wallet to complete the transfer.

The command line launches the official wallet and connects the wallet to the private chain network of the deployment contract, as follows:

./ethereum\ Wallet--rpc http://10.11.178.42:8545

In the Wallet above the toolbar select contacts, select "WATCH TOKEN", the location of the token deployment address to fill the address bar, click OK to complete the addition, as shown below.


Select Send in the toolbar, fill in the relevant token information, make sure to click Send to complete the transfer.

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.