ERC 20コイン振替および残高照会--java(web 3 j)

7199 ワード

ERC 20コイン振替および残高照会–java(web 3 j)
準備作業:振り替える前にERC 20コインを持っていなければなりません.コイン発行スタンプはここで、テストネット上でテストすることができます.コイン発行の本質はスマート契約の導入であり、gasを消費する必要があり、コイン振替もethを手数料として消費する必要があるからだ.準備が完了したら、ERC 20コイン振替を直接行いましょう~web 3 jのAPIを呼び出して関連操作を完了し、必要なmaven依存:

    org.web3j
    core
    3.2.0


一:コイン振替
このコイン振替は、元の取引を構築することによって行われます.コードを見てください.主網親測有効~
/**
     * erc20    
     *
     * @param from                
     * @param to                  
     * @param value               
     * @param privateKey           
     * @param contractAddress       
     * @return     
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws IOException
     */
    public static String transferERC20Token(String from, String to, BigInteger value, String privateKey, String contractAddress) throws ExecutionException, InterruptedException, IOException {
        Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/c313bf2c97834ee29d933a996caaafb0"));
        //         ,   
        Credentials credentials = Credentials.create(privateKey);
        //  nonce,    
        BigInteger nonce;
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
        if (ethGetTransactionCount == null) {
            return null;
        }
        nonce = ethGetTransactionCount.getTransactionCount();
        //gasPrice gasLimit        
        BigInteger gasPrice;
        EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
        if (ethGasPrice == null) {
            return null;
        }
        gasPrice = ethGasPrice.getGasPrice();
        //BigInteger.valueOf(4300000L)                    
        BigInteger gasLimit = BigInteger.valueOf(60000L);
        //ERC20      
        value = value.multiply(VALUE);
        Function function = new Function(
                TRANSFER,
                Arrays.asList(new Address(to), new Uint256(value)),
                Collections.singletonList(new TypeReference() {
                }));
        //  RawTransaction    
        String encodedFunction = FunctionEncoder.encode(function);
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                contractAddress, encodedFunction);

        //  Transaction
        byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signMessage);
        //    
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        String hash = ethSendTransaction.getTransactionHash();
        if (hash != null) {
            return hash;
        }
        return null;
    }

二:コイン残高照会
private static final String DATA_PREFIX = "0x70a08231000000000000000000000000";
public static BigDecimal getBalance(String address, String contractAddress) throws IOException {
        String value = Admin.build(new HttpService("https://mainnet.infura.io"))
                .ethCall(org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address,
                contractAddress, DATA_PREFIX + address.substring(2)), DefaultBlockParameterName.PENDING).send().getValue();
        String s = new BigInteger(value.substring(2), 16).toString();
        BigDecimal balance = new BigDecimal(s).divide(WEI, 6, RoundingMode.HALF_DOWN);
        return balance;
    }

以上のコードホストネットワークで発行されたコインの親測は有効です.もしあなたに役に立つなら、いいねをクリックしましょう.
最後に、簡単なERC 20コイン契約を添付します
pragma solidity ^0.4.25;

contract ERC20Interface {

    string public constant name = "   ";
    string public constant symbol = "CSB";
    uint8 public constant decimals = 18;

    function totalSupply() public constant returns (uint);
    function balanceOf(address tokenOwner) public constant returns (uint balance);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);
    function allowance(address tokenOwner, address spender) public constant returns (uint remaining);

    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

contract SafeMath {

    function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
        if (a == 0) {
            return 0;
        }
        c = a * b;
        assert(c / a == b);
        return c;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a + b;
        assert(c >= a);
        return c;
    }
}


contract CSBToken is ERC20Interface, SafeMath {

  string public name;
  string public symbol;
  uint8 public decimals;
  uint256 public totalSupply;


  mapping (address => uint256) public balanceOf;

  mapping (address => mapping (address => uint256)) public allowanceOf;

   constructor() public payable {
      name = "   ";
      symbol = "CSB";
      decimals = 18;
      totalSupply = 1000000000 * 10 ** uint256(decimals);
      balanceOf[msg.sender] = totalSupply;
   }

    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;
      emit Transfer(_from, _to, _value);
       assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }

    function transfer(address _to, uint256 _value) public returns (bool success) {
       _transfer(msg.sender, _to, _value);
       return true;
   }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
       require(allowanceOf[_from][msg.sender] >= _value);
       allowanceOf[_from][msg.sender] -= _value;
       _transfer(_from, _to, _value);
       return true;
   }

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

   function allowance(address _owner, address _spender) view public returns (uint remaining){
     return allowanceOf[_owner][_spender];
   }

  function totalSupply() public constant returns (uint totalsupply){
      return totalSupply;
  }

  function balanceOf(address tokenOwner) public constant returns(uint balance){
      return balanceOf[tokenOwner];
  }

}