前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >web3j批量转账

web3j批量转账

作者头像
笔阁
发布2018-09-04 17:17:54
1.8K0
发布2018-09-04 17:17:54
举报
文章被收录于专栏:极客编程极客编程

使用web3j来连接geth并转账,基本转账函数可以这样写:

代码语言:javascript
复制
//以太坊转账
    //from:转出方账户
    //password:转出方密码
    //addrTo:收款账户
    //value:转账额
    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;
    }

上面函数中,当转账失败,会将失败结果写入F:/testErr.txt中。

批量转账就是在for循环中连续调用上面这个函数进行转账,现在设置从addr0向addr1连续转账10次:

代码语言:javascript
复制
for(int i=0;i<10;i++)
{
     transferEth(addr0,"123",addr1,Convert.toWei("1", Convert.Unit.ETHER).toBigInteger());
}

先查询addr1的余额,有102.9110385个ether:

代码语言:javascript
复制
> web3.formwei(eth.getBalance(eth.accounts[1]))
102.9110385

运行批量转账函数,会发现控制台报错:

查询余额,发现只转成功了一笔:

代码语言:javascript
复制
> web3.formwei(eth.getBalance(eth.accounts[1]))
103.9110385

查看打印的错误信息textErr.txt:

可见失败了9笔交易,只有第一笔交易成功了。失败的信息是因为有交易重复。初步判断是nonce设置出问题了。对于单笔转账,nonce可以从区块链查询到,在for循环里,需要自己去递增nonce。

修改transferEth函数如下:

代码语言:javascript
复制
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;
    }

查看geth的log信息,可以看到提交了多笔交易:

查询addr1的账户余额,从103变成113了,转账成功:

代码语言:javascript
复制
> web3.formwei(eth.getBalance(eth.accounts[1]))
113.9110385

分享个很受欢迎全网稀缺的互动教程:

  • web3j,主要是针对java和android程序员围绕web3j库进行区块链以太坊开发的讲解。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
区块链
云链聚未来,协同无边界。腾讯云区块链作为中国领先的区块链服务平台和技术提供商,致力于构建技术、数据、价值、产业互联互通的区块链基础设施,引领区块链底层技术及行业应用创新,助力传统产业转型升级,推动实体经济与数字经济深度融合。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档