【区块链】使用Oraclize让智能合约调用外部数据

简介

Oraclize对于以太坊来说,是一份智能合约,继承它之后,自定义的合约可以通过api访问外部的数据。但需要给一定的费用。

  • Orcalize的数据源有:

    • URL (合约外部的API接口)
    • WolframAlpha (新一代的搜索引擎,能根据问题直接给出答案,如London的天气)
    • IPFS (星际文件系统,一个分布式的存储系统)
    • random (随机数引擎,能产生一个安全的随机数)
  • Orcalize的数据源调用的费用:


使用步骤

  • (1)继承Oraclize合约
  • (2)定义外部数据源的访问方式
  • (3)定义数据返回的回调函数__callback()

官方例子

  • 查看Youtube某个视频的观看人数
/*
   Youtube video views

   This contract keeps in storage a views counter
   for a given Youtube video.
*/


pragma solidity ^0.4.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract YoutubeViews is usingOraclize {

    string public viewsCount;

    event newOraclizeQuery(string description);
    event newYoutubeViewsCount(string views);

    function YoutubeViews() {
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        viewsCount = result;
        newYoutubeViewsCount(viewsCount);
        // do something with viewsCount. like tipping the author if viewsCount > X?
    }

    function update() payable {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query('URL', 'html(https://www.youtube.com/watch?v=9bZkp7q19f0).xpath(//*[contains(@class, "watch-view-count")]/text())');
    }

}                                          
  • 调用WolframAlpha查看伦敦的天气
/*
   WolframAlpha example

   This contract sends a temperature measure request to WolframAlpha
*/


pragma solidity ^0.4.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract WolframAlpha is usingOraclize {

    string public temperature;

    event newOraclizeQuery(string description);
    event newTemperatureMeasure(string temperature);

    function WolframAlpha() {
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        temperature = result;
        newTemperatureMeasure(temperature);
        // do something with the temperature measure..
    }

    function update() payable {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query("WolframAlpha", "temperature in London");
    }
} 

备注

猜你喜欢

转载自blog.csdn.net/ns2250225/article/details/80498838