背景
该示例代码取自官方文档(https://docs.oraclize.it/#ethereum-quick-start),并升级到0.4.25
版本。
代码
pragma solidity ^0.4.25;
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);
constructor() public payable {
emit LogConstructorInitiated("Constructor was initiated. Call 'updatePrice()' to send the Oraclize Query.");
}
function __callback(bytes32 myid, string result) public {
if (msg.sender != oraclize_cbAddress()) revert();
ETHUSD = result;
emit LogPriceUpdated(result);
}
function updatePrice() public payable {
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
oraclize_query("URL", "json(https://api.gdax.com/products/ETH-USD/ticker).price");
}
}
}
部署
使用 Remix 和 METAMASK 部署很方便。因为调用 Oraclize 需要付费,我给了10 Gwei
(图中是调用后返回时抓的图,因此已经变回0 Gwei
了)。

交易记录是 https://rinkeby.etherscan.io/tx/0x268441bf511a3fe94e36101638c062d46c7c0dc73987a53352310432e1146d87,得到合约地址0x879db62e6A7f992eb4E5D86962D00F9464A5769E
。
运行
现在,可以点击按钮和合约进行交互了。

同时,也能看到Event的输出。

同时,如果查看交易记录的话,可以看到Oraclize的返回(回调)。

第一条是构造函数,第二条是updatePrice的调用,第三条是Oraclize的回调(红框)。
其他遗留问题
调试过程中,我注意到一个问题,Remix 无法正确获得ETHUSD
的值。

而我使用 MyEtherWallet 则可以正确显示。

我怀疑是 Remix 调试解析的问题,因为跟本次 Oraclize 没关系,就不深究了,以后有空了再说。
网友评论