使用Oraclize让智能合约调用外部数据

简介

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

  • Orcalize的数据源有:

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


使用步骤

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

备注

  • 官方文档:http://docs.oraclize.it/#home
  • 官方例子在线IDE:http://dapps.oraclize.it/browser-solidity/#gist=9817193e5b05206847ed1fcd1d16bd1d&version=soljson-v0.4.24+commit.e67f0147.js
  • 查询api: http://www.realitykeys.com/

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

你可能感兴趣的:(智能合约)