W3Schools



在geth你可以任何加载.js file.

我在维基上发现了这个我很喜欢的一个:

function checkAllBalances() { 
  var i =0; 
  eth.accounts.forEach( function(e){
    console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " + web3.fromWei(eth.getBalance(e), "ether") + " ether"); 
    i++; 
  })
};

你经常使用其他的吗? 一种“经典”或“必备”的存储库将是一个很好的资源。

go-ethereumjavascript
11个回答
26

1.只有在有交易时才开采!

var mining_threads = 1

function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        if (eth.mining) return;
        console.log("== Pending transactions! Mining...");
        miner.start(mining_threads);
    } else {
        miner.stop(0);  // This param means nothing
        console.log("== No transactions! Mining stopped.");
    }
}

eth.filter("latest", function(err, block) { checkWork(); });
eth.filter("pending", function(err, block) { checkWork(); });

checkWork();

2.从geth获取一些数据而不启动节点。

$ geth --exec "eth.accounts" console 2>/dev/null

["0x0000000000000000000000000000000000000000"]

3.查看交易

function printTransaction(txHash) {
  var tx = eth.getTransaction(txHash);
  if (tx != null) {
    console.log("  tx hash          : " + tx.hash + "\n"
      + "   nonce           : " + tx.nonce + "\n"
      + "   blockHash       : " + tx.blockHash + "\n"
      + "   blockNumber     : " + tx.blockNumber + "\n"
      + "   transactionIndex: " + tx.transactionIndex + "\n"
      + "   from            : " + tx.from + "\n" 
      + "   to              : " + tx.to + "\n"
      + "   value           : " + tx.value + "\n"
      + "   gasPrice        : " + tx.gasPrice + "\n"
      + "   gas             : " + tx.gas + "\n"
      + "   input           : " + tx.input);
  }
}

4.打印块的详细信息

function printBlock(block) {
  console.log("Block number     : " + block.number + "\n"
    + " hash            : " + block.hash + "\n"
    + " parentHash      : " + block.parentHash + "\n"
    + " nonce           : " + block.nonce + "\n"
    + " sha3Uncles      : " + block.sha3Uncles + "\n"
    + " logsBloom       : " + block.logsBloom + "\n"
    + " transactionsRoot: " + block.transactionsRoot + "\n"
    + " stateRoot       : " + block.stateRoot + "\n"
    + " miner           : " + block.miner + "\n"
    + " difficulty      : " + block.difficulty + "\n"
    + " totalDifficulty : " + block.totalDifficulty + "\n"
    + " extraData       : " + block.extraData + "\n"
    + " size            : " + block.size + "\n"
    + " gasLimit        : " + block.gasLimit + "\n"
    + " gasUsed         : " + block.gasUsed + "\n"
    + " timestamp       : " + block.timestamp + "\n"
    + " transactions    : " + block.transactions + "\n"
    + " uncles          : " + block.uncles);
    if (block.transactions != null) {
      console.log("--- transactions ---");
      block.transactions.forEach( function(e) {
        printTransaction(e);
      })
    }
}

5.检查所有余额

function checkAllBalances() { 
 var i =0; 
 eth.accounts.forEach( function(e){
    console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " +    web3.fromWei(eth.getBalance(e), "ether") + " ether"); 
  i++; 
 })
};

来源

  1. HTTPS://GitHub.com/ether EU M/go-ether EU M/wiki/bitch in-tricks
  2. HTTPS://ether EU M.stack Exchange.com/啊/2928/259

11

用于查找已挖掘的块和叔叔+列表事务的脚本

这是我检查和打印块,叔叔和事务的脚本。这最初是作为问题的答案而写的我如何知道提交的块是否成为叔叔? .

我已单独列出它们以便于阅读。如果你打算用它geth, you would probably want to concatenate the following 5 functions into a single file for easy copy-pasting into the geth console. And just remove the field you don't need to see.

打印交易(txHash)

function printTransaction(txHash) {
  var tx = eth.getTransaction(txHash);
  if (tx != null) {
    console.log("  tx hash          : " + tx.hash + "\n"
      + "   nonce           : " + tx.nonce + "\n"
      + "   blockHash       : " + tx.blockHash + "\n"
      + "   blockNumber     : " + tx.blockNumber + "\n"
      + "   transactionIndex: " + tx.transactionIndex + "\n"
      + "   from            : " + tx.from + "\n" 
      + "   to              : " + tx.to + "\n"
      + "   value           : " + tx.value + "\n"
      + "   gasPrice        : " + tx.gasPrice + "\n"
      + "   gas             : " + tx.gas + "\n"
      + "   input           : " + tx.input);
  }
}

打印块(block)

function printBlock(block) {
  console.log("Block number     : " + block.number + "\n"
    + " hash            : " + block.hash + "\n"
    + " parentHash      : " + block.parentHash + "\n"
    + " nonce           : " + block.nonce + "\n"
    + " sha3Uncles      : " + block.sha3Uncles + "\n"
    + " logsBloom       : " + block.logsBloom + "\n"
    + " transactionsRoot: " + block.transactionsRoot + "\n"
    + " stateRoot       : " + block.stateRoot + "\n"
    + " miner           : " + block.miner + "\n"
    + " difficulty      : " + block.difficulty + "\n"
    + " totalDifficulty : " + block.totalDifficulty + "\n"
    + " extraData       : " + block.extraData + "\n"
    + " size            : " + block.size + "\n"
    + " gasLimit        : " + block.gasLimit + "\n"
    + " gasUsed         : " + block.gasUsed + "\n"
    + " timestamp       : " + block.timestamp + "\n"
    + " transactions    : " + block.transactions + "\n"
    + " uncles          : " + block.uncles);
    if (block.transactions != null) {
      console.log("--- transactions ---");
      block.transactions.forEach( function(e) {
        printTransaction(e);
      })
    }
}

printUncle(block,uncleNumber,uncle)

function printUncle(block, uncleNumber, uncle) {
  console.log("Block number     : " + block.number + " , uncle position: " + uncleNumber + "\n"
    + " Uncle number    : " + uncle.number + "\n"
    + " hash            : " + uncle.hash + "\n"
    + " parentHash      : " + uncle.parentHash + "\n"
    + " nonce           : " + uncle.nonce + "\n"
    + " sha3Uncles      : " + uncle.sha3Uncles + "\n"
    + " logsBloom       : " + uncle.logsBloom + "\n"
    + " transactionsRoot: " + uncle.transactionsRoot + "\n"
    + " stateRoot       : " + uncle.stateRoot + "\n"
    + " miner           : " + uncle.miner + "\n"
    + " difficulty      : " + uncle.difficulty + "\n"
    + " totalDifficulty : " + uncle.totalDifficulty + "\n"
    + " extraData       : " + uncle.extraData + "\n"
    + " size            : " + uncle.size + "\n"
    + " gasLimit        : " + uncle.gasLimit + "\n"
    + " gasUsed         : " + uncle.gasUsed + "\n"
    + " timestamp       : " + uncle.timestamp + "\n"
    + " transactions    : " + uncle.transactions + "\n");
}

getMinedBlocks(miner,startBlockNumber,endBlockNumber)

如果startBlockNumber is not specified, it will default to the last 10,000 blocks. This takes some time to scan, so reduce this number to 1000 to reduce the scanning time.

如果endBlockNumber is not specified, it will default to the latest block number.

