Web3j
如何更改 web3j 中事務之間的隨機數?
我有這行程式碼,它在區塊鏈中註冊交易。我想知道如何使交易之間的隨機數不同?
txhash = careercertificate .createCertificate(id, fecha, nombre, rutalumno, instituto, rutinstituto, titulo, totalhash, fechatitulacion, registronumber, codigoV) .send().getTransactionHash();
在底層,Web3J SmartContract Java Wrapper 通過獲取
getTransactionCount
賬戶的交易數量來計算隨機數 (credential
)。EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send(); BigInteger nonce = ethGetTransactionCount.getTransactionCount();
如果由於某些原因,您想手動設置隨機數(因為我猜您要發送多個並行事務),這不是一件容易的事,您必須複製 web3j 在幕後所做的事情。
一世。一些常數
final String privateKey = "48c2210576121c68883b2f96ae82cdf5fd845d99f4243b9c44651316accaac97"; // Dummy private key !!! final String contractAddress = "0x5e417E6d4e15471912743e1173D5fD3a3617aD9f"; // Smart contract after deployment on Ganache final BigInteger gasLimit = new BigInteger("6721975"); // Block gas limit (Ganache) final BigInteger gasPrice = new BigInteger("20000000000"); // 20 gwei - Gas Price (Ganache)
ii. 連接節點並啟動web3j
// Connect to the node Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
iii. 讀取私鑰
// Read Private Key Credentials credentials = Credentials.create(privateKey)
iv. 計算交易數據
一筆交易由多個資訊組成,例如
from
account、to
account 、value
、gasPrice
、和。在智能觸點的情況下,代表函式的編碼、參數類型和參數。gasLimit``nonce``data``data
你可以
data
這樣計算:// Extract the function from the Smart Contract wrapper generated by web3j cli final Function function = new Function( Counter.FUNC_INCREMENT, Arrays.<Type>asList(), Collections.<TypeReference<?>>emptyList()); // Encode to data String data = FunctionEncoder.encode(function);
v. 選擇一個隨機數
根據您的需要,選擇一個隨機數(/!\ 必須大於此帳戶上最後一次交易的隨機數)
// Calculate nonce (...) BigInteger nonce = new BigInteger("101");
六。準備交易
// Prepare transaction RawTransaction rawTransaction = RawTransaction.createTransaction( nonce, gasPrice, gasLimit, contractAddress, BigInteger.ZERO, // No Value data);
七。發送交易
// Transaction manager RawTransactionManager transactionManager = new RawTransactionManager(web3, credentials); EthSendTransaction transaction = transactionManager.signAndSend(rawTransaction); log.debug("transaction hash = {}", transaction.getTransactionHash());
你可以在這裡找到程式碼: