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 服务使用什么 API 从外部来源获取温度?
  • 我应该如何更改此代码

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

解决方法

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