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

Chainlink Functions调用实时API时encodeUint256输入无效问题求助

我正在编写Chainlink Functions的source.js脚本,尝试从实时API获取footprint数据(API地址:https://api.wheretheiss.at/v1/satellites/25544,无需密钥),脚本代码如下:

const config = {
  url: "https://api.wheretheiss.at/v1/satellites/25544",
}

const response = Functions.makeHttpRequest(config)
return Functions.encodeUint256(Math.round(response.footprint))

使用npx hardhat functions-simulate运行脚本时,收到客户端合约返回的错误:encodeUint256 invalid input.,求排查解决。


问题原因与解决方案

1. 核心问题:异步请求未正确处理

Functions.makeHttpRequest是异步函数,直接赋值给response得到的是Promise对象,而非API返回的实际数据,导致response.footprint为undefined,Math.round(undefined)结果为NaN,传入encodeUint256就会触发无效输入错误。同时原代码还忽略了API响应的结构——实际数据存在于response.data字段中,而非直接在response根节点。

2. 修复后的完整代码

const config = {
  url: "https://api.wheretheiss.at/v1/satellites/25544",
}

async function run() {
  try {
    // 等待异步请求完成,获取完整响应
    const response = await Functions.makeHttpRequest(config)
    
    // 校验请求是否成功
    if (!response.success) {
      throw new Error(`API请求失败: ${response.error.message}`)
    }
    
    // 提取并校验footprint字段
    const footprint = response.data.footprint
    if (typeof footprint !== 'number' || isNaN(footprint)) {
      throw new Error(`无效的footprint数据: ${footprint}`)
    }
    
    // 转换为uint256兼容的整数(uint256范围:0 ~ 2^256-1)
    const roundedFootprint = Math.round(footprint)
    if (roundedFootprint < 0 || roundedFootprint > 2**256 - 1) {
      throw new Error(`footprint超出uint256范围: ${roundedFootprint}`)
    }
    
    return Functions.encodeUint256(roundedFootprint)
  } catch (error) {
    throw new Error(`处理失败: ${error.message}`)
  }
}

return run()

3. 关键修复点

  • 用await等待Functions.makeHttpRequest解析完成,获取response.data中的实际API返回值
  • 增加请求成功判断、字段类型校验、数值范围校验,避免无效数据流入编码环节
  • 用async/await包裹整个逻辑,确保异步操作按预期执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:44:55