簡體   English   中英

如何使用以太坊私有網絡調用 API

[英]How to call API in solidity with ethereum private network

我正在嘗試使用以太坊專用網絡在智能合約代碼中調用外部 API,但沒有得到任何解決方案。

我也經歷了 chainlink 解決方案,但根據最新的網站更新,我沒有從markt.link獲得 oracle id 和 job id。

有人可以幫我解決如何使用以太坊專用網絡進行 HTTP 獲取/發布請求嗎?

Solidity 被編譯為 EVM(以太坊虛擬機)字節碼。 為了保持所有操作的確定性,在 VM 內部運行的代碼不能與 VM 外部的資源進行通信。

話雖如此,還有諸如 Chainlink 之類的服務,允許您通過公共網絡上的 Solidity 代碼與外部 API 進行通信。 當您調用特定的 Chainlink SDK 函數時,它會向其傳遞 API URL 和其他參數,它會發出 Solidity 事件。 他們的鏈下應用程序正在監聽此事件,查詢 URL 並將包含結果的新交易發送回您的合約。

您的私有網絡上沒有 Chainlink 節點。 因此,在專用網絡上,您可以使用自己的鏈下應用程序復制這種方法。

堅固性:

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"
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM