拓冰建站拓冰建站
首页 / 资讯中心 / 正文

使用 @corsair-dev/blocknative 在 Corsair 中接入 Blocknative 实时 Gas 价格预测

使用 corsair-dev/blocknative 在 Corsair 中接入 Blocknative 实时 Gas 价格预测【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsair本文介绍如何通过 Corsair 官方插件corsair-dev/blocknative将 Blocknative Gas Platform内存池监控与实时 Gas 预测 API集成进你的多租户 AI 应用只需一次安装与配置即可获得 5 个强类型 API 操作、5 个本地同步的数据库实体、内置的 API Key 凭据管理与自动重试策略。读完本文你将掌握从插件安装、租户连接、端点调用到本地数据查询的完整实战链路。Blocknative 插件概览corsair-dev/blocknative是 Corsair 生态中的官方插件包位于 packages/blocknative它把 Blocknative 的 Gas Platform 能力封装为一组类型安全、经过 Zod 校验、可审计的操作。通过 Corsair 统一的数据层所有请求返回的数据会自动同步到本地数据库供search()/list()快速检索。该插件提供5 个强类型 API 操作gas.getBaseFeeEstimates、gas.getDistribution、gas.getOracles、gas.getPrices、gas.getSupportedChains全部为read风险级别5 个本地同步实体baseFeeEstimates、blockPrices、chains、gasDistributions、oracles支持开箱即用的.search()/.list()API Key 认证Corsair 在租户首次使用时提示填写凭据多租户场景下每个租户的 Key 相互隔离。插件元数据可在 packages/blocknative/plugin-docs.yaml 查看displayName: Blocknativedescription: Mempool monitoring API for real-time Ethereum and blockchain transaction tracking.安装使用 pnpm仓库默认包管理器参见 packages/blocknative/package.json安装插件pnpm add corsair-dev/blocknative插件以corsair与zod为 peerDependencies要求corsair 0.1.0、zod ^4.1.13因此你还需要先安装核心包pnpm add corsair初始化并注册插件在corsair.ts中创建 Corsair 实例并注册blocknative()插件。完整初始化示例如下参考 docs/plugins/blocknative/overview.mdximport Database from better-sqlite3; import { createCorsair } from corsair; import { blocknative } from corsair-dev/blocknative; export const corsair createCorsair({ plugins: [ blocknative(), ], database: new Database(corsair.db), kek: process.env.CORSAIR_KEK!, hub: { projectApiKey: process.env.CORSAIR_API_KEY!, signingSecret: process.env.CORSAIR_SIGNING_SECRET!, }, });要点说明databaseCorsair 使用 better-sqlite3 等本地数据库保存同步数据与凭据kekKey Encryption Key用于加密存储各租户的 API Key取值为环境变量CORSAIR_KEKhub配置projectApiKey与signingSecret用于托管租户连接页面与 Webhook 签名校验multiTenancy多租户是默认能力通过corsair.withTenant(id)切换租户上下文。关于 KEK 与 Hub 的详细说明见 docs/quick-start.mdx租户隔离机制见 docs/concepts/multi-tenancy.mdxAPI Key 概念见 docs/concepts/api-key.mdx。连接租户与凭据管理插件使用API Key认证Auth: API key。当某个租户第一次调用端点时Corsair 会提示该租户提供 Blocknative API Key而不是在服务端预置全局密钥——这正是多租户 SaaS 所需的每个租户用自己的账号模式。从源码看blocknative()工厂packages/blocknative/index.ts内部逻辑如下默认认证类型为api_key且authConfig声明account: [one]即每个租户绑定一个账号keyBuilder优先使用初始化时传入的options.key若配置了全局 Key否则从租户密钥存储ctx.keys.get_api_key()读取找不到时抛出AuthMissingError(blocknative, api_key)。连接流程通过manage.connect.createLink生成连接链接将租户引导至 Hub 托管的连接页完成 API Key 填写const { connectUrl } await corsair.manage.connect.createLink({ plugin: blocknative, tenantId: acme, }); // 将用户浏览器重定向到 connectUrl连接机制详见 docs/management/connect.mdxOAuth 相关流程见 docs/concepts/oauth.mdx。端点详解5 个 Gas 操作插件将 5 个端点统一挂在blocknative.api.gas.*命名空间下端点的嵌套声明见 packages/blocknative/index.ts。下表来自 packages/blocknative/README.md操作Operation ID风险说明gas.getBaseFeeEstimatesblocknative.api.gas.getBaseFeeEstimatesread获取未来 5 个以太坊区块的基础费、blob 基础费与优先费实时预测gas.getDistributionblocknative.api.gas.getDistributionread获取当前内存池 Gas 价格分布分解gas.getOraclesblocknative.api.gas.getOraclesread获取各链支持的 Gas 预言机元数据gas.getPricesblocknative.api.gas.getPricesread按指定入块概率获取 Gas 价格估算下一区块或约 10 秒gas.getSupportedChainsblocknative.api.gas.getSupportedChainsread获取 Blocknative Gas 服务支持的链元数据gas.getPrices获取特定入块概率下的 Gas 价格估算。输入参数见 packages/blocknative/endpoints/types.ts参数类型必填说明chainidnumber正整数否目标链 IDsystemstring否链系统标识如ethereumnetworkstring否网络标识如mainconfidenceLevelsnumber[]1–99 的整数否期望的入块置信度列表调用示例const tenant corsair.withTenant(acme); const prices await tenant.blocknative.api.gas.getPrices({ chainid: 1, confidenceLevels: [99, 50], });输出结构BlocknativeBlockPrices见 packages/blocknative/schema/database.ts包含system、network、unit单位如 gwei、blockPrices[]每个区块条目含blockNumber、estimatedTransactionCount、baseFeePerGas、blobBaseFeePerGas及estimatedPrices[]每个价格点含confidence、price、maxPriorityFeePerGas、maxFeePerGas。底层映射该操作请求 Blocknative 官方端点GET /gasprices/blockprices见 packages/blocknative/endpoints/gas.tschainid、system、network、confidenceLevels原样透传为查询参数数组参数会重复追加如confidenceLevels99confidenceLevels50由 client.ts 处理。gas.getBaseFeeEstimates获取未来 5 个以太坊区块的基础费、blob 基础费与优先费预测。输入为空对象{}。await tenant.blocknative.api.gas.getBaseFeeEstimates({});输出BlocknativeBaseFeeEstimates见 schema/database.ts除system/network/unit外还包含baseFeePerGas、blobBaseFeePerGas以及estimatedBaseFees[]数组元素为按区块偏移如pending1映射到{ confidence, baseFee }[]的记录。底层请求GET /gasprices/basefee-estimates无查询参数见 endpoints/gas.ts。gas.getDistribution获取当前内存池 Gas 价格分布。输入参数chainid?: number正整数。await tenant.blocknative.api.gas.getDistribution({ chainid: 1 });输出BlocknativeGasDistribution见 schema/database.ts包含maxPrice、currentBlockNumber、msSinceLastBlock与topNDistribution内含distribution: number[][]分布矩阵与n。底层请求GET /gasprices/distribution?chainid1。gas.getOracles获取各链支持的 Gas 预言机元数据。输入为空对象。await tenant.blocknative.api.gas.getOracles({});输出形如{ oracles: BlocknativeOracle[] }。每个预言机条目见 schema/database.ts包含arch、chainId、label、icon、system、network、addressByVersion、rpcUrl、blockExplorerUrl等可选字段。底层请求GET /oracles返回数组后由插件包装为{ oracles }结构见 endpoints/gas.ts。gas.getSupportedChains获取 Blocknative Gas 服务支持的链元数据。输入为空对象。await tenant.blocknative.api.gas.getSupportedChains({});输出形如{ chains: BlocknativeChain[] }。每个链条目见 schema/database.ts包含arch、chainId、label、icon、system、network、features[]等字段。底层请求GET /chains。各端点的完整输入/输出类型定义集中在 packages/blocknative/endpoints/types.tsZod schema 同时被用于运行时请求参数校验与响应数据解析保证类型安全贯穿 HTTP 全链路。底层请求客户端与错误语义所有端点共用makeBlocknativeRequestpackages/blocknative/client.ts完成 HTTP 调用关键实现细节Base URLBLOCKNATIVE_API_BASE https://api.blocknative.com官方 Gas Platform 地址认证头Authorization头直接放置原始 API Key不是Bearer前缀这是 Blocknative 官方要求的格式api.test.ts 中专门断言了这一点超时单请求 20 秒AbortSignal.timeout(REQUEST_TIMEOUT_MS)超时抛出BlocknativeAPIError响应解析先读取文本再 JSON.parse解析失败时按原始文本处理最终用对应 Zod schema 校验校验失败同样抛出BlocknativeAPIError错误类型BlocknativeAPIError含code、status、body与BlocknativeRateLimitError429含retryAfterMs从Retry-After响应头解析支持秒数与 HTTP 日期两种格式。内置错误处理与重试策略插件内置错误处理器packages/blocknative/error-handlers.ts可按需在blocknative({ errorHandlers })中覆盖处理器匹配条件行为RATE_LIMIT_ERRORBlocknativeRateLimitError实例、HTTP 429、或消息含ratelimit/rate limit/429等最多重试 5 次并透传服务端Retry-After头作为退避参考AUTH_ERRORHTTP 401或消息含authorization header must contain a valid apikey、not a valid api key、unauthorized、401不重试maxRetries: 0密钥无效时重试无意义DEFAULT兜底匹配所有错误不重试重试行为由 Corsair 核心执行器在每次调用时按匹配到的处理器决定api.test.ts中通过构造 401/429 错误验证了匹配与重试策略的返回结果。自定义错误处理可参考 demo/minimal/corsair-full.ts 中 Slack 插件的写法在errorHandlers中重写RATE_LIMIT_ERROR的handler并返回{ maxRetries, headersRetryAfterMs, retryStrategy }。通用错误处理概念见 docs/concepts/error-handling.mdx。本地数据同步与查询Blocknative 插件会把每次调用的响应同步到本地数据库。实体清单定义在 packages/blocknative/schema/index.tschains、oracles、blockPrices、baseFeeEstimates、gasDistributionsschema 版本为1.0.0。所有实体都支持tenant.blocknative.db.entity.search({ data, limit?, offset? })与.list()。以baseFeeEstimates为例const rows await corsair.blocknative.db.baseFeeEstimates.search({ data: { unit: { equals: gwei }, currentBlockNumber: { gte: 19000000 }, }, limit: 100, offset: 0, });各实体可用的过滤字段与操作符完整表格见 docs/plugins/blocknative/database.mdxbaseFeeEstimatesentity_id、system、network、unit字符串equals/contains/startsWith/endsWith/incurrentBlockNumber、msSinceLastBlock、baseFeePerGas、blobBaseFeePerGas数值equals/gt/gte/lt/lte/inblockPricesentity_id、system、network、unit、maxPrice、currentBlockNumber、msSinceLastBlock操作符同上chainsentity_id、arch、chainId数值、label、icon、system、network字符串操作符gasDistributionsentity_id、system、network、unit、maxPrice、currentBlockNumber、msSinceLastBlockoraclesentity_id、arch、chainId、label、icon、system、network、rpcUrl、blockExplorerUrl。每条.search()均支持limit/offset分页.list()与.search()位于同一路径。数据库操作通用能力见 docs/concepts/database.mdx数据同步机制见 docs/concepts/integrations.mdx。Webhooks无Blocknative 插件不提供任何 WebhookblocknativeWebhooksNested {}且pluginWebhookMatcher恒返回false见 packages/blocknative/index.ts。如需事件驱动能力可结合 Corsair 支持的第三方工作流编排方案见 docs/guides 目录下的相关指南。测试与验证仓库为插件提供了两层测试保障单元测试packages/blocknative/api.test.tsmock 全局fetch验证插件实例结构5 个端点 schema、api_key认证、空 webhooks、AuthMissingError抛出逻辑、Authorization头格式原始 Key 而非 Bearer、各端点的 URL 与查询参数映射、401/429 错误处理匹配集成测试packages/blocknative/integration.test.ts设置BLOCKNATIVE_API_KEY环境变量后自动启用直连官方 API 验证/chains、/gasprices/blockprices、/gasprices/basefee-estimates、/gasprices/distribution、/oracles的响应可被本地 schema 正确解析。在packages/blocknative目录下可分别运行pnpm testJest与pnpm typechecktsc 类型检查构建产物通过 tsup 输出到dist/。与 Agent 生态结合Corsair 的 MCP 适配层可以把blocknative.api.*操作直接暴露为 MCP 工具供 Claude、LangChain、LlamaIndex、Mastra 等 Agent 框架调用——这意味着 LLM Agent 可以直接查询实时 Gas 价格并据此辅助用户决策。适配器位于 adapters 目录相关用法见 docs/mcp-adapters 文档。许可证corsair-dev/blocknative遵循 Apache-2.0 许可见 packages/blocknative/package.json 的license字段及仓库根目录 LICENSE。【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsair创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门