问题描述
我正在尝试使用 Chainlink 连接到 API,以从下面请求中的 URL 获取 uint。问题是,每次“音量”值返回 0 时。我感觉问题是两件事之一:
- oracle 不喜欢访问数组。我试过“data[0]”和“data.0”。两者都适用于文档页面上的 jsonPath。
- API 返回的是字符串而不是数字(因为数字用引号括起来)。我也尝试过 bytes32 作业,只返回 0x0。其他 StackOverflow 帖子还展示了预言机将字符串数字读取为数字。
以下代码片段是对 Chainlink 文档中显示的“deploy on remix”代码所做的唯一更改:https://docs.chain.link/docs/make-a-http-get-request。
request.add("get","https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/avg_interest_rates?sort=-record_date");
request.add("path","data.0.avg_interest_rate_amt");
合同通过 Remix/Metamask 部署在 Kovan 上,并为合同提供了大量链接。我可能做错了什么?
解决方法
有几个问题:
-
响应太大,所以节点只是在
HttpGet
任务处停止。我已经在我的节点上对其进行了测试,这是我得到的确切错误:HTTP response too large,must be less than 32768 bytes
。如果你能影响这一点,那就太好了。否则,您将需要拥有自己的节点,该节点将返回符合上述限制的较短响应。 -
结果应该只有整数,Solidity 不理解小数点,而是使用 WEI。这就是为什么你需要将结果乘以至少 100,10^18 是一个标准,所以我会这样做。以下部分应该适合您:
function requestData(string memory _id,string memory _field) public {
Chainlink.Request memory request = buildChainlinkRequest(jobId,address(this),this.fulfillData.selector);
request.add("get","https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/avg_interest_rates?sort=-record_date");
string[] memory path = new string[](3);
path[0] = "data";
path[1] = _id;
path[2] = _field;
request.addStringArray("path",path);
int timesAmount = 10**18;
request.addInt("times",timesAmount);
sendChainlinkRequestTo(oracle,request,fee);
}
我还添加了 _id
和 _field
作为函数参数来查询任何对象的任何字段。请注意,这只有在您能弄清楚如何获得更短的响应时才有效。