1. 程式人生 > >web3j 傳送以太幣(ropsten 測試網路)

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/<your-token>
        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());
    }
	
}