【4】私有链发币

实现源码:

/*************************************
 * web3.js version :  1.0.0-beta.35  *
 *  */

// require filestream to read solidity file
const fs=require("fs")
const Web3=require("web3")
const solc=require("solc")
const web3Admin=require("web3admin")
////init Web3  rpc-http Connection through  private port :8545
let web3=new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"))

////read contract file
const solcfile=fs.readFileSync("TokenERC20.sol");
////compile solc file to json ABI
const output= solc.compile(solcfile.toString(),1)

var tokenContract=output.contracts[':TokenERC20']
////get token contract abi
const tokenContractABI=tokenContract.interface
////get token contract bytecode recognized by js code
const bytecode=tokenContract.bytecode

////asynchronized unlock default account for depolying token20Contract
web3.eth.getAccounts().then(data=>{

    web3.eth.personal.unlockAccount(data[0],'liujp')
    console.log("unlock account:"+data[0])

    /********************* deploy contract **********************
     *   new web3.eth.Contract(param1,param2,param3)            *
     *     param1: JSON.parse(tokenContractABI),                *
     *     param2: address:null,                                *
     *     param3: options{                                     *
     *                data:"0x"+bytecode,                       *
     *                from: account address,                    *
     *                gas:1000000                               *
     *     }                                                    */

    console.log("deploying the contract")
    const tokenContract20=new web3.eth.Contract(JSON.parse(tokenContractABI))
    tokenContract20.deploy({
        data:'0x'+bytecode,    //以0x开头
        //传递构造函数的参数(发行量:10000000000000,token名称:'XXXX',符号:"XXX")
        arguments:[10000000000000,'XXXX','XXX']
    }).send({
        from:"0x04a78a0ef3d868fdb9d7532c8b1ef7f49167f5a4",
        gas:1000000,
        gasPrice:'30000000'
    },function(error,transactionHash){
        console.log("send回调");
        console.log("error:"+error);
        console.log("send transactionHash:"+transactionHash);
    }).on('error', function(error){ console.error(error) })
        .then(function(newContractInstance){
            var newContractAddress=newContractInstance.options.address
            console.log("新合约地址:"+newContractAddress);
        });


    web3.eth.getBalance(data[0])
        .then(function(balance){
            console.log(balance)
        });
    // ////sendTransaction
    // web3.eth.sendTransaction({
    //     from:data[0],
    //     to: data[1],
    //     value:web3.utils.toWei("1")
    // });
    ////miner start mining
    // web3Admin.extend(web3)
    // console.log("turning on mining",web3.miner.start())
    // console.log("isMining?",web3.eth.mining)

    //执行结果:
    //send transactionHash:0x9bfb166a8abb3211b4c5303ae905e40c655e0480d8a5246bc3a8a260eb68333e
    ///新合约地址:0xFa5d8686fA1f899E88CD6d45B7Deab57d3F32caC
});
ERC20代币源码:
pragma solidity ^0.4.16;

interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }

contract TokenERC20 {
    string public name="LJP";
    string public symbol="LJP";
    uint8 public decimals = 18;  // 18 是建议的默认值
    uint256 public totalSupply=1000000000000;

    mapping (address => uint256) public balanceOf;  // 
    mapping (address => mapping (address => uint256)) public allowance;

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

    event Burn(address indexed from, uint256 value);


    function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
        totalSupply = initialSupply * 10 ** uint256(decimals);
        balanceOf[msg.sender] = totalSupply;
        name = tokenName;
        symbol = tokenSymbol;
    }


    function _transfer(address _from, address _to, uint _value) internal {
        require(_to != 0x0);
        require(balanceOf[_from] >= _value);
        require(balanceOf[_to] + _value > balanceOf[_to]);
        uint previousBalances = balanceOf[_from] + balanceOf[_to];
        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;
        Transfer(_from, _to, _value);
        assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }

    function transfer(address _to, uint256 _value) public {
        _transfer(msg.sender, _to, _value);
    }

    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;
    }

    function approve(address _spender, uint256 _value) public
        returns (bool success) {
        allowance[msg.sender][_spender] = _value;
        return true;
    }

    function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
        tokenRecipient spender = tokenRecipient(_spender);
        if (approve(_spender, _value)) {
            spender.receiveApproval(msg.sender, _value, this, _extraData);
            return true;
        }
    }

    function burn(uint256 _value) public returns (bool success) {
        require(balanceOf[msg.sender] >= _value);
        balanceOf[msg.sender] -= _value;
        totalSupply -= _value;
        Burn(msg.sender, _value);
        return true;
    }

    function burnFrom(address _from, uint256 _value) public returns (bool success) {
        require(balanceOf[_from] >= _value);
        require(_value <= allowance[_from][msg.sender]);
        balanceOf[_from] -= _value;
        allowance[_from][msg.sender] -= _value;
        totalSupply -= _value;
        Burn(_from, _value);
        return true;
    }
}
 
  1. 安装webstorm 平台 ,web3 0.0-beta35最新版、solc、等js库
  2. 准备erc20代币token合约
  3. 具体实现过程见源码
  4. 成功之后注意在控制台(geth console)处调用miner.start(),启动挖矿(当前web3Admin 调用miner仍存在问题,暂通过控制台执行)

猜你喜欢

转载自blog.csdn.net/dwjpeng2/article/details/81536857
今日推荐