如何通过以太坊获取最近的交易?

问题描述 投票:0回答:3

如何从 EVM 加载最近 10 或 20 笔交易?

我发现通过下面的代码,我可以监听“待处理”的交易。但我想加载所有 20 个最新交易,无论它们处于哪种状态。

var url = "...some-node-or-alchemy-"
var provider = new ethers.providers.JsonRpcProvider(url);
  
provider.on("pending", (tx) => {
    console.log(tx);
});

如何做到这一点? 文档并没有多大帮助。它仅显示我可以从特定哈希加载交易的函数。但我不知道哈希值,需要先获取最新的哈希值。

ethereum blockchain web3js ethers.js
3个回答
0
投票

您可以使用 ethers EtherscanProvider api。

JsonRpcProvider
将您连接到以太坊区块链中的节点,
EtherscanProvider
将您连接到
etherscan
api

let etherscanProvider = new ethers.providers.EtherscanProvider();

// Getting the current Ethereum price
etherscanProvider.getEtherPrice().then(function(price) {
    console.log("Ether price in USD: " + price);
});


// Getting the transaction history of an address
let address = '0xb2682160c482eB985EC9F3e364eEc0a904C44C23';
let startBlock = 3135808;
let endBlock = 5091477;
etherscanProvider.getHistory(address, startBlock, endBlock).then(function(history) {
    console.log(history);

或者您可以注册 etherscan api,这里是 https://api.etherscan.io/apis

但无论如何,我认为你不能指定交易数量。该实现依赖于 RPC 服务器。如果它们没有构建,您可以在前端处理这个问题并仅将指定数量的交易返回给用户


0
投票

待处理和已确认交易是两种非常不同的交易类型,一种是易失性的,另一种是已确认为区块链的一部分的。

连接到节点并使用 Ethers 传输

pending
事件是获取最新待处理交易的好方法。

对于已确认的交易,您可以对

block
事件使用类似的流来获取最新的区块编号,然后使用 eth_getBlockByNumber 调用检查区块中包含的交易。


0
投票
// Note this is V6 of ethers
const provider = new ethers.JsonRpcProvider(`https://mainnet.infura.io/v3/${process.env.YOUR_INFURA_API_KEY}`);
const eth_getBlockByNumber = async () => {
  const blockByNumber = await provider.send("eth_getBlockByNumber", ["pending", false]);
  const transactions = blockByNumber.transactions;
  const first50Transactions = transactions.slice(0, 50);
  console.log("First 50 transactions:", first50Transactions);
};

eth_getBlockByNumber();
© www.soinside.com 2019 - 2024. All rights reserved.