You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Cosmos API无结果时,如何获取指定地址的61笔交易数据?

问题分析与解决方案

核心问题

你的代码硬编码了tx.height=200000的过滤条件,导致仅查询高度为200000的交易,而目标地址的61笔交易均不在该高度,因此返回结果为0。此外还需注意API事件参数的格式规范与分页处理逻辑。

调整步骤

1. 移除不必要的高度过滤

删除URL中&events=tx.height=200000的限制,确保查询该地址作为message.sender的所有交易。

2. 修正事件参数格式

Cosmos REST API要求事件值使用双引号,需对引号进行转义处理,避免参数解析错误。

3. 实现分页查询

Cosmos交易API默认分页返回结果(通常每页最多100条),需循环获取所有分页数据,直到无下一页结果。

修改后的完整代码

import aiohttp
import asyncio

async def fetch_transactions_for_address(node_url, address):
    async with aiohttp.ClientSession() as session:
        transaction_count = 0
        next_key = None
        
        while True:
            # 构建请求参数,处理分页逻辑
            params = {
                "events": f"message.sender=\"{address}\"",
                "pagination.limit": "100"  # 每页最大条数,可根据节点配置调整
            }
            if next_key:
                params["pagination.key"] = next_key
            
            async with session.get(f"{node_url}/cosmos/tx/v1beta1/txs", params=params) as response:
                print(f"Response Status: {response.status}")
                if response.status == 200:
                    data = await response.json()
                    transaction_count += len(data.get('tx_responses', []))
                    # 检查是否存在下一页
                    next_key = data.get('pagination', {}).get('next_key')
                    if not next_key:
                        break
                else:
                    response_text = await response.text()
                    print(f"Failed to fetch data: {response_text}")
                    raise Exception(f"Failed to fetch data: {response.status}")
        
        return transaction_count

async def main():
    node_url = "https://cosmos-rest.publicnode.com"
    address = "cosmos1hcaq68m5krxuppd8xnqnrm4uf2gudkmhns5d6n"
    try:
        transaction_count = await fetch_transactions_for_address(node_url, address)
        print(f"Number of transactions for the address: {transaction_count}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(main())

额外说明

  • 若需要获取该地址作为接收方的交易(Mintscan显示的交易通常包含发送和接收两种场景),可修改events参数为message.sender=\"{address}\" OR message.recipient=\"{address}\"。
  • 部分公共节点存在请求频率限制,若遇到429错误,可在循环中添加await asyncio.sleep(1)的延迟逻辑。

内容的提问来源于stack exchange,提问作者ScraperBegginer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 06:00:11