最近在嘗試使用web3j-android 的庫進行離線簽名一個交易并發送,結果發現發送并交易成功了,但是最后在Android端上會拋出例外
拋出例外段代碼如下:
public EthSendTransaction signAndSend(RawTransaction rawTransaction)
throws IOException {
String hexValue = sign(rawTransaction);
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();
if (ethSendTransaction != null && !ethSendTransaction.hasError()) {
String txHashLocal = Hash.sha3(hexValue);
String txHashRemote = ethSendTransaction.getTransactionHash();
if (!txHashVerifier.verify(txHashLocal, txHashRemote)) {
throw new TxHashMismatchException(txHashLocal, txHashRemote);
}
}
return ethSendTransaction;
}
本人撰寫的方法如下:
String account1PrivateKey = "f4a21456d314d1fafd9aa2dbf18e5df4a846c91570952b8c0058433508ee1256";
Credentials credentials = Credentials.create(account1PrivateKey);
Web3j web3j = EthService.initWeb3j();
RawTransactionManager transactionManager = new RawTransactionManager(web3j, credentials);
new Thread(new Runnable() {
@Override
public void run() {
try {
EthSendTransaction ethSendTransaction = transactionManager.sendTransaction(BigInteger.valueOf(1000L), BigInteger.valueOf(30000L), acount2, "", BigInteger.valueOf(1000L));
String transactionHash = ethSendTransaction.getTransactionHash();
System.out.println("transactionHash:" + transactionHash);
}catch (Exception e) {
e.printStackTrace();
}
}
}).start();
uj5u.com熱心網友回復:
問題解決方案:1、自己離線封裝,不呼叫合約物件
/**
* 離線簽名eth
*
* @param contractAddress//合約地址
* @param to//轉賬的錢包地址
* @param nonce//獲取到的交易次數
* @param gasPrice
* @param gasLimit
* @param value //轉賬的值
* @return
*/
public static String signedEthContractTransactionData(String privateKey, String contractAddress, String to, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, Double value, Double decimal) throws Exception {
//因為每個代幣可以規定自己的小數位, 所以實際的轉賬值=數值 * 10^小數位
BigDecimal realValue = BigDecimal.valueOf(value * Math.pow(10.0, decimal));
//0xa9059cbb代表某個代幣的轉賬方法hex(transfer) + 對方的轉賬地址hex + 轉賬的值的hex
String data = "0xa9059cbb" + Numeric.toHexStringNoPrefixZeroPadded(Numeric.toBigInt(to), 64) + Numeric.toHexStringNoPrefixZeroPadded(realValue.toBigInteger(), 64);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress, data);
//手續費= (gasPrice * gasLimit ) / 10^18 ether
Credentials credentials = Credentials.create(privateKey);
//使用TransactionEncoder對RawTransaction進行簽名操作
byte signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
//轉換成0x開頭的字串
return Numeric.toHexString(signedMessage);
}
2、 修改測驗環境,換成https://www.npmjs.com/package/ganache-cli
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/31768.html
標籤:區塊鏈技術
上一篇:關于HTML5視頻加密的新觀點
下一篇:什么是區塊鏈和位元幣?
