web3j 发送以太币(ropsten 测试网络)

这里连接的ropsten网络,本来想写这么进行ERC20 代币的转账,可是一直因为gas 的原因没成功,对于这个我也不是很熟悉,就先放上以太币转账的例子

package test;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import contract.MttContract;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;


/**
 * 通过输入私钥的方式,取得钱包权限转账
 * 参考: https://www.cnblogs.com/hongpxiaozhu/p/8574986.html
 * @author 12198
 *
 */
public class Test {
	
	
    public static void main(String[] args) throws Exception {
        String sendTest = sendTest(StaticValue.myRopstenService, StaticValue.account2, StaticValue.account1, StaticValue.account2Pri, "1");
        System.out.println(sendTest);
        
//        String sendERC20 = sendERC20(StaticValue.myRopstenService, StaticValue.account2, StaticValue.account1, StaticValue.MttContractAddress, StaticValue.account2Pri, "100000");
//        System.out.println(sendERC20);
    }
    
   
    
    
    public static String sendTest(String netUrl,String ownAddress,String toAddress,String fromPri,String bigDecimalValue) throws InterruptedException, ExecutionException, IOException{
    	//设置需要的矿工费
        BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L);
        BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);

        //调用的是kovan测试环境,这里使用的是infura这个客户端   https://kovan.infura.io/
        Web3j web3j = getWeb3j(netUrl);
        
        //获得余额
        String ethBanlance = TestGetBalance.getEthBanlance(web3j, ownAddress);
        String checkMoney = checkMoney(bigDecimalValue, ethBanlance);
        if(!checkMoney.contentEquals("")){
        	return checkMoney;
        }
        
//        Web3j web3j = Web3j.build(new HttpService(StaticValue.chongtiService)); //test
//        Web3j web3j = Web3j.build(new HttpService(chongtiService)); //test
        //转账人账户地址
//        String ownAddress = StaticValue.account1;
        //被转人账户地址
//        String toAddress = StaticValue.account2;
//        String toAddress = StaticValue.testk1234;
//        String toAddress = testk1234;
        //转账人私钥
        Credentials credentials = Credentials.create(fromPri);
       
        BigInteger nonce = getNonce(web3j, ownAddress);

        //创建交易,这里是转0.5个以太币
        BigInteger value = Convert.toWei(bigDecimalValue, Convert.Unit.ETHER).toBigInteger();
        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
                nonce, GAS_PRICE, GAS_LIMIT, toAddress, value);

        //签名Transaction,这里要对交易做签名
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signedMessage);

        //发送交易
        EthSendTransaction ethSendTransaction =
                web3j.ethSendRawTransaction(hexValue).send();
        String transactionHash = ethSendTransaction.getTransactionHash();

       
        //获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了
        printTransaction(rawTransaction);
        System.out.println("交易id:"+transactionHash);
        
        close(web3j);
        if(transactionHash != null){
        	return "peding";//交易进行中
        }else{
        	return "fail";//交易失败
        }
		
    }
    
  
   
    
    
    
    
    
    /**
	 * 连接网络
	 * @param netUrl
	 * @return
	 */
	public static Web3j getWeb3j(String netUrl){
		Admin web3j = Admin.build(new HttpService(netUrl));
		return web3j;
	}
	
	/**
	 * 关闭网络
	 * @param web3j
	 */
	public static void close(Web3j web3j){
		web3j.shutdown();
	}
	
	/**
	 * 获得交易笔数
	 * @param web3j
	 * @param ownAddress
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws IOException 
	 */
	public static BigInteger getNonce(Web3j web3j,String ownAddress) throws InterruptedException, ExecutionException, IOException{
		 //getNonce(这里的Nonce我也不是很明白,大概是交易的笔数吧)
		 EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
	                ownAddress, DefaultBlockParameterName.LATEST).send();
	        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
	        return nonce;
	}
	
	/**
	 * 钱包地址余额是否足够转账校验
	 * @param bigDecimalValue
	 * @param addressBalance
	 * @return
	 */
	public static String checkMoney(String bigDecimalValue,String addressBalance){
		if(new BigDecimal(addressBalance).subtract(new BigDecimal(bigDecimalValue)).compareTo(new BigDecimal("0")) <= 0){
        	return  "转账金额大于钱包地址余额";
        }else{
        	return "";
        }
		
	}
	
	 /**
     * 打印事务对象的一些信息
     * @param rawTransaction
     */
    private static void printTransaction(RawTransaction rawTransaction){
    	System.out.println("交易时间"+rawTransaction.getData());
    	System.out.println("转入地址:"+rawTransaction.getTo());
    	System.out.println("gaslimit:"+rawTransaction.getGasLimit());
    	System.out.println("gasPrice:"+rawTransaction.getGasPrice());
    	System.out.println("nonce:"+rawTransaction.getNonce());
    	System.out.println("value:"+rawTransaction.getValue());
    }
	
}

参考: https://www.cnblogs.com/hongpxiaozhu/p/8574986.html

你可能感兴趣的:(web3j,以太坊)