oracle智能合约和oracle服务之间的交互



我想使用此代码来恢复温度并将结果返回给智能合约

contract CMCOracle {
// Contract owner   address public owner;
// BTC Marketcap Storage   uint public btcMarketCap;
// Callback function   event CallbackGetBTCCap();
function CMCOracle() public {
owner = msg.sender;
}
function updateWe() public {
// Calls the callback function
CallbackGetBTCCap();
}
function setBTCCap(uint cap) public {
// If it isn't sent by a trusted oracle
// a.k.a ourselves, ignore it
require(msg.sender == owner);
btcMarketCap = cap;
}
function getBTCCap() constant public returns (uint) {
return btcMarketCap;
}
}
var fetch = require('fetch')
var OracleContract = require('./build/contracts/CMCOracle.json')
var contract = require('truffle-contract')
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https://localhost:8545'));
// Truffle abstraction to interact with our
// deployed contract
var oracleContract = contract(OracleContract);
oracleContract.setProvider(web3.currentProvider);
// Dirty hack for web3@1.0.0 support for localhost testrpc
// see https://github.com/trufflesuite/truffle-contract/issues/56#issuecomment-331084530
if (typeof oracleContract.currentProvider.sendAsync !== "function") {
oracleContract.currentProvider.sendAsync = function() {
return oracleContract.currentProvider.send.apply(
oracleContract.currentProvider, arguments
);
};
}
// Get accounts from web3 web3.eth.getAccounts((err, accounts) => {
oracleContract.deployed().then((oracleInstance) => {
// Watch event and respond to event
// With a callback function
oracleInstance.CallbackGetBTCCap()
.watch((err, event) => {
// Fetch data
// and update it into the contract
fetch.fetchUrl('https://api.coinmarketcap.com/v1/global/',(err, m, b)=> {
const cmcJson = JSON.parse(b.toString());
const btcMarketCap = parseInt(cmcJson.total_market_cap_usd);
// Send data back contract on-chain
oracleInstance.setBTCCap(btcMarketCap, {from: accounts[0]});
})
})
}).catch((err) => { console.log(err) });

但我不明白如何更改代码。

  • 智能合约如何将我想了解其温度的城市传递给oracle服务
  • oracle服务使用什么API从外部源获取温度
  • 我应该如何更改此代码

来源:https://kndrck.co/posts/ethereum_oracles_a_simple_guide/

  1. 智能合约不与API交互,而是与Oracle本身交互。通常情况下,它应该是两个不同的合同,就像其中一个合同应该与外部世界分离一样。甲骨文合约是区块链的API,它基本上驻留在区块链中。您可以通过合同包装库(web3j,ethereumj(来联系合同
  2. 合约包装器将以JSON的形式从API获取数据。然后应用程序将数据转换为Solidity语言中定义的原始数据。一旦完成,只要应用程序从API获取数据,数据就会通过emit-event函数不断发送到区块链。最后,您将拥有一个确定性数据库源,这样您就可以复制此源并按原样转移到另一个位置
  3. 例如,您可以使用"api.openweathermap.org/data/2.5/weather"和数据结构更改名为"https://api.coinmarketcap.com/v1/global/"的API端点(链接:https://openweathermap.org/current)

相关内容

  • 没有找到相关文章

最新更新