function getMinedBlocks(miner, startBlockNumber, endBlockNumber) {
  if (endBlockNumber == null) {
    endBlockNumber = eth.blockNumber;
    console.log("Using endBlockNumber: " + endBlockNumber);
  }
  if (startBlockNumber == null) {
    startBlockNumber = endBlockNumber - 10000;
    console.log("Using startBlockNumber: " + startBlockNumber);
  }
  console.log("Searching for miner \"" + miner + "\" within blocks "  + startBlockNumber + " and " + endBlockNumber + "\"");

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    if (i % 1000 == 0) {
      console.log("Searching block " + i);
    }
    var block = eth.getBlock(i);
    if (block != null) {
      if (block.miner == miner || miner == "*") {
        console.log("Found block " + block.number);
        printBlock(block);
      }
      if (block.uncles != null) {
        for (var j = 0; j < 2; j++) {
          var uncle = eth.getUncle(i, j);
          if (uncle != null) {
            if (uncle.miner == miner || miner == "*") {
              console.log("Found uncle " + block.number + " uncle " + j);
              printUncle(block, j, uncle);
            }
          }          
        }
      }
    }
  }
}

getMyMinedBlocks(startBlockNumber,endBlockNumber)

function getMyMinedBlocks(startBlockNumber, endBlockNumber) {
  getMinedBlocks(eth.accounts[0], startBlockNumber, endBlockNumber);
}

使用上述功能的示例

以下是在公共主网Ethereum网络上使用上述功能的一些示例。

  • 打印块由“0x52bc44d5378309ee2abf1539bf71de1b7d7be3b5”开采。看到HTTPS://ether scan.IO/block/1325630

    getMinedBlocks("0x52bc44d5378309ee2abf1539bf71de1b7d7be3b5", 1325620, 1325640);
    
  • 使用“0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb”挖掘的叔叔打印块。看到HTTPS://ether scan.IO/block/1325635

    getMinedBlocks("0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb", 1325630, 1325640);
    

    与输出:

    > getMinedBlocks("0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb", 1325630, 1325640);
    Searching for miner "0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb" within blocks 1325630 and 1325640"
    Found uncle 1325635 uncle 0
    Block number     : 1325635 , uncle position: 0
     Uncle number    : 1325634
     hash            : 0xae03bb2d5f1fbde4e22bf79850307ab6ae7d8545a9f0de4a5f529095546308c0
     parentHash      : 0x771b46e0310666780a55b1d603648d89e7d8cc3feac20a175117b4cb7e206a75
     nonce           : 0xeff5922de2f569e8
     sha3Uncles      : 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347
     logsBloom       : 0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
     transactionsRoot: 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421
     stateRoot       : 0xafca80bc836c00c7eeb4b6f3254573f72d38a0738ce4793da7d5222ed6c0c5cd
     miner           : 0xf3b9d2c81f2b24b0fa0acaaa865b7d9ced5fc2fb
     difficulty      : 26564802678158
     totalDifficulty : 0
     extraData       : 0x426974436c756220455448204d696e696e6720506f6f6c
     size            : 0
     gasLimit        : 4712388
     gasUsed         : 0
     timestamp       : 1460501836
     transactions    : undefined
    
  • 打印块与叔叔。看到HTTPS://ether scan.IO/block/907703

    getMinedBlocks("*", 907703, 907703);
    
  • 我的矿工在块1321603和1321605之间开采的打印块

    getMyMinedBlocks(1321603, 1321605);
    

12

脚本在一系列块中查找非零事务计数

(2016年4月22日更新)

这是一个脚本,用于检查起始块号和结束块号之间的事务数:

function checkTransactionCount(startBlockNumber, endBlockNumber) {
  console.log("Searching for non-zero transaction counts between blocks "  + startBlockNumber + " and " + endBlockNumber);

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    var block = eth.getBlock(i);
    if (block != null) {
      if (block.transactions != null && block.transactions.length != 0) {
        console.log("Block #" + i + " has " + block.transactions.length + " transactions")
      }
    }
  }
}

运行块1到46146的脚本显示以下结果 - 没有事务!:

> checkTransactionCount(1, 46146)
Searching for non-zero transaction counts between blocks 1 and 46146
undefined

