首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >智能契约- OpenWeatherMap API

智能契约- OpenWeatherMap API
EN

Ethereum用户
提问于 2018-05-06 03:54:36
回答 2查看 315关注 0票数 1

我希望创建一个智能契约,在连续3天或更多天天气超过30度时,使用OpenWeatherMap API将数量的以太发送到某个地址。

如何在智能契约中使用API中的数据?

提前谢谢..。

EN

回答 2

Ethereum用户

发布于 2018-05-07 08:08:03

由于所有事务都必须是确定性的,EVM虚拟机(EVM)无法访问外部网络。

您需要创建一个oracle服务,该服务读取外部API,并以可信的方式将此信息提供给Ethereum智能契约。

这里有更多的背景信息,甲骨文服务是如何在幕后运作的?

票数 0
EN

Ethereum用户

发布于 2022-03-15 09:33:00

是的,有可能。

备选方案1:容易但集中

您需要Web3JS (或py或java等)。创建一个NodeJS文件index.js,安装web3axios (调用天气数据),在某个地方安装host index.js,当温度升高或下降时,调用智能契约函数。

备选方案2:艰难但分散。

使用Oracles https://ethereum.org/en/developers/docs/oracles/它为智能契约提供了正确的数据。

教程:https://www.youtube.com/watch?v=AtHp7me2Yks

API调用具有坚实性的示例:

代码语言:javascript
复制
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract APIConsumer is ChainlinkClient {
    using Chainlink for Chainlink.Request;
  
    uint256 public volume;
    
    address private oracle;
    bytes32 private jobId;
    uint256 private fee;
  
    constructor() {
        setPublicChainlinkToken();
        oracle = 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8;
        jobId = "d5270d1c311941d0b08bead21fea7747";
        fee = 0.1 * 10 ** 18; // (Varies by network and job)
    }
    
   
    function requestVolumeData() public returns (bytes32 requestId) 
    {
        Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
        
        // Set the URL to perform the GET request on
        request.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
        
        // Set the path to find the desired data in the API response, where the response format is:
        // {"RAW":
        //   {"ETH":
        //    {"USD":
        //     {
        //      "VOLUME24HOUR": xxx.xxx,
        //     }
        //    }
        //   }
        //  }
        request.add("path", "RAW.ETH.USD.VOLUME24HOUR");
        
        // Multiply the result by 1000000000000000000 to remove decimals
        int timesAmount = 10**18;
        request.addInt("times", timesAmount);
        
        // Sends the request
        return sendChainlinkRequestTo(oracle, request, fee);
    }
    
    /**
     * Receive the response in the form of uint256
     */ 
    function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
    {
        volume = _volume;
    }

    // function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract
}
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/47686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档