您可以使用 Chainlink 作为您的Oracle。
正如许多人所提到的,您将需要一个 oracle 来获取您的 API 调用。需要注意的重要一点是,您的合约实际上是要求预言机为您进行 API 调用,而不是自己进行 API 调用。这是因为区块链是确定性的。如需更多信息,请参阅this thread。
要回答您的问题,您可以使用去中心化预言机服务Chainlink。
你会添加一个函数:
function getWinner()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
出于以下示例的目的,我们将假设您想要返回 uint256 而不是地址。您可以返回 bytes32,然后将其转换为地址,但为简单起见,假设 API 返回获胜者的索引。您必须找到可以发出http.get 请求并返回uint256 对象的节点和jobId。您可以从market.link 找到节点和作业。每个测试网(Ropsten、Mainnet、Kovan 等)都有不同的节点地址,因此请确保选择正确的。
对于这个演示,我们将使用 LinkPool 的 ropsten 节点
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
理想情况下,您应该选择多个节点来运行您的工作,以使其无需信任且去中心化。您可以read here 了解有关预协调器和聚合数据的更多信息。 披露我是该博客的作者
您的完整合同如下所示:
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract GetData is ChainlinkClient {
uint256 indexOfWinner;
address public manager;
address payable[] public players;
uint256 MINIMUM = 1000000000000000;
// The address of an oracle
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
//bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
uint256 ORACLE_PAYMENT = 1 * LINK;
constructor() public {
setPublicChainlinkToken();
manager = msg.sender;
}
function getWinnerAddress()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
// When the URL finishes, the response is routed to this function
function fulfill(bytes32 _requestId, uint256 _index)
public
recordChainlinkFulfillment(_requestId)
{
indexOfWinner = _index;
assert(msg.sender == manager);
players[indexOfWinner].transfer(address(this).balance);
players = new address payable[](0);
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
modifier onlyOwner() {
require(msg.sender == manager);
_;
}
// Allows the owner to withdraw their LINK on this contract
function withdrawLink() external onlyOwner() {
LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
}
}
这可以满足您的所有需求。
如果不能调整API返回uint,可以返回一个bytes32,然后转成地址或者字符串。
function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}