让我们检查脚本是否按预期工作:

> eth.blockNumber
1382234
> checkTransactionCount(1382224, 1382234)
Searching for non-zero transaction counts between blocks 1382224 and 1382234
Block #1382224 has 4 transactions
Block #1382225 has 2 transactions
Block #1382226 has 4 transactions
Block #1382227 has 6 transactions
Block #1382228 has 17 transactions
Block #1382231 has 2 transactions
Block #1382234 has 1 transactions
undefined

46147到46200中包含一些交易:

> checkTransactionCount(46147, 46200)
Searching for non-zero transaction counts between blocks 46147 and 46200
Block #46147 has 1 transactions
Block #46169 has 1 transactions
Block #46170 has 1 transactions
Block #46194 has 1 transactions
undefined

45

脚本查找到/从帐户的交易

用法

查找到/从的所有交易eth.accounts[0] within the last 1,000 blocks:

> getTransactionsByAccount(eth.accounts[0])

查找到/从的所有交易the DAO's account 0xbb9bc244d798123fde783fcc1c72d3bb8c189413 between blocks 1,432,400 and 1,432,423:

> getTransactionsByAccount("0xbb9bc244d798123fde783fcc1c72d3bb8c189413", 1432400, 1432423)

查找最近1000个街区中任何帐户的所有交易:

> getTransactionsByAccount("*")


剧本

function getTransactionsByAccount(myaccount, startBlockNumber, endBlockNumber) {
  if (endBlockNumber == null) {
    endBlockNumber = eth.blockNumber;
    console.log("Using endBlockNumber: " + endBlockNumber);
  }
  if (startBlockNumber == null) {
    startBlockNumber = endBlockNumber - 1000;
    console.log("Using startBlockNumber: " + startBlockNumber);
  }
  console.log("Searching for transactions to/from account \"" + myaccount + "\" within blocks "  + startBlockNumber + " and " + endBlockNumber);

  for (var i = startBlockNumber; i <= endBlockNumber; i++) {
    if (i % 1000 == 0) {
      console.log("Searching block " + i);
    }
    var block = eth.getBlock(i, true);
    if (block != null && block.transactions != null) {
      block.transactions.forEach( function(e) {
        if (myaccount == "*" || myaccount == e.from || myaccount == e.to) {
          console.log("  tx hash          : " + e.hash + "\n"
            + "   nonce           : " + e.nonce + "\n"
            + "   blockHash       : " + e.blockHash + "\n"
            + "   blockNumber     : " + e.blockNumber + "\n"
            + "   transactionIndex: " + e.transactionIndex + "\n"
            + "   from            : " + e.from + "\n" 
            + "   to              : " + e.to + "\n"
            + "   value           : " + e.value + "\n"
            + "   time            : " + block.timestamp + " " + new Date(block.timestamp * 1000).toGMTString() + "\n"
            + "   gasPrice        : " + e.gasPrice + "\n"
            + "   gas             : " + e.gas + "\n"
            + "   input           : " + e.input);
        }
      })
    }
  }
}


查找到/来自的交易eth.accounts[0] address:

> getTransactionsByAccount(eth.accounts[0])
Using endBlockNumber: 1864
Using startBlockNumber: 864
Searching for transactions to/from account "0xa7857047907d53a2e494d5f311b4b586dc6a96d2" within blocks 864 and 1864
Searching block 1000
  tx hash          : 0x3c3bc3c456a84e20cf0077f9aa5ce363d3b12bca18d01000a750288c2e76401e
   nonce           : 44
   blockHash       : 0xef2d15775908951fc61f9a83b53c00cf2cde4e0def93e20544f784441c6178db
   blockNumber     : 1582
   transactionIndex: 0
   from            : 0xa7857047907d53a2e494d5f311b4b586dc6a96d2
   to              : null
   value           : 0
   time            : 1470459255 Sat, 06 Aug 2016 04:54:15 GMT
   gasPrice        : 20000000000
   gas             : 24615
   input           : 0x6060604052600a8060106000396000f360606040526008565b00
  tx hash          : 0xc255cdbf477452eb8922d8230889f7cc08b9deed4695378aba3d97906071ce5f
   nonce           : 45
   blockHash       : 0x987a8214af96bb1530b97fe09da8f8168679e42c9efb4defee50800f2067d6d8
   blockNumber     : 1587
   transactionIndex: 0
   from            : 0xa7857047907d53a2e494d5f311b4b586dc6a96d2
   to              : null
   value           : 0
   time            : 1470459409 Sat, 06 Aug 2016 04:56:49 GMT
   gasPrice        : 20000000000
   gas             : 24615
   input           : 0x6060604052600a8060106000396000f360606040526008565b00
...

5

脚本获取帐户余额并包括DAO标记

这是一个版本checkAllBalances that also displays the DAO tokens. There is a Linux script that you can execute from the command line at 如何从geth打印我的帐户余额和TheDAO代币.

function padTokens(s, n) {
  var o = s.toPrecision(n);
  while (o.length < n) {
    o = " " + o;
  }
  return o;
}

function padEthers(s) {
  var o = s.toFixed(18);
  while (o.length < 27) {
    o = " " + o;
  }
  return o;
}

function checkAllBalances() { 
  var theDAOABI = [ { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "5e+22" } ], "name": "minTokensToCreate", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "2.668900014413644230605979e+24" } ], "name": "totalSupply", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "", "value": "1464426000" } ], "name": "closingTime", "inputs": [], "constant": true }, { "type": "function", "outputs": [], "name": "refund", "inputs": [], "constant": false }, { "type": "function", "outputs": [ { "type": "address", "name": "", "value": "0xda4a4626d3e16e094de3225a751aab7128e96526" } ], "name": "curator", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "balance", "value": "0" } ], "name": "balanceOf", "inputs": [ { "type": "address", "name": "_owner" } ], "constant": true }, { "type": "function", "outputs": [ { "type": "uint256", "name": "_numberOfProposals", "value": "0" } ], "name": "numberOfProposals", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "address", "name": "", "value": "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" } ], "name": "extraBalance", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "bool", "name": "", "value": true } ], "name": "isFueled", "inputs": [], "constant": true }, { "type": "function", "outputs": [ { "type": "bool", "name": "success" } ], "name": "createTokenProxy", "inputs": [ { "type": "address", "name": "_tokenHolder" } ], "constant": false }, { "type": "function", "outputs": [ { "type": "uint256", "name": "_voteID" } ], "name": "vote", "inputs": [ { "type": "uint256", "name": "_proposalID" }, { "type": "bool", "name": "_supportsProposal" } ], "constant": false }, { "type": "event", "name": "FuelingToDate", "inputs": [ { "type": "uint256", "name": "value", "indexed": false } ], "anonymous": false }, { "type": "event", "name": "ProposalAdded", "inputs": [ { "type": "uint256", "name": "proposalID", "indexed": true }, { "type": "address", "name": "recipient", "indexed": false }, { "type": "uint256", "name": "amount", "indexed": false }, { "type": "bool", "name": "newCurator", "indexed": false }, { "type": "string", "name": "description", "indexed": false } ], "anonymous": false }, { "type": "event", "name": "ProposalTallied", "inputs": [ { "type": "uint256", "name": "proposalID", "indexed": true }, { "type": "bool", "name": "result", "indexed": false }, { "type": "uint256", "name": "quorum", "indexed": false } ], "anonymous": false } ];
  var theDAOAddress = "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413";
  var theDAO = eth.contract(theDAOABI).at(theDAOAddress);
  var theDAOTotal = 0; 
  var ethersTotal = 0; 

  console.log("  #     Account                                        TheDAO                      ethers");
  console.log("------- ------------------------------------------ ---------- ---------------------------");
  var i =0; 
  eth.accounts.forEach( function(e){
    var tokens = theDAO.balanceOf(e) / parseFloat(1e16);
    theDAOTotal += parseFloat(tokens);
    var ethers = web3.fromWei(eth.getBalance(e), "ether");
    ethersTotal += parseFloat(ethers);
    console.log("  " + i + "\t" + e + " " + padTokens(tokens, 10) + " " + padEthers(ethers)); 
    i++; 
  })
  console.log("------- ------------------------------------------ ---------- ---------------------------");
  console.log("  " + i + "                                               " + padTokens(theDAOTotal, 10) + " " + padEthers(ethersTotal));
}; 

