web3j bulk transfer

Use web3j to connect geth and transfer funds. The basic transfer function can be written as follows:

//Ethereum transfer
    //from: account of Transferor
    //Password: transfer out password
    //addrTo: collection account
    //value: transfer amount
    public  String transferEth(String from,String password,String to,BigInteger value) throws  Exception
    {
        EthGetTransactionCount ethGetTransactionCount = ethClient.ethGetTransactionCount(
                from, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
       PersonalUnlockAccount personalUnlockAccount = ethClient.personalUnlockAccount(from,password).send();
       if (personalUnlockAccount.accountUnlocked())
        {
            BigInteger gasPrice = Contract.GAS_PRICE;
            BigInteger gasLimit = Contract.GAS_LIMIT.divide(new BigInteger("2"));
            synchronized(TestLocal.class) {
                Transaction transaction = Transaction.createEtherTransaction(from,nonce,gasPrice,gasLimit,to,value);
                EthSendTransaction transactionResponse = ethClient.ethSendTransaction(transaction).sendAsync().get();;
                if(transactionResponse.hasError()){
                    String message=transactionResponse.getError().getMessage();
                    System.out.println("transaction failed,info:"+message);
                    Utils.writeFile("F:/testErr.txt","transaction failed,info:"+message);
                    return message;
                }else{
                    String hash=transactionResponse.getTransactionHash();
                    System.out.println("transaction from "+from+" to "+to+" amount:"+value);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //writeFile("transaction from "+from+" to "+to+" amount:"+value+" time:"+df.format(new Date()));
                    return  hash;
                }
            }
 
        }
        return null;
    }

In the above function, if the transfer fails, the failure result will be written to F:/testErr.txt.

Batch transfer is to call the above function continuously in the for loop for transfer. Now set to transfer from addr0 to addr1 10 times in a row:

for(int i=0;i<10;i++)
{
     transferEth(addr0,"123",addr1,Convert.toWei("1", Convert.Unit.ETHER).toBigInteger());
}

First, query the balance of addr1. There are 102.9110385 ether:

> web3.formwei(eth.getBalance(eth.accounts[1]))
102.9110385

When running the batch transfer function, an error will be reported on the console:

After querying the balance, only one transaction was successfully transferred:

> web3.formwei(eth.getBalance(eth.accounts[1]))
103.9110385

To view the printed error message textErr.txt:

It can be seen that 9 transactions failed and only the first one succeeded. The failure message is due to duplicate transactions. The preliminary judgment is that there is something wrong with nonce setting. For a single transfer, nonce can be queried from the blockchain. In the for loop, you need to increase nonce by yourself.

Modify the transferEth function as follows:

public  String transferEthWith(String from,String password,String to,BigInteger value) throws  Exception
    {
        EthGetTransactionCount ethGetTransactionCount = ethClient.ethGetTransactionCount(
                from, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        if(gNoce == null)
            gNoce = nonce;
        PersonalUnlockAccount personalUnlockAccount = ethClient.personalUnlockAccount(from,password).send();
        if (personalUnlockAccount.accountUnlocked())
        {
            BigInteger gasPrice = Contract.GAS_PRICE;
            BigInteger gasLimit = Contract.GAS_LIMIT.divide(new BigInteger("2"));
            synchronized(TestLocal.class) {
                Transaction transaction = Transaction.createEtherTransaction(from,gNoce,gasPrice,gasLimit,to,value);
                gNoce = gNoce.add(new BigInteger("1"));
                EthSendTransaction transactionResponse = ethClient.ethSendTransaction(transaction).sendAsync().get();;
                if(transactionResponse.hasError()){
                    String message=transactionResponse.getError().getMessage();
                    System.out.println("transaction failed,info:"+message);
                    Utils.writeFile("F:/testErr.txt","transaction failed,info:"+message);
                    return message;
                }else{
                    String hash=transactionResponse.getTransactionHash();
                    System.out.println("transaction from "+from+" to "+to+" amount:"+value);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //writeFile("transaction from "+from+" to "+to+" amount:"+value+" time:"+df.format(new Date()));
                    return  hash;
                }
            }
 
        }
        return null;
    }

Viewing the log information of geth, you can see that multiple transactions have been submitted:

After querying the account balance of addr1, it changed from 103 to 113. The transfer succeeded:

> web3.formwei(eth.getBalance(eth.accounts[1]))
113.9110385

Share a popular interactive tutorial that is rare in the whole network:

  • web3j , mainly for java and android programmers to explain the development of blockchain Ethereum around the web3j library.

Original: blog.csdn.net/lizhijun301/article/details/80365712

Tags: Blockchain network Java Android

Posted on Sun, 09 Feb 2020 11:54:21 -0500 by martin_g