版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33781658/article/details/88681961
oraclize入门
我们可以通过oraclize在ethereum与外界通信
看下文档
https://docs.oraclize.it/#ethereum
看下示例代码
pragma solidity ^0.4.11;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract ExampleContract is usingOraclize {
string public ETHUSD;
event LogConstructorInitiated(string nextStep);
event LogPriceUpdated(string price);
event LogNewOraclizeQuery(string description);
function ExampleContract() payable {
LogConstructorInitiated("Constructor was initiated. Call 'updatePrice()' to send the Oraclize Query.");
}
function __callback(bytes32 myid, string result) {
if (msg.sender != oraclize_cbAddress()) revert();
ETHUSD = result;
LogPriceUpdated(result);
}
function updatePrice() payable {
if (oraclize_getPrice("URL") > this.balance) {
LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
oraclize_query("URL", "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price");
}
}
}
这里的代码的意思是
通过updatePrice方法查询像现在ETH的价格
_callback就是请求的回调,
然后把价格存入到ETHUSD变量里面
然后我们只要访问ETHUSD就可以得到查询的结果
然后我们也可以请求各种不同的地址
// This code example will ask Oraclize to send as soon as possible
// a transaction with the primary result (as a string) of the given
// formula ("random number between 0 and 100") fetched from the
// data-source "WolframAlpha".
oraclize_query("WolframAlpha", "random number between 0 and 100");
oraclize_query("URL", "https://api.kraken.com/0/public/Ticker?pair=ETHXBT")
oraclize_query("URL",
"json(https://www.therocktrading.com/api/ticker/BTCEUR).result.0.last")
oraclize_query("IPFS", "QmdEJwJG1T9rzHvBD8i69HHuJaRgXRKEQCP7Bh1BVttZbU")
// The URL datasource also supports a supplement argument, useful for creating HTTP POST requests.
// If that argument is a valid JSON string, it will be automatically sent as JSON.
oraclize_query("URL", "json(https://shapeshift.io/sendamount).success.deposit",
'{"pair":"eth_btc","amount":"1","withdrawal":"1AAcCo21EUc1jbocjssSQDzLna9Vem2UN5"}')