Json-Rpc

使用 Web3 拉取區塊#、雜湊和時間戳

  • April 5, 2020

誰能給我關於使用 web3 使用 Web3 提取最新塊號、雜湊和時間戳的建議?我無法讓它發揮作用,而且從我所看到的來看,文件相當薄弱。一旦我提取了這些值,我就會將它們載入到我網頁中的 p 元素中,這就是我有 getElementByID 語句的原因。下面的腳本和 HTML 程式碼

//connect web3 and check if web3 is connected correctly
   if (typeof web3 !== 'undefined') {
       web3 = new Web3(web3.currentProvider);
   } else {
       // set the provider you want from Web3.providers
       web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
   }
   if(web3.isConnected()) {
   console.log("connected"); 
   } else {
   console.log("not connected")
   }

//pulls state information from the blockchain
   web3.eth.filter('latest').changed(function(){
     var blockNumber = web3.eth.number;
     document.getElementById('latestBlock').innerText = blockNumber;
     var hash = web3.eth.getBlockNumber();
     document.getElementById('latestBlockHash').innerText = hash;
     var timeStamp = web3.eth.block(blockNumber).timestamp;
     document.getElementById('latestBlockTimestamp').innerText = Date(timeStamp);
   });





<div class="container">
     <h2>Blockchain Monitor</h2>
     <div class="panel panel-default">
       <div class="panel-heading">Ethereum Network</div>
       <div class="panel-body"> 
           <h5>Coinbase Address: <strong id="coinbase"></strong></h5>
           <h5>Latest Block Number: <strong id="latestBlock"></strong></h5>
           <h5>Latest Block Timestamp: <strong id="latestBlockTimestamp"></strong></h5>
           <h5>Latest Block Hash: <strong id="latestBlockHash"></strong></h5>
       </div>
     </div>
   </div>

塊號通過以下方式檢索:

var blockNumber = web3.eth.blockNumber;

塊雜湊通過以下方式檢索:

var blockHash = web3.eth.getBlock(blockNumber).hash;

時間戳為:

var timestamp = web3.eth.getBlock(blockNumber).timestamp;

閱讀此處的文件以獲取更多資訊:https ://github.com/ethereum/wiki/wiki/JavaScript-API

從 web3 1.x 開始,大部分函式都變成了 Promise。為了在非同步函式中達到這些值:

const blockNumber = await web3.eth.getBlockNumber();
const blockHash = await web3.eth.getBlock(await web3.eth.getBlockNumber()))
                   .hash;
const timestamp = await web3.eth.getBlock(await web3.eth.getBlockNumber()))
                   .timestamp

引用自:https://ethereum.stackexchange.com/questions/28192