Solidity

使用 oraclize 和solidity-util - 無法拆分由空格分隔的字元串

  • November 6, 2018

我正在學習使用 Oraclize 將其連接到 random.org 以生成隨機數。

這是我的測試合約程式碼:

pragma solidity ^0.4.25;

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
import "github.com/willitscale/solidity-util/lib/Strings.sol";
import "github.com/willitscale/solidity-util/lib/Integers.sol";
import "github.com/willitscale/solidity-util/lib/Addresses.sol";

contract Oraclize is usingOraclize {

   using Strings for string;
   using Integers for uint;
   using Addresses for address;

   string public randomNumbers;
   uint[] public randomNumbersArray;

   event newOraclizeQuery(string description);
   event randomNumbersGenerated(string randomNumbers);

   constructor() public {
       update();
   }

   function __callback(bytes32, string result) public {
       if (msg.sender != oraclize_cbAddress()) revert();
       randomNumbers = result;

       string[] storage split = result.split(" ");

       for (uint i = 0; i < split.length; i++) {
           randomNumbersArray.push(parseInt(split[i]));
       }

       emit randomNumbersGenerated(randomNumbers);
   }

   function update() public payable {
       emit newOraclizeQuery("Loading new set of random numbers, standing by for the answer...");
       oraclize_query('URL', '...');
   }

}

我已經通過 Rinkeyby測試網在http://remix.ethereum.org上測試了上述內容。我部署了合約,然後呼叫了update()函式,然後檢查了兩個公共欄位,它們都是空的/0:

在此處輸入圖像描述

我在這裡做錯了什麼?

當我取出程式碼的空格部分的隨機數拆分時,回調開始工作。

在此處輸入圖像描述

有任何想法嗎?

我使用了不同的solidity utils library + WolframAlpha alpha api來解決它,如下所示:

pragma solidity ^0.4.25;

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
import "github.com/Arachnid/solidity-stringutils/strings.sol";

contract OraclizeTest is usingOraclize {

   using strings for *;

   string public randomNumbers;
   bytes32 public loadNewRandomNumbersQueryId;

   event NewRandomNumbers(string _randomNumbers);

   function loadNewRandomNumbers() public payable {
       loadNewRandomNumbersQueryId = oraclize_query("WolframAlpha", "10 unique random numbers between 0 and 53");
   }

   function __callback(bytes32 _queryId, string _result) public {
       require(_queryId == loadNewRandomNumbersQueryId, "Oraclize Query Id Does Not Match");
       require(msg.sender == oraclize_cbAddress(), "Invalid Oraclize Callback Address");

       if (_queryId == loadNewRandomNumbersQueryId) {
           randomNumbers = _result;
           emit NewRandomNumbers(randomNumbers);
       }
   }

   function parseRandomNumbers() public view returns (uint[] _randomNumbersArray) {
       strings.slice memory s = randomNumbers.toSlice();
       strings.slice memory delim = ",".toSlice();
       uint[] memory parts = new uint[](s.count(delim) + 1);
       for (uint i = 0; i < parts.length; i++) {
           parts[i] = parseInt(s.split(delim).toString());
       }
       return parts;
   }

}

引用自:https://ethereum.stackexchange.com/questions/60669