Go-Ethereum
等待在 geth 中探勘交易的最佳方式
我目前正在使用以下函式(使用web3.js )檢查是否已探勘交易:
function waitForTx(tx_hash) { var result = null; // This is not really efficient but nodejs cannot pause the running process while(result === null) { result = web3.eth.getTransactionReceipt(tx_hash); } }
有沒有辦法避免阻塞循環?
Xavier 有一個很好的解決方案,這裡有明確的使用範例:https ://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6 。你會得到一個可交易的收據。這是一個非阻塞的解決方案,所以javascript執行緒在等待promise返回時不會卡住。
使用 Promise 可以很好地解決它,並作為 web3 的擴展來實現。將程式碼逐字包含在***getTransactionReceiptMined.js中。***然後,像他的例子一樣與它互動……下面的突出摘錄。
你發送一個交易並獲得交易雜湊(快速),然後呼叫他的函式來設置一個等待交易被探勘的承諾(區塊時間)。然後,使用您探勘的交易收據執行您的程式碼。
從他的例子中提取(添加評論):
... // do something that sends a transaction return meta.sendCoin(account_two, 6, { from: account_one }); }) .then(function (txnHash) { // now you have the unmined transaction hash, return receipt promise console.log(txnhash); // follow along return web3.eth.getTransactionReceiptMined(txnHash); }) .then(function (receipt) { // now you have the mined transaction receipt as "receipt" console.log(receipt); // explore it :-) // carry on with the next step return meta.getBalance.call(account_two); })
這是等待探勘合約(或任何交易雜湊)的 ECMAScript 2016 版本:
// await sleep trick // http://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // We need to wait until any miner has included the transaction // in a block to get the address of the contract async function waitBlock() { while (true) { let receipt = web3.eth.getTransactionReceipt(contract.transactionHash); if (receipt && receipt.contractAddress) { console.log("Your contract has been deployed at http://testnet.etherscan.io/address/" + receipt.contractAddress); console.log("Note that it might take 30 - 90 sceonds for the block to propagate befor it's visible in etherscan.io"); break; } console.log("Waiting a mined block to include your contract... currently in block " + web3.eth.blockNumber); await sleep(4000); } } waitBlock();