这是一些示例输出:

> checkAllBalances()
  #     Account                                        TheDAO                      ethers
------- ------------------------------------------ ---------- ---------------------------
  0     0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa       1100        1.111111111111111111
  1     0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb       2200        2.222222222222222222
  2     0xcccccccccccccccccccccccccccccccccccccccc       3300        3.333333333333333333
------- ------------------------------------------ ---------- ---------------------------
  3                                                      6600        6.666666666666666666

5

在区块链中找到令牌,礼貌HTTPS://GitHub.com/里那个恶/find-ether EU M-coins/blob/master/token.就是

var tokenInterface = [{"type": "function","name": "name","constant": true,"inputs": [],"outputs": [{"name": "","type": "string"}]},{"type": "function","name": "decimals","constant": true,"inputs": [],"outputs": [{"name": "","type": "uint8"}]},{"type": "function","name": "balanceOf","constant": true,"inputs": [{"name": "","type": "address"}],"outputs": [{"name": "","type": "uint256"}]},{"type": "function","name": "symbol","constant": true,"inputs": [],"outputs": [{"name": "","type": "string"}]},{"type": "function","name": "transfer","constant": false,"inputs": [{"name": "_to","type": "address"},{"name": "_value","type": "uint256"}],"outputs": []},{"type": "constructor","inputs": [{"name": "_supply","type": "uint256"},{"name": "_name","type": "string"},{"name": "_decimals","type": "uint8"},{"name": "_symbol","type": "string"}]},{"name": "Transfer","type": "event","anonymous": false,"inputs": [{"indexed": true,"name": "from","type": "address"},{"indexed": true,"name": "to","type": "address"},{"indexed": false,"name": "value","type": "uint256"}]}];
TokenContract = web3.eth.contract(tokenInterface);

var lowestBlock = 474147; //November 3, 2015 - last time the ABI above was changed
var highestBlock = eth.getBlock("latest").number;
//var lowestBlock = 483325; //smaller test case with just one coin (MistCoin)
//var highestBlock = 484731; //smaller test case with just one coin (MistCoin)
for (var x=lowestBlock; x < highestBlock; x++) {
  var transactions = eth.getBlock(x).transactions;
  for (var y=0; y < transactions.length; y++) {
//    if (x % 100 == 0) { console.log("."); }
    var contractAddr = eth.getTransactionReceipt(transactions[y]).contractAddress;
    if (contractAddr != null) {
       var tokenInstance = TokenContract.at(contractAddr);
       var symbol = "";
       var decimals = "";
       var name = "";
       try {
         symbol = tokenInstance.symbol();
       } catch(err) {
       }
       try {
         decimals = tokenInstance.decimals();
       } catch(err) {
         //don't do anything here, just catch the error so program doesn't die
       }
       try {
         name = tokenInstance.name();
       } catch(err) {
         //don't do anything here, just catch the error so program doesn't die
       }
       if (symbol != null && symbol != "" && name != null && name != "") {
         console.log("-----------");
         console.log("Contract Address: " + contractAddr);
         console.log("Name: " + name);
         console.log("Symbol: " + symbol);
         console.log("Decimals: " + decimals);
         console.log("-----------");
       }
//       console.log(contractAddr);  //testing
    }
  }
//  console.log(eth.getBlock(x).transactions);  //testing
}

10

快速扫描帐户上的事务块的方法

查看Node.JS源代码 or its 样本输出.

这是一个异步扫描程序,它创建200个线程来扫描,查找与您的帐号相关的任何/所有交易。

您可以轻松更改发现事务时发生的情况,目前只需打印到控制台即可查看。

上面的一些答案显示了扫描查找事务的所有块的同步方法,但同步执行此扫描的速度很慢,尤其是当您通过Internet连接到Geth时。该解决方案在扫描大量块时速度更快。


1

这是一个简单的获得总余额的方法:

function totalBalance() { 
  var x = 0
  eth.accounts.forEach( function(e) {
    x = x + parseFloat(web3.fromWei(eth.getBalance(e)), 10); 
  });
  console.log("  total balance: " + x + " ether"); 
};

9

将整个余额从一个帐户转移到另一个帐户

/**
 * Transfer the ENTIRE BALANCE from one account to another.
 *
 * Before you call this, you must unlock your account:
 *   personal.unlockAccount(from)
 *
 * @see https://github.com/ethereum/go-ethereum/issues/1637
 * @see https://github.com/ethereum/go-ethereum/issues/2173
 */
function transferEntireBalance(from, to) {
    var gas = new BigNumber(21000);
    var price = web3.eth.gasPrice;  // current average price; or set your own
    var balance = eth.getBalance(from);
    var value = balance.minus(gas.times(price));
    if (value.greaterThan(0)) {
        var txn = eth.sendTransaction({from: from, to: to, gasPrice: price, gas: gas, value: value});
        console.log("  Transfer", from, "to", to, ":", txn);
        return txn;
    }
    console.log("  Transfer "+ from +" to "+ to +": (No funds available)");
    return null;
}

HTTPS://gist.GitHub.com/Ross-怕/出发489宝宝7额度7427哦4498058不0的6啊5984

这计算了进行交易所需的天然气量,然后它从中转移了100%的资金(在天然气成本之后)from account to the to account.

运行此方法后,from account will have 0 Ether remaining.

用法:

var txn = transferEntireBalance(from, to);
eth.getTransaction(txn);

更新于19日至7月17日,默认情况下专门使用BigNumber数学和系统范围的平均gasPrice。


0

只是为了好玩。递归获取所有块:)(不是最好的方法)

 function getAllBlocks(blockNumber,res) { 
  if(blockNumber < 0) return; 
  var block = eth.getBlock(blockNumber); 
  res.push(getAllBlocks(block.number-1,res));
  return res; 
 }

getAllBlocks('latest',[])

0

针对特定帐户的启发式搜索货币交易 processing the entire chain

var myAddr = '0xbb9bc244d798123fde783fcc1c72d3bb8c189413';
var currentBlock = eth.blockNumber;
var n = eth.getTransactionCount(myAddr, currentBlock);
var bal = eth.getBalance(myAddr, currentBlock);
for (var i=currentBlock; i >= 0 && (n > 0 || bal > 0); --i) {
    try {
        var block = eth.getBlock(i, true);
        if (block && block.transactions) {
            block.transactions.forEach(function(e) {
                if (myAddr == e.from) {
                    if (e.from != e.to)
                        bal = bal.plus(e.value);
                    console.log(i, e.from, e.to, e.value.toString(10));
                    --n;
                }
                if (myAddr == e.to) {
                    if (e.from != e.to)
                        bal = bal.minus(e.value);
                    console.log(i, e.from, e.to, e.value.toString(10));
                }
            });
        }
    } catch (e) { console.error("Error in block " + i, e); }
}

它是如何工作的?

使用有关当前状态的可用信息(“来自”交易的数量和当前余额),它会及时返回,直到找到至少这么多“来自”的交易,然后继续返回,直到余额达到0.

固有的限制是0值交易之前 the account was funded will not be found.