如何在以太坊专用网络中稳定调用API



我试图在以太坊私有网络的智能合约代码中调用外部API,但没有得到任何解决方案。

我也通过链接解决方案,但我没有得到oracle id和作业id从market .link根据最新的网站更新

有人可以帮助我如何使HTTP获得/发布请求与以太坊专用网络稳固?

Solidity被编译为EVM(以太坊虚拟机)字节码。为了保证所有操作的确定性,在虚拟机内部运行的代码不能与虚拟机外部的资源通信。

话虽如此,有像Chainlink这样的服务,允许你在公共网络上通过Solidity代码与外部api进行通信。当你调用一个特定的Chainlink SDK函数,传递API URL和其他参数时,它会发出Solidity事件。他们的离线应用程序正在监听此事件,查询URL并将包含结果的新交易发送回您的合约。

您的私有网络中没有Chainlink节点。因此,在私有网络上,您可以用自己的off - chain应用程序复制这种方法。

可靠性:

pragma solidity ^0.8;
contract MyContract {
event DataRequested(string url);
function requestData(string memory url) public {
emit DataRequested(url);
}
function receiveData(bytes memory data) public {
// it's recommended to validate `msg.sender`
// and allow for this function to be invoked only from an authorized address
require(msg.sender == address(0x123));
}
}

JS:

const Web3 = require("web3");
const web3 = new Web3(YOUR_NODE_URL);
const myContract = new web3.eth.Contract(ABI, ADDRESS);
// handle the event when it's emitted
myContract.events.DataRequested(async (eventData) => {
// process the URL
const result = queryUrl(eventData.returnValues.url);
// send the data back from the authorized address
// your local `web3` instance or the node need to know the private key of `0x123` address
await myContract.methods.receiveData(result).send({
from: "0x123"
});
});