Go-Ethereum

如何正確使用來自 web3.js 的過濾器

  • May 4, 2017

我想根據過濾器中的transactionhash獲取塊號,但是,當我將以下程式碼添加到我的項目時,我發現它很奇怪,因為有時它會自動轉賬兩次,有時我必須第二次轉賬才能看到它返回事務雜湊。

此外,我無法在過濾器中取回塊號。怎麼了 ?

function TransferTest() {
   alert("START TO TRANSFER")
   var Web3 = require('web3');
   var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
   var abiArray=[
       {"constant":true,"inputs":[],"name":"minter","outputs":
           [{"name":"","type":"address"}],"payable":false,"type":"function"},
       {"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},
       {"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"type":"function"},
       {"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"send","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Sent","type":"event"}
   ];
   var object=web3.eth.getTransactionReceipt("0x327fa3ecb7f9312119201995714c6c94a92accfa1643810b2bd3ee6c4f3a038e");
   var conAddress=object.contractAddress;
   var Mycontract=web3.eth.contract(abiArray);
   var MyConIns=Mycontract.at(conAddress);
   var uAddress=document.getElementById("uAddress").value;
   var tarAddress=document.getElementById("tarAddress").value;
   var AKamount=document.getElementById("AKamount").value;
   var success=web3.personal.unlockAccount(uAddress,"carochan123");
   alert(success);
   MyConIns.send(tarAddress,AKamount,{from:uAddress});var filter=web3.eth.filter("pending");
   filter.watch(function(error, result){
       if (!error)
           alert("monitor");
           alert(result);
       var block = web3.eth.getBlock(result, true);
       alert(block.number);
   });

   alert(MyConIns.balances(tarAddress));//50,150,170,260,270,300,320,330,360,370,380,390,410,420
   alert(MyConIns.balances(uAddress));
}

部分答案:可能是您無法獲得塊號

var block = web3.eth.getBlock(result, true);
alert(block.number);

因為該塊是“待定的”,在這種情況下它number 將會是null(參見web3.eth.getBlock返回值描述)。

首先,為了避免錯過您的事務,最好在執行事務之前啟動您的過濾器監視。

此外,getBlock()您可能希望使其非同步,以確保它具有返回值。

希望這可以幫助。

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