我正在开发一个项目,使用一个必须进行API调用的智能合约。我正试图遵循这个链接的ChainLink指南。我想从另一个函数调用requestRiskData(),而不是使用输出(风险变量更新)来做一些事情。但是,由于它需要像30秒更新风险值后,oracle调用我怎么能等待风险变量更新?
有人来帮忙吗?Thx
我将在这里附加代码:
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.8/ConfirmedOwner.sol";
contract APIConsumer is ChainlinkClient, ConfirmedOwner {
using Chainlink for Chainlink.Request;
uint256 public risk;
bytes32 private jobId;
uint256 private fee;
string public a= "0x6e1db9836521977ee93651027768f7e0d5722a33";
event RequestRisk(bytes32 indexed requestId, uint256 risk);
/**
* @notice Initialize the link token and target oracle
*
* Goerli Testnet details:
* Link Token: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* Oracle: 0xCC79157eb46F5624204f47AB42b3906cAA40eaB7 (Chainlink DevRel)
* jobId: ca98366cc7314957b8c012c72f05aeeb
*
*/
constructor() ConfirmedOwner(msg.sender) {
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
setChainlinkOracle(0xCC79157eb46F5624204f47AB42b3906cAA40eaB7);
jobId = "ca98366cc7314957b8c012c72f05aeeb";
fee = (1 * LINK_DIVISIBILITY) / 10; // 0,1 * 10**18 (Varies by network and job)
}
// Set the path to find the desired data in the API response, where the response format is:
// {
//"data":{
// "0x6e1db9836521977ee93651027768f7e0d5722a33":{
// "risk":{
// "score":....
// }
// }
// }
// }
function requestRiskData() public returns (bytes32 requestId) {
Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
req.add("get","https://demo.anchainai.com/api/address_risk_score?proto=eth&address=0x6e1db9836521977ee93651027768f7e0d5722a33&apikey=demo_api_key");
req.add("path", "data,0x6e1db9836521977ee93651027768f7e0d5722a33,risk,score");
return sendChainlinkRequest(req, fee);
}
function fulfill(
bytes32 _requestId,
uint256 _risk
) public recordChainlinkFulfillment(_requestId) {
emit RequestRisk(_requestId, _risk);
risk = _risk;
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(
link.transfer(msg.sender, link.balanceOf(address(this))),
"Unable to transfer"
);
}
function myStuff() public payable{
requestRiskData();
if(risk>2){
//DO MY STUFF
}
}
}
我试着写myStuff()函数,但我不知道如何处理这个
你能解释一下你的意思吗?我想从另一个函数调用requestRiskData(),而不是使用输出(风险变量更新)来做一些事情
当你说"使用输出来做一些事情"你是指在合约之外(前端)还是在智能合约内部?
如果您想使用oracle返回的_risk
的值,您应该在fulfill()
回调中设置_risk
的值后添加该逻辑(或调用实现该逻辑的辅助函数)。
所以在您的情况下,以下行应该移动到fulfill()
回调的末尾:
if(risk>2){
//DO MY STUFF
}
如果你在前端使用_risk
的值,那么在你的前端使用ethersjs或web3js来监听RequestRisk
事件。
顺便说一句,你可能想要考虑重命名该事件,因为它不是在请求函数中,而是在回调中,所以它真的应该是RiskReceived
或那种名称的事件。
希望这对你有帮助!