ETH Price: $3,814.08 (-2.11%)
Gas: 9 Gwei

Transaction Decoder

Block:
17585200 at Jun-29-2023 01:17:47 PM +UTC
Transaction Fee:
0.002412504 ETH $9.20
Gas Used:
47,304 Gas / 51 Gwei

Emitted Events:

96 Wallet.ExecutedTransaction( _destination=0x8c5c6adf33e8ba9ca44517648e183a94c868c889, _value=966300000000000000, _data=0x, _returndata=0x )

Account State Difference:

  Address   Before After State Difference Code
0x02DfF64c...9fd58FC22
0.039684065 Eth
Nonce: 1
0.037271561 Eth
Nonce: 2
0.002412504
0x2a7ed430...f758b7757 0.9663 Eth0 Eth0.9663
0x8C5c6aDf...4C868C889 0.682303176056891503 Eth1.648603176056891503 Eth0.9663
(Fee Recipient: 0xE94...A0c)
2,144.841446242563195227 Eth2,144.841585302921593595 Eth0.000139060358398368

Execution Trace

Wallet.executeTransaction( _destination=0x8C5c6aDf33E8bA9ca44517648E183a94C868C889, _value=966300000000000000, _data=0x ) => ( 0x )
  • ETH 0.9663 0x8c5c6adf33e8ba9ca44517648e183a94c868c889.CALL( )
    {"ABIResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract ABIResolver is ResolverBase {\n    bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;\n\n    event ABIChanged(bytes32 indexed node, uint256 indexed contentType);\n\n    mapping(bytes32=\u003emapping(uint256=\u003ebytes)) abis;\n\n    /**\n     * Sets the ABI associated with an ENS node.\n     * Nodes may have one ABI of each content type. To remove an ABI, set it to\n     * the empty string.\n     * @param node The node to update.\n     * @param contentType The content type of the ABI\n     * @param data The ABI data.\n     */\n    function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {\n        // Content types must be powers of 2\n        require(((contentType - 1) \u0026 contentType) == 0);\n\n        abis[node][contentType] = data;\n        emit ABIChanged(node, contentType);\n    }\n\n    /**\n     * Returns the ABI associated with an ENS node.\n     * Defined in EIP205.\n     * @param node The ENS node to query\n     * @param contentTypes A bitwise OR of the ABI formats accepted by the caller.\n     * @return contentType The content type of the return value\n     * @return data The ABI data\n     */\n    function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {\n        mapping(uint256=\u003ebytes) storage abiset = abis[node];\n\n        for (uint256 contentType = 1; contentType \u003c= contentTypes; contentType \u003c\u003c= 1) {\n            if ((contentType \u0026 contentTypes) != 0 \u0026\u0026 abiset[contentType].length \u003e 0) {\n                return (contentType, abiset[contentType]);\n            }\n        }\n\n        return (0, bytes(\"\"));\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}\n"},"Address.sol":{"content":"pragma solidity ^0.5.0;\n\n/**\n * @dev Collection of functions related to the address type,\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * This test is non-exhaustive, and there may be false-negatives: during the\n     * execution of a contract\u0027s constructor, its address will be reported as\n     * not containing a contract.\n     *\n     * \u003e It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies in extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size \u003e 0;\n    }\n}\n"},"AddrResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract AddrResolver is ResolverBase {\n    bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;\n    bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06;\n    uint constant private COIN_TYPE_ETH = 60;\n\n    event AddrChanged(bytes32 indexed node, address a);\n    event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);\n\n    mapping(bytes32=\u003emapping(uint=\u003ebytes)) _addresses;\n\n    /**\n     * Sets the address associated with an ENS node.\n     * May only be called by the owner of that node in the ENS registry.\n     * @param node The node to update.\n     * @param a The address to set.\n     */\n    function setAddr(bytes32 node, address a) external authorised(node) {\n        setAddrCoinType(node, COIN_TYPE_ETH, addressToBytes(a));\n    }\n\n    /**\n     * Returns the address associated with an ENS node.\n     * @param node The ENS node to query.\n     * @return The associated address.\n     */\n    function addr(bytes32 node) public view returns (address payable) {\n        bytes memory a = addr(node, COIN_TYPE_ETH);\n        if(a.length == 0) {\n            return address(0);\n        }\n        return bytesToAddress(a);\n    }\n\n    function setAddrCoinType(bytes32 node, uint coinType, bytes memory a) public authorised(node) {\n        emit AddressChanged(node, coinType, a);\n        if(coinType == COIN_TYPE_ETH) {\n            emit AddrChanged(node, bytesToAddress(a));\n        }\n        _addresses[node][coinType] = a;\n    }\n\n    function addr(bytes32 node, uint coinType) public view returns(bytes memory) {\n        return _addresses[node][coinType];\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}"},"balanceable.sol":{"content":"/**\n *  Balanceable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./ERC20.sol\";\n\n\n/// @title Balanceable - This is a contract used to get a balance\ncontract Balanceable {\n    /// @dev This function is used to get a balance\n    /// @param _address of which balance we are trying to ascertain\n    /// @param _asset is the address of an ERC20 token or 0x0 for ether.\n    /// @return balance associated with an address, for any token, in the wei equivalent\n    function _balance(address _address, address _asset) internal view returns (uint256) {\n        if (_asset != address(0)) {\n            return ERC20(_asset).balanceOf(_address);\n        } else {\n            return _address.balance;\n        }\n    }\n}\n"},"base64.sol":{"content":"pragma solidity ^0.5.15;\n\n/**\n * This method was modified from the GPLv3 solidity code found in this repository\n * https://github.com/vcealicu/melonport-price-feed/blob/master/pricefeed/PriceFeed.sol\n */\n\n/// @title Base64 provides base 64 decoding functionality.\ncontract Base64 {\n    bytes constant BASE64_DECODE_CHAR = hex\"000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e003e003f3435363738393a3b3c3d00000000000000000102030405060708090a0b0c0d0e0f10111213141516171819000000003f001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233\";\n\n    /// @return decoded array of bytes.\n    /// @param _encoded base 64 encoded array of bytes.\n    function _base64decode(bytes memory _encoded) internal pure returns (bytes memory) {\n        byte v1;\n        byte v2;\n        byte v3;\n        byte v4;\n        uint length = _encoded.length;\n        bytes memory result = new bytes(length);\n        uint index;\n\n        // base64 encoded strings can\u0027t be length 0 and they must be divisble by 4\n        require(length \u003e 0  \u0026\u0026 length % 4 == 0, \"invalid base64 encoding\");\n\n        if (keccak256(abi.encodePacked(_encoded[length - 2])) == keccak256(\"=\")) {\n            length -= 2;\n        } else if (keccak256(abi.encodePacked(_encoded[length - 1])) == keccak256(\"=\")) {\n            length -= 1;\n        }\n\n        uint count = length \u003e\u003e 2 \u003c\u003c 2;\n        uint i;\n\n        for (i = 0; i \u003c count;) {\n            v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v3 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v4 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n\n            result[index++] = (v1 \u003c\u003c 2 | v2 \u003e\u003e 4) \u0026 0xff;\n            result[index++] = (v2 \u003c\u003c 4 | v3 \u003e\u003e 2) \u0026 0xff;\n            result[index++] = (v3 \u003c\u003c 6 | v4) \u0026 0xff;\n        }\n\n        if (length - count == 2) {\n            v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n\n            result[index++] = (v1 \u003c\u003c 2 | v2 \u003e\u003e 4) \u0026 0xff;\n        } else if (length - count == 3) {\n            v1 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v2 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n            v3 = BASE64_DECODE_CHAR[uint8(_encoded[i++])];\n\n            result[index++] = (v1 \u003c\u003c 2 | v2 \u003e\u003e 4) \u0026 0xff;\n            result[index++] = (v2 \u003c\u003c 4 | v3 \u003e\u003e 2) \u0026 0xff;\n        }\n\n        // Set to correct length.\n        assembly {\n            mstore(result, index)\n        }\n\n        return result;\n    }\n}\n"},"base64Exporter.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./base64.sol\";\n\n\ncontract Base64Exporter is Base64 {\n    /// @dev export _base64decode() as an external function.\n    function base64decode(bytes calldata _encoded) external pure returns (bytes memory) {\n        return _base64decode(_encoded);\n    }\n}\n"},"burner.sol":{"content":"/**\n *  IBurner - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\n\n// The BurnerToken interface is the interface to a token contract which\n// provides the total burnable supply for the TokenHolder contract.\ninterface IBurner {\n    function currentSupply() external view returns (uint256);\n}\n"},"burnerToken.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\n\n\ninterface TokenHolder {\n    function burn(address, uint256) external returns (bool);\n}\n\n\ncontract BurnerToken {\n    using SafeMath for uint256;\n\n    event Transfer(address indexed from, address indexed to, uint256 value);\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    uint256 public currentSupply;\n\n    address public owner;\n    string public name;\n    uint8 public decimals;\n    string public symbol;\n\n    mapping(address =\u003e uint256) public balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint256)) public allowance;\n\n    //Holds accumulated dividend tokens other than TKN\n    TokenHolder public tokenholder;\n\n    constructor() public {\n        owner = msg.sender;\n        name = \"Monolith TKN\";\n        decimals = 8;\n        symbol = \"TKN\";\n    }\n\n    function totalSupply() external view returns (uint256) {\n        return currentSupply;\n    }\n\n    function mint(address addr, uint256 amount) external {\n        balanceOf[addr] = balanceOf[addr].add(amount);\n        currentSupply = currentSupply.add(amount);\n        emit Transfer(address(0), addr, amount);\n    }\n\n    function transfer(address _to, uint256 _value) external returns (bool success) {\n        if (balanceOf[msg.sender] \u003c _value) return false;\n        if (_to == address(0)) return false;\n\n        balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\n        balanceOf[_to] = balanceOf[_to].add(_value);\n        emit Transfer(msg.sender, _to, _value);\n        return true;\n    }\n\n    function transferFrom(address _from, address _to, uint256 _value) external returns (bool success) {\n        if (_to == address(0)) return false;\n        if (balanceOf[_from] \u003c _value) return false;\n\n        uint256 allowed = allowance[_from][msg.sender];\n        if (allowed \u003c _value) return false; //PROBLEM!\n        /* require(_value \u003c= allowed, \"amount exceeds allowance\"); */\n\n        balanceOf[_to] = balanceOf[_to].add(_value);\n        balanceOf[_from] = balanceOf[_from].sub(_value);\n        allowance[_from][msg.sender] = allowed.sub(_value);\n        emit Transfer(_from, _to, _value);\n        return true;\n    }\n\n    function approve(address _spender, uint256 _value) external returns (bool success) {\n        //require user to set to zero before resetting to nonzero\n        if ((_value != 0) \u0026\u0026 (allowance[msg.sender][_spender] != 0)) {\n            return false;\n        }\n\n        allowance[msg.sender][_spender] = _value;\n        emit Approval(msg.sender, _spender, _value);\n        return true;\n    }\n\n    function increaseApproval(address _spender, uint256 _addedValue) external returns (bool success) {\n        uint256 oldValue = allowance[msg.sender][_spender];\n        allowance[msg.sender][_spender] = oldValue.add(_addedValue);\n        emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);\n        return true;\n    }\n\n    function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool success) {\n        uint256 oldValue = allowance[msg.sender][_spender];\n        if (_subtractedValue \u003e oldValue) {\n            allowance[msg.sender][_spender] = 0;\n        } else {\n            allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue);\n        }\n        emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);\n        return true;\n    }\n\n    function setTokenHolder(address _th) external {\n        tokenholder = TokenHolder(_th);\n    }\n\n    function burn(uint256 _amount) public returns (bool result) {\n        if (_amount \u003e balanceOf[msg.sender]) return false;\n\n        balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount);\n        currentSupply = currentSupply.sub(_amount);\n        result = tokenholder.burn(msg.sender, _amount);\n        if (!result) revert();\n        emit Transfer(msg.sender, address(0), _amount);\n    }\n}\n"},"bytesUtils.sol":{"content":"/**\n *  BytesUtils - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\n\n\n/// @title BytesUtils provides basic byte slicing and casting functionality.\nlibrary BytesUtils {\n    using SafeMath for uint256;\n\n    /// @dev This function converts to an address\n    /// @param _bts bytes\n    /// @param _from start position\n    function _bytesToAddress(bytes memory _bts, uint256 _from) internal pure returns (address) {\n        require(_bts.length \u003e= _from.add(20), \"slicing out of range\");\n\n        bytes20 convertedAddress;\n        uint256 startByte = _from.add(32); //first 32 bytes denote the array length\n\n        assembly {\n            convertedAddress := mload(add(_bts, startByte))\n        }\n\n        return address(convertedAddress);\n    }\n\n    /// @dev This function slices bytes into bytes4\n    /// @param _bts some bytes\n    /// @param _from start position\n    function _bytesToBytes4(bytes memory _bts, uint256 _from) internal pure returns (bytes4) {\n        require(_bts.length \u003e= _from.add(4), \"slicing out of range\");\n\n        bytes4 slicedBytes4;\n        uint256 startByte = _from.add(32); //first 32 bytes denote the array length\n\n        assembly {\n            slicedBytes4 := mload(add(_bts, startByte))\n        }\n\n        return slicedBytes4;\n    }\n\n    /// @dev This function slices a uint\n    /// @param _bts some bytes\n    /// @param _from start position\n    // credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity\n    // and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177\n    function _bytesToUint256(bytes memory _bts, uint256 _from) internal pure returns (uint256) {\n        require(_bts.length \u003e= _from.add(32), \"slicing out of range\");\n\n        uint256 convertedUint256;\n        uint256 startByte = _from.add(32); //first 32 bytes denote the array length\n\n        assembly {\n            convertedUint256 := mload(add(_bts, startByte))\n        }\n\n        return convertedUint256;\n    }\n}\n"},"bytesUtilsExporter.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./bytesUtils.sol\";\n\n\ncontract BytesUtilsExporter {\n    using BytesUtils for bytes;\n\n    /// @dev export _bytesToAddress() as an external function.\n    function bytesToAddress(bytes calldata _bts, uint256 _from) external pure returns (address) {\n        return _bts._bytesToAddress(_from);\n    }\n\n    /// @dev export _bytesToBytes4() as an external function.\n    function bytesToBytes4(bytes calldata _bts, uint256 _from) external pure returns (bytes4) {\n        return _bts._bytesToBytes4(_from);\n    }\n\n    /// @dev export _bytesToUint256() as an external function.\n    function bytesToUint256(bytes calldata _bts, uint256 _from) external pure returns (uint256) {\n        return _bts._bytesToUint256(_from);\n    }\n}\n"},"ContentHashResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract ContentHashResolver is ResolverBase {\n    bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;\n\n    event ContenthashChanged(bytes32 indexed node, bytes hash);\n\n    mapping(bytes32=\u003ebytes) hashes;\n\n    /**\n     * Sets the contenthash associated with an ENS node.\n     * May only be called by the owner of that node in the ENS registry.\n     * @param node The node to update.\n     * @param hash The contenthash to set\n     */\n    function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {\n        hashes[node] = hash;\n        emit ContenthashChanged(node, hash);\n    }\n\n    /**\n     * Returns the contenthash associated with an ENS node.\n     * @param node The ENS node to query.\n     * @return The associated contenthash.\n     */\n    function contenthash(bytes32 node) external view returns (bytes memory) {\n        return hashes[node];\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}\n"},"controllable.sol":{"content":"/**\n *  Controllable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./controller.sol\";\nimport \"./ensResolvable.sol\";\n\n\n/// @title Controllable implements access control functionality of the Controller found via ENS.\ncontract Controllable is ENSResolvable {\n    // Default values for mainnet ENS\n    // controller.tokencard.eth\n    bytes32 private constant _DEFAULT_CONTROLLER_NODE = 0x7f2ce995617d2816b426c5c8698c5ec2952f7a34bb10f38326f74933d5893697;\n\n    /// @dev Is the registered ENS node identifying the controller contract.\n    bytes32 private _controllerNode = _DEFAULT_CONTROLLER_NODE;\n\n    /// @notice Constructor initializes the controller contract object.\n    /// @param _controllerNode_ is the ENS node of the Controller.\n    /// @dev pass in bytes32(0) to use the default, production node labels for ENS\n    constructor(bytes32 _controllerNode_) internal {\n        // Set controllerNode or use default\n        if (_controllerNode_ != bytes32(0)) {\n            _controllerNode = _controllerNode_;\n        }\n    }\n\n    /// @notice Checks if message sender is a controller.\n    modifier onlyController() {\n        require(_isController(msg.sender), \"sender is not a controller\");\n        _;\n    }\n\n    /// @notice Checks if message sender is an admin.\n    modifier onlyAdmin() {\n        require(_isAdmin(msg.sender), \"sender is not an admin\");\n        _;\n    }\n\n    /// @return the controller node registered in ENS.\n    function controllerNode() public view returns (bytes32) {\n        return _controllerNode;\n    }\n\n    /// @return true if the provided account is a controller.\n    function _isController(address _account) internal view returns (bool) {\n        return IController(_ensResolve(_controllerNode)).isController(_account);\n    }\n\n    /// @return true if the provided account is an admin.\n    function _isAdmin(address _account) internal view returns (bool) {\n        return IController(_ensResolve(_controllerNode)).isAdmin(_account);\n    }\n}\n"},"controller.sol":{"content":"/**\n *  Controller - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./ownable.sol\";\nimport \"./transferrable.sol\";\n\n\n/// @title The IController interface provides access to the isController and isAdmin checks.\ninterface IController {\n    function isController(address) external view returns (bool);\n\n    function isAdmin(address) external view returns (bool);\n}\n\n\n/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.\n/// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers.\n/// @dev Owner can change the Admins\n/// @dev Admins and can the Controllers\n/// @dev Controllers are used by the application.\ncontract Controller is IController, Ownable, Transferrable {\n    event AddedController(address _sender, address _controller);\n    event RemovedController(address _sender, address _controller);\n\n    event AddedAdmin(address _sender, address _admin);\n    event RemovedAdmin(address _sender, address _admin);\n\n    event Claimed(address _to, address _asset, uint256 _amount);\n\n    event Stopped(address _sender);\n    event Started(address _sender);\n\n    mapping(address =\u003e bool) private _isAdmin;\n    uint256 private _adminCount;\n\n    mapping(address =\u003e bool) private _isController;\n    uint256 private _controllerCount;\n\n    bool private _stopped;\n\n    /// @notice Constructor initializes the owner with the provided address.\n    /// @param _ownerAddress_ address of the owner.\n    constructor(address payable _ownerAddress_) public Ownable(_ownerAddress_, false) {}\n\n    /// @notice Checks if message sender is an admin.\n    modifier onlyAdmin() {\n        require(_isAdmin[msg.sender], \"sender is not an admin\");\n        _;\n    }\n\n    /// @notice Check if Owner or Admin\n    modifier onlyAdminOrOwner() {\n        require(_isOwner(msg.sender) || _isAdmin[msg.sender], \"sender is not an admin\");\n        _;\n    }\n\n    /// @notice Check if controller is stopped\n    modifier notStopped() {\n        require(!isStopped(), \"controller is stopped\");\n        _;\n    }\n\n    /// @notice Add a new admin to the list of admins.\n    /// @param _account address to add to the list of admins.\n    function addAdmin(address _account) external onlyOwner notStopped {\n        _addAdmin(_account);\n    }\n\n    /// @notice Remove a admin from the list of admins.\n    /// @param _account address to remove from the list of admins.\n    function removeAdmin(address _account) external onlyOwner {\n        _removeAdmin(_account);\n    }\n\n    /// @return the current number of admins.\n    function adminCount() external view returns (uint256) {\n        return _adminCount;\n    }\n\n    /// @notice Add a new controller to the list of controllers.\n    /// @param _account address to add to the list of controllers.\n    function addController(address _account) external onlyAdminOrOwner notStopped {\n        _addController(_account);\n    }\n\n    /// @notice Remove a controller from the list of controllers.\n    /// @param _account address to remove from the list of controllers.\n    function removeController(address _account) external onlyAdminOrOwner {\n        _removeController(_account);\n    }\n\n    /// @notice count the Controllers\n    /// @return the current number of controllers.\n    function controllerCount() external view returns (uint256) {\n        return _controllerCount;\n    }\n\n    /// @notice is an address an Admin?\n    /// @return true if the provided account is an admin.\n    function isAdmin(address _account) external view notStopped returns (bool) {\n        return _isAdmin[_account];\n    }\n\n    /// @notice is an address a Controller?\n    /// @return true if the provided account is a controller.\n    function isController(address _account) external view notStopped returns (bool) {\n        return _isController[_account];\n    }\n\n    /// @notice this function can be used to see if the controller has been stopped\n    /// @return true is the Controller has been stopped\n    function isStopped() public view returns (bool) {\n        return _stopped;\n    }\n\n    /// @notice Internal-only function that adds a new admin.\n    function _addAdmin(address _account) private {\n        require(!_isAdmin[_account], \"provided account is already an admin\");\n        require(!_isController[_account], \"provided account is already a controller\");\n        require(!_isOwner(_account), \"provided account is already the owner\");\n        require(_account != address(0), \"provided account is the zero address\");\n        _isAdmin[_account] = true;\n        _adminCount++;\n        emit AddedAdmin(msg.sender, _account);\n    }\n\n    /// @notice Internal-only function that removes an existing admin.\n    function _removeAdmin(address _account) private {\n        require(_isAdmin[_account], \"provided account is not an admin\");\n        _isAdmin[_account] = false;\n        _adminCount--;\n        emit RemovedAdmin(msg.sender, _account);\n    }\n\n    /// @notice Internal-only function that adds a new controller.\n    function _addController(address _account) private {\n        require(!_isAdmin[_account], \"provided account is already an admin\");\n        require(!_isController[_account], \"provided account is already a controller\");\n        require(!_isOwner(_account), \"provided account is already the owner\");\n        require(_account != address(0), \"provided account is the zero address\");\n        _isController[_account] = true;\n        _controllerCount++;\n        emit AddedController(msg.sender, _account);\n    }\n\n    /// @notice Internal-only function that removes an existing controller.\n    function _removeController(address _account) private {\n        require(_isController[_account], \"provided account is not a controller\");\n        _isController[_account] = false;\n        _controllerCount--;\n        emit RemovedController(msg.sender, _account);\n    }\n\n    /// @notice stop our controllers and admins from being useable\n    function stop() external onlyAdminOrOwner {\n        _stopped = true;\n        emit Stopped(msg.sender);\n    }\n\n    /// @notice start our controller again\n    function start() external onlyOwner {\n        _stopped = false;\n        emit Started(msg.sender);\n    }\n\n    //// @notice Withdraw tokens from the smart contract to the specified account.\n    function claim(address payable _to, address _asset, uint256 _amount) external onlyAdmin notStopped {\n        _safeTransfer(_to, _asset, _amount);\n        emit Claimed(_to, _asset, _amount);\n    }\n}\n"},"date.sol":{"content":"/**\n *  Date - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\n\n/// @title Date provides redimentary date parsing functionality.\n/// @notice This method parses months found in an ISO date to a number\ncontract Date {\n    bytes32 private constant _JANUARY = keccak256(\"Jan\");\n    bytes32 private constant _FEBRUARY = keccak256(\"Feb\");\n    bytes32 private constant _MARCH = keccak256(\"Mar\");\n    bytes32 private constant _APRIL = keccak256(\"Apr\");\n    bytes32 private constant _MAY = keccak256(\"May\");\n    bytes32 private constant _JUNE = keccak256(\"Jun\");\n    bytes32 private constant _JULY = keccak256(\"Jul\");\n    bytes32 private constant _AUGUST = keccak256(\"Aug\");\n    bytes32 private constant _SEPTEMBER = keccak256(\"Sep\");\n    bytes32 private constant _OCTOBER = keccak256(\"Oct\");\n    bytes32 private constant _NOVEMBER = keccak256(\"Nov\");\n    bytes32 private constant _DECEMBER = keccak256(\"Dec\");\n\n    /// @return the number of the month based on its name.\n    /// @param _month the first three letters of a month\u0027s name e.g. \"Jan\".\n    function _monthToNumber(string memory _month) internal pure returns (uint8) {\n        bytes32 month = keccak256(abi.encodePacked(_month));\n        if (month == _JANUARY) {\n            return 1;\n        } else if (month == _FEBRUARY) {\n            return 2;\n        } else if (month == _MARCH) {\n            return 3;\n        } else if (month == _APRIL) {\n            return 4;\n        } else if (month == _MAY) {\n            return 5;\n        } else if (month == _JUNE) {\n            return 6;\n        } else if (month == _JULY) {\n            return 7;\n        } else if (month == _AUGUST) {\n            return 8;\n        } else if (month == _SEPTEMBER) {\n            return 9;\n        } else if (month == _OCTOBER) {\n            return 10;\n        } else if (month == _NOVEMBER) {\n            return 11;\n        } else if (month == _DECEMBER) {\n            return 12;\n        } else {\n            revert(\"not a valid month\");\n        }\n    }\n}\n"},"DNSResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\nimport \"./RRUtils.sol\";\n\ncontract DNSResolver is ResolverBase {\n    using RRUtils for *;\n    using ENSBytesUtils for bytes;\n\n    bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682;\n    bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c;\n\n    // DNSRecordChanged is emitted whenever a given node/name/resource\u0027s RRSET is updated.\n    event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);\n    // DNSRecordDeleted is emitted whenever a given node/name/resource\u0027s RRSET is deleted.\n    event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource);\n    // DNSZoneCleared is emitted whenever a given node\u0027s zone information is cleared.\n    event DNSZoneCleared(bytes32 indexed node);\n\n    // DNSZonehashChanged is emitted whenever a given node\u0027s zone hash is updated.\n    event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash);\n\n    // Zone hashes for the domains.\n    // A zone hash is an EIP-1577 content hash in binary format that should point to a\n    // resource containing a single zonefile.\n    // node =\u003e contenthash\n    mapping(bytes32=\u003ebytes) private zonehashes;\n\n    // Version the mapping for each zone.  This allows users who have lost\n    // track of their entries to effectively delete an entire zone by bumping\n    // the version number.\n    // node =\u003e version\n    mapping(bytes32=\u003euint256) private versions;\n\n    // The records themselves.  Stored as binary RRSETs\n    // node =\u003e version =\u003e name =\u003e resource =\u003e data\n    mapping(bytes32=\u003emapping(uint256=\u003emapping(bytes32=\u003emapping(uint16=\u003ebytes)))) private records;\n\n    // Count of number of entries for a given name.  Required for DNS resolvers\n    // when resolving wildcards.\n    // node =\u003e version =\u003e name =\u003e number of records\n    mapping(bytes32=\u003emapping(uint256=\u003emapping(bytes32=\u003euint16))) private nameEntriesCount;\n\n    /**\n     * Set one or more DNS records.  Records are supplied in wire-format.\n     * Records with the same node/name/resource must be supplied one after the\n     * other to ensure the data is updated correctly. For example, if the data\n     * was supplied:\n     *     a.example.com IN A 1.2.3.4\n     *     a.example.com IN A 5.6.7.8\n     *     www.example.com IN CNAME a.example.com.\n     * then this would store the two A records for a.example.com correctly as a\n     * single RRSET, however if the data was supplied:\n     *     a.example.com IN A 1.2.3.4\n     *     www.example.com IN CNAME a.example.com.\n     *     a.example.com IN A 5.6.7.8\n     * then this would store the first A record, the CNAME, then the second A\n     * record which would overwrite the first.\n     *\n     * @param node the namehash of the node for which to set the records\n     * @param data the DNS wire format records to set\n     */\n    function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) {\n        uint16 resource = 0;\n        uint256 offset = 0;\n        bytes memory name;\n        bytes memory value;\n        bytes32 nameHash;\n        // Iterate over the data to add the resource records\n        for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {\n            if (resource == 0) {\n                resource = iter.dnstype;\n                name = iter.name();\n                nameHash = keccak256(abi.encodePacked(name));\n                value = bytes(iter.rdata());\n            } else {\n                bytes memory newName = iter.name();\n                if (resource != iter.dnstype || !name.equals(newName)) {\n                    setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0);\n                    resource = iter.dnstype;\n                    offset = iter.offset;\n                    name = newName;\n                    nameHash = keccak256(name);\n                    value = bytes(iter.rdata());\n                }\n            }\n        }\n        if (name.length \u003e 0) {\n            setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0);\n        }\n    }\n\n    /**\n     * Obtain a DNS record.\n     * @param node the namehash of the node for which to fetch the record\n     * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record\n     * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types\n     * @return the DNS record in wire format if present, otherwise empty\n     */\n    function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) {\n        return records[node][versions[node]][name][resource];\n    }\n\n    /**\n     * Check if a given node has records.\n     * @param node the namehash of the node for which to check the records\n     * @param name the namehash of the node for which to check the records\n     */\n    function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) {\n        return (nameEntriesCount[node][versions[node]][name] != 0);\n    }\n\n    /**\n     * Clear all information for a DNS zone.\n     * @param node the namehash of the node for which to clear the zone\n     */\n    function clearDNSZone(bytes32 node) public authorised(node) {\n        versions[node]++;\n        emit DNSZoneCleared(node);\n    }\n\n    /**\n     * setZonehash sets the hash for the zone.\n     * May only be called by the owner of that node in the ENS registry.\n     * @param node The node to update.\n     * @param hash The zonehash to set\n     */\n    function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) {\n        bytes memory oldhash = zonehashes[node];\n        zonehashes[node] = hash;\n        emit DNSZonehashChanged(node, oldhash, hash);\n    }\n\n    /**\n     * zonehash obtains the hash for the zone.\n     * @param node The ENS node to query.\n     * @return The associated contenthash.\n     */\n    function zonehash(bytes32 node) external view returns (bytes memory) {\n        return zonehashes[node];\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == DNS_RECORD_INTERFACE_ID ||\n               interfaceID == DNS_ZONE_INTERFACE_ID ||\n               super.supportsInterface(interfaceID);\n    }\n\n    function setDNSRRSet(\n        bytes32 node,\n        bytes memory name,\n        uint16 resource,\n        bytes memory data,\n        uint256 offset,\n        uint256 size,\n        bool deleteRecord) private\n    {\n        uint256 version = versions[node];\n        bytes32 nameHash = keccak256(name);\n        bytes memory rrData = data.substring(offset, size);\n        if (deleteRecord) {\n            if (records[node][version][nameHash][resource].length != 0) {\n                nameEntriesCount[node][version][nameHash]--;\n            }\n            delete(records[node][version][nameHash][resource]);\n            emit DNSRecordDeleted(node, name, resource);\n        } else {\n            if (records[node][version][nameHash][resource].length == 0) {\n                nameEntriesCount[node][version][nameHash]++;\n            }\n            records[node][version][nameHash][resource] = rrData;\n            emit DNSRecordChanged(node, name, resource, rrData);\n        }\n    }\n}"},"ECDSA.sol":{"content":"/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2019 zOS Global Limited\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\npragma solidity ^0.5.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * NOTE: This call _does not revert_ if the signature is invalid, or\n     * if the signer is otherwise unable to be retrieved. In those scenarios,\n     * the zero address is returned.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        // Check the signature length\n        if (signature.length != 65) {\n            return (address(0));\n        }\n\n        // Divide the signature in r, s and v variables\n        bytes32 r;\n        bytes32 s;\n        uint8 v;\n\n        // ecrecover takes the signature parameters, and the only way to get them\n        // currently is to use assembly.\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            r := mload(add(signature, 0x20))\n            s := mload(add(signature, 0x40))\n            v := byte(0, mload(add(signature, 0x60)))\n        }\n\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (281): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) \u003e 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return address(0);\n        }\n\n        if (v != 27 \u0026\u0026 v != 28) {\n            return address(0);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        return ecrecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * replicates the behavior of the\n     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n     * JSON-RPC method.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n    }\n}\n"},"ENS.sol":{"content":"/**\n * BSD 2-Clause License\n *\n * Copyright (c) 2018, True Names Limited\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\npragma solidity ^0.5.0;\n\ninterface ENS {\n\n    // Logged when the owner of a node assigns a new owner to a subnode.\n    event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);\n\n    // Logged when the owner of a node transfers ownership to a new account.\n    event Transfer(bytes32 indexed _node, address _owner);\n\n    // Logged when the resolver for a node changes.\n    event NewResolver(bytes32 indexed _node, address _resolver);\n\n    // Logged when the TTL of a node changes\n    event NewTTL(bytes32 indexed _node, uint64 _ttl);\n\n    // Logged when an operator is added or removed.\n    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);\n\n    function setRecord(bytes32 _node, address _owner, address _resolver, uint64 _ttl) external;\n    function setSubnodeRecord(bytes32 _node, bytes32 _label, address _owner, address _resolver, uint64 _ttl) external;\n    function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) external returns(bytes32);\n    function setResolver(bytes32 _node, address _resolver) external;\n    function setOwner(bytes32 _node, address _owner) external;\n    function setTTL(bytes32 _node, uint64 _ttl) external;\n    function setApprovalForAll(address _operator, bool _approved) external;\n    function owner(bytes32 _node) external view returns (address);\n    function resolver(bytes32 _node) external view returns (address);\n    function ttl(bytes32 _node) external view returns (uint64);\n    function recordExists(bytes32 _node) external view returns (bool);\n    function isApprovedForAll(address _owner, address _operator) external view returns (bool);\n}\n"},"ENSBytesUtils.sol":{"content":"pragma solidity \u003e0.4.23;\n\nlibrary ENSBytesUtils {\n    /*\n    * @dev Returns the keccak-256 hash of a byte range.\n    * @param self The byte string to hash.\n    * @param offset The position to start hashing at.\n    * @param len The number of bytes to hash.\n    * @return The hash of the byte range.\n    */\n    function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {\n        require(offset + len \u003c= self.length);\n        assembly {\n            ret := keccak256(add(add(self, 32), offset), len)\n        }\n    }\n\n    /*\n    * @dev Returns a positive number if `other` comes lexicographically after\n    *      `self`, a negative number if it comes before, or zero if the\n    *      contents of the two bytes are equal.\n    * @param self The first bytes to compare.\n    * @param other The second bytes to compare.\n    * @return The result of the comparison.\n    */\n    function compare(bytes memory self, bytes memory other) internal pure returns (int) {\n        return compare(self, 0, self.length, other, 0, other.length);\n    }\n\n    /*\n    * @dev Returns a positive number if `other` comes lexicographically after\n    *      `self`, a negative number if it comes before, or zero if the\n    *      contents of the two bytes are equal. Comparison is done per-rune,\n    *      on unicode codepoints.\n    * @param self The first bytes to compare.\n    * @param offset The offset of self.\n    * @param len    The length of self.\n    * @param other The second bytes to compare.\n    * @param otheroffset The offset of the other string.\n    * @param otherlen    The length of the other string.\n    * @return The result of the comparison.\n    */\n    function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {\n        uint shortest = len;\n        if (otherlen \u003c len)\n        shortest = otherlen;\n\n        uint selfptr;\n        uint otherptr;\n\n        assembly {\n            selfptr := add(self, add(offset, 32))\n            otherptr := add(other, add(otheroffset, 32))\n        }\n        for (uint idx = 0; idx \u003c shortest; idx += 32) {\n            uint a;\n            uint b;\n            assembly {\n                a := mload(selfptr)\n                b := mload(otherptr)\n            }\n            if (a != b) {\n                // Mask out irrelevant bytes and check again\n                uint mask;\n                if (shortest \u003e 32) {\n                    mask = uint256(- 1); // aka 0xffffff....\n                } else {\n                    mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\n                }\n                uint diff = (a \u0026 mask) - (b \u0026 mask);\n                if (diff != 0)\n                return int(diff);\n            }\n            selfptr += 32;\n            otherptr += 32;\n        }\n\n        return int(len) - int(otherlen);\n    }\n\n    /*\n    * @dev Returns true if the two byte ranges are equal.\n    * @param self The first byte range to compare.\n    * @param offset The offset into the first byte range.\n    * @param other The second byte range to compare.\n    * @param otherOffset The offset into the second byte range.\n    * @param len The number of bytes to compare\n    * @return True if the byte ranges are equal, false otherwise.\n    */\n    function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {\n        return keccak(self, offset, len) == keccak(other, otherOffset, len);\n    }\n\n    /*\n    * @dev Returns true if the two byte ranges are equal with offsets.\n    * @param self The first byte range to compare.\n    * @param offset The offset into the first byte range.\n    * @param other The second byte range to compare.\n    * @param otherOffset The offset into the second byte range.\n    * @return True if the byte ranges are equal, false otherwise.\n    */\n    function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {\n        return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);\n    }\n\n    /*\n    * @dev Compares a range of \u0027self\u0027 to all of \u0027other\u0027 and returns True iff\n    *      they are equal.\n    * @param self The first byte range to compare.\n    * @param offset The offset into the first byte range.\n    * @param other The second byte range to compare.\n    * @return True if the byte ranges are equal, false otherwise.\n    */\n    function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {\n        return self.length \u003e= offset + other.length \u0026\u0026 equals(self, offset, other, 0, other.length);\n    }\n\n    /*\n    * @dev Returns true if the two byte ranges are equal.\n    * @param self The first byte range to compare.\n    * @param other The second byte range to compare.\n    * @return True if the byte ranges are equal, false otherwise.\n    */\n    function equals(bytes memory self, bytes memory other) internal pure returns(bool) {\n        return self.length == other.length \u0026\u0026 equals(self, 0, other, 0, self.length);\n    }\n\n    /*\n    * @dev Returns the 8-bit number at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes\n    * @return The specified 8 bits of the string, interpreted as an integer.\n    */\n    function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {\n        return uint8(self[idx]);\n    }\n\n    /*\n    * @dev Returns the 16-bit number at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes\n    * @return The specified 16 bits of the string, interpreted as an integer.\n    */\n    function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {\n        require(idx + 2 \u003c= self.length);\n        assembly {\n            ret := and(mload(add(add(self, 2), idx)), 0xFFFF)\n        }\n    }\n\n    /*\n    * @dev Returns the 32-bit number at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes\n    * @return The specified 32 bits of the string, interpreted as an integer.\n    */\n    function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {\n        require(idx + 4 \u003c= self.length);\n        assembly {\n            ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)\n        }\n    }\n\n    /*\n    * @dev Returns the 32 byte value at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes\n    * @return The specified 32 bytes of the string.\n    */\n    function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {\n        require(idx + 32 \u003c= self.length);\n        assembly {\n            ret := mload(add(add(self, 32), idx))\n        }\n    }\n\n    /*\n    * @dev Returns the 32 byte value at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes\n    * @return The specified 32 bytes of the string.\n    */\n    function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {\n        require(idx + 20 \u003c= self.length);\n        assembly {\n            ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)\n        }\n    }\n\n    /*\n    * @dev Returns the n byte value at the specified index of self.\n    * @param self The byte string.\n    * @param idx The index into the bytes.\n    * @param len The number of bytes.\n    * @return The specified 32 bytes of the string.\n    */\n    function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) {\n        require(len \u003c= 32);\n        require(idx + len \u003c= self.length);\n        assembly {\n            let mask := not(sub(exp(256, sub(32, len)), 1))\n            ret := and(mload(add(add(self, 32), idx)),  mask)\n        }\n    }\n\n    function memcpy(uint dest, uint src, uint len) private pure {\n        // Copy word-length chunks while possible\n        for (; len \u003e= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        // Copy remaining bytes\n        uint mask = 256 ** (32 - len) - 1;\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n    }\n\n    /*\n    * @dev Copies a substring into a new byte string.\n    * @param self The byte string to copy from.\n    * @param offset The offset to start copying at.\n    * @param len The number of bytes to copy.\n    */\n    function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) {\n        require(offset + len \u003c= self.length);\n\n        bytes memory ret = new bytes(len);\n        uint dest;\n        uint src;\n\n        assembly {\n            dest := add(ret, 32)\n            src := add(add(self, 32), offset)\n        }\n        memcpy(dest, src, len);\n\n        return ret;\n    }\n\n    // Maps characters from 0x30 to 0x7A to their base32 values.\n    // 0xFF represents invalid characters in that range.\n    bytes constant base32HexTable = hex\u002700010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F\u0027;\n\n    /**\n     * @dev Decodes unpadded base32 data of up to one word in length.\n     * @param self The data to decode.\n     * @param off Offset into the string to start at.\n     * @param len Number of characters to decode.\n     * @return The decoded data, left aligned.\n     */\n    function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {\n        require(len \u003c= 52);\n\n        uint ret = 0;\n        uint8 decoded;\n        for(uint i = 0; i \u003c len; i++) {\n            bytes1 char = self[off + i];\n            require(char \u003e= 0x30 \u0026\u0026 char \u003c= 0x7A);\n            decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);\n            require(decoded \u003c= 0x20);\n            if(i == len - 1) {\n                break;\n            }\n            ret = (ret \u003c\u003c 5) | decoded;\n        }\n\n        uint bitlen = len * 5;\n        if(len % 8 == 0) {\n            // Multiple of 8 characters, no padding\n            ret = (ret \u003c\u003c 5) | decoded;\n        } else if(len % 8 == 2) {\n            // Two extra characters - 1 byte\n            ret = (ret \u003c\u003c 3) | (decoded \u003e\u003e 2);\n            bitlen -= 2;\n        } else if(len % 8 == 4) {\n            // Four extra characters - 2 bytes\n            ret = (ret \u003c\u003c 1) | (decoded \u003e\u003e 4);\n            bitlen -= 4;\n        } else if(len % 8 == 5) {\n            // Five extra characters - 3 bytes\n            ret = (ret \u003c\u003c 4) | (decoded \u003e\u003e 1);\n            bitlen -= 1;\n        } else if(len % 8 == 7) {\n            // Seven extra characters - 4 bytes\n            ret = (ret \u003c\u003c 2) | (decoded \u003e\u003e 3);\n            bitlen -= 3;\n        } else {\n            revert();\n        }\n\n        return bytes32(ret \u003c\u003c (256 - bitlen));\n    }\n}\n"},"ENSRegistry.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ENS.sol\";\n\n/**\n * The ENS registry contract.\n */\ncontract ENSRegistry is ENS {\n\n    struct Record {\n        address owner;\n        address resolver;\n        uint64 ttl;\n    }\n\n    mapping (bytes32 =\u003e Record) records;\n    mapping (address =\u003e mapping(address =\u003e bool)) operators;\n\n    // Permits modifications only by the owner of the specified node.\n    modifier authorised(bytes32 _node) {\n        address owner = records[_node].owner;\n        require(owner == msg.sender || operators[owner][msg.sender]);\n        _;\n    }\n\n    /**\n     * @dev Constructs a new ENS registrar.\n     */\n    constructor() public {\n        records[0x0].owner = msg.sender;\n    }\n\n    /**\n     * @dev Sets the record for a node.\n     * @param _node The node to update.\n     * @param _owner The address of the new owner.\n     * @param _resolver The address of the resolver.\n     * @param _ttl The TTL in seconds.\n     */\n    function setRecord(bytes32 _node, address _owner, address _resolver, uint64 _ttl) external {\n        setOwner(_node, _owner);\n        _setResolverAndTTL(_node, _resolver, _ttl);\n    }\n\n    /**\n     * @dev Sets the record for a subnode.\n     * @param _node The parent node.\n     * @param _label The hash of the label specifying the subnode.\n     * @param _owner The address of the new owner.\n     * @param _resolver The address of the resolver.\n     * @param _ttl The TTL in seconds.\n     */\n    function setSubnodeRecord(bytes32 _node, bytes32 _label, address _owner, address _resolver, uint64 _ttl) external {\n        bytes32 subnode = setSubnodeOwner(_node, _label, _owner);\n        _setResolverAndTTL(subnode, _resolver, _ttl);\n    }\n\n    /**\n     * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node.\n     * @param _node The node to transfer ownership of.\n     * @param _owner The address of the new owner.\n     */\n    function setOwner(bytes32 _node, address _owner) public authorised(_node) {\n        _setOwner(_node, _owner);\n        emit Transfer(_node, _owner);\n    }\n\n    /**\n     * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node.\n     * @param _node The parent node.\n     * @param _label The hash of the label specifying the subnode.\n     * @param _owner The address of the new owner.\n     */\n    function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) public authorised(_node) returns(bytes32) {\n        bytes32 subnode = keccak256(abi.encodePacked(_node, _label));\n        _setOwner(subnode, _owner);\n        emit NewOwner(_node, _label, _owner);\n        return subnode;\n    }\n\n    /**\n     * @dev Sets the resolver address for the specified node.\n     * @param _node The node to update.\n     * @param _resolver The address of the resolver.\n     */\n    function setResolver(bytes32 _node, address _resolver) public authorised(_node) {\n        emit NewResolver(_node, _resolver);\n        records[_node].resolver = _resolver;\n    }\n\n    /**\n     * @dev Sets the TTL for the specified node.\n     * @param _node The node to update.\n     * @param _ttl The TTL in seconds.\n     */\n    function setTTL(bytes32 _node, uint64 _ttl) public authorised(_node) {\n        emit NewTTL(_node, _ttl);\n        records[_node].ttl = _ttl;\n    }\n\n    /**\n     * @dev Enable or disable approval for a third party (\"operator\") to manage\n     *  all of `msg.sender`\u0027s ENS records. Emits the ApprovalForAll event.\n     * @param _operator Address to add to the set of authorized operators.\n     * @param _approved True if the operator is approved, false to revoke approval.\n     */\n    function setApprovalForAll(address _operator, bool _approved) external {\n        operators[msg.sender][_operator] = _approved;\n        emit ApprovalForAll(msg.sender, _operator, _approved);\n    }\n\n    /**\n     * @dev Returns the address that owns the specified node.\n     * @param _node The specified node.\n     * @return address of the owner.\n     */\n    function owner(bytes32 _node) public view returns (address) {\n        address addr = records[_node].owner;\n        if (addr == address(this)) {\n            return address(0x0);\n        }\n\n        return addr;\n    }\n\n    /**\n     * @dev Returns the address of the resolver for the specified node.\n     * @param _node The specified node.\n     * @return address of the resolver.\n     */\n    function resolver(bytes32 _node) public view returns (address) {\n        return records[_node].resolver;\n    }\n\n    /**\n     * @dev Returns the TTL of a node, and any records associated with it.\n     * @param _node The specified node.\n     * @return ttl of the node.\n     */\n    function ttl(bytes32 _node) public view returns (uint64) {\n        return records[_node].ttl;\n    }\n\n    /**\n     * @dev Returns whether a record has been imported to the registry.\n     * @param _node The specified node.\n     * @return Bool if record exists\n     */\n    function recordExists(bytes32 _node) public view returns (bool) {\n        return records[_node].owner != address(0x0);\n    }\n\n    /**\n     * @dev Query if an address is an authorized operator for another address.\n     * @param _owner The address that owns the records.\n     * @param _operator The address that acts on behalf of the owner.\n     * @return True if `operator` is an approved operator for `owner`, false otherwise.\n     */\n    function isApprovedForAll(address _owner, address _operator) external view returns (bool) {\n        return operators[_owner][_operator];\n    }\n\n    function _setOwner(bytes32 _node, address _owner) internal {\n        records[_node].owner = _owner;\n    }\n\n    function _setResolverAndTTL(bytes32 _node, address _resolver, uint64 _ttl) internal {\n        if(_resolver != records[_node].resolver) {\n            records[_node].resolver = _resolver;\n            emit NewResolver(_node, _resolver);\n        }\n\n        if(_ttl != records[_node].ttl) {\n            records[_node].ttl = _ttl;\n            emit NewTTL(_node, _ttl);\n        }\n    }\n}\n"},"ensResolvable.sol":{"content":"/**\n *  ENSResolvable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./ENS.sol\";\nimport \"./PublicResolver.sol\";\n\n\n///@title ENSResolvable - Ethereum Name Service Resolver\n///@notice contract should be used to get an address for an ENS node\ncontract ENSResolvable {\n    /// @notice _ensRegistry points to the ENS registry smart contract.\n    address private _ensRegistry;\n\n    /// @param _ensReg_ is the ENS registry used\n    constructor(address _ensReg_) internal {\n        _ensRegistry = _ensReg_;\n    }\n\n    /// @notice this is used to that one can observe which ENS registry is being used\n    function ensRegistry() external view returns (address) {\n        return _ensRegistry;\n    }\n\n    /// @notice helper function used to get the address of a node\n    /// @param _node of the ENS entry that needs resolving\n    /// @return the address of the said node\n    function _ensResolve(bytes32 _node) internal view returns (address) {\n        return PublicResolver(ENS(_ensRegistry).resolver(_node)).addr(_node);\n    }\n}\n"},"ERC165.sol":{"content":"pragma solidity ^0.5.15;\n\n/// @title ERC165 interface specifies a standard way of querying if a contract implements an interface.\ninterface ERC165 {\n    function supportsInterface(bytes4) external view returns (bool);\n}\n"},"ERC20.sol":{"content":"pragma solidity ^0.5.15;\n\n/// @title ERC20 interface is a subset of the ERC20 specification.\n/// @notice see https://github.com/ethereum/EIPs/issues/20\ninterface ERC20 {\n    function allowance(address _owner, address _spender) external view returns (uint256);\n    function approve(address _spender, uint256 _value) external returns (bool);\n    function balanceOf(address _who) external view returns (uint256);\n    function totalSupply() external view returns (uint256);\n    function transfer(address _to, uint256 _value) external returns (bool);\n    function transferFrom(address _from, address _to, uint256 _value) external returns (bool);\n}\n"},"holder.sol":{"content":"/**\n *  Holder (aka Asset Contract) - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./transferrable.sol\";\nimport \"./balanceable.sol\";\nimport \"./burner.sol\";\nimport \"./controllable.sol\";\nimport \"./tokenWhitelistable.sol\";\n\n\n/// @title Holder - The TKN Asset Contract\n/// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner.\ncontract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable {\n    using SafeMath for uint256;\n\n    event Received(address _from, uint256 _amount);\n    event CashAndBurned(address _to, address _asset, uint256 _amount);\n    event Claimed(address _to, address _asset, uint256 _amount);\n\n    /// @dev Check if the sender is the burner contract\n    modifier onlyBurner() {\n        require(msg.sender == _burner, \"burner contract is not the sender\");\n        _;\n    }\n\n    // Burner token which can be burned to redeem shares.\n    address private _burner;\n\n    /// @notice Constructor initializes the holder contract.\n    /// @param _burnerContract_ is the address of the token contract TKN with burning functionality.\n    /// @param _ens_ is the address of the ENS registry.\n    /// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist.\n    /// @param _controllerNode_ is the ENS node of the Controller\n    constructor(address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_)\n        public\n        ENSResolvable(_ens_)\n        Controllable(_controllerNode_)\n        TokenWhitelistable(_tokenWhitelistNode_)\n    {\n        _burner = _burnerContract_;\n    }\n\n    /// @notice Ether may be sent from anywhere.\n    function() external payable {\n        emit Received(msg.sender, msg.value);\n    }\n\n    /// @notice Burn handles disbursing a share of tokens in this contract to a given address.\n    /// @param _to The address to disburse to\n    /// @param _amount The amount of TKN that will be burned if this succeeds\n    function burn(address payable _to, uint256 _amount) external onlyBurner returns (bool) {\n        if (_amount == 0) {\n            return true;\n        }\n        // The burner token deducts from the supply before calling.\n        uint256 supply = IBurner(_burner).currentSupply().add(_amount);\n        address[] memory redeemableAddresses = _redeemableTokens();\n        for (uint256 i = 0; i \u003c redeemableAddresses.length; i++) {\n            uint256 redeemableBalance = _balance(address(this), redeemableAddresses[i]);\n            if (redeemableBalance \u003e 0) {\n                uint256 redeemableAmount = redeemableBalance.mul(_amount).div(supply);\n                _safeTransfer(_to, redeemableAddresses[i], redeemableAmount);\n                emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount);\n            }\n        }\n\n        return true;\n    }\n\n    /// @notice This allows for the admin to reclaim the non-redeemableTokens.\n    /// @param _to this is the address which the reclaimed tokens will be sent to.\n    /// @param _nonRedeemableAddresses this is the array of tokens to be claimed.\n    function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {\n        for (uint256 i = 0; i \u003c _nonRedeemableAddresses.length; i++) {\n            //revert if token is redeemable\n            require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), \"redeemables cannot be claimed\");\n            uint256 claimBalance = _balance(address(this), _nonRedeemableAddresses[i]);\n            if (claimBalance \u003e 0) {\n                _safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);\n                emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);\n            }\n        }\n\n        return true;\n    }\n\n    /// @notice Returned the address of the burner contract.\n    /// @return the TKN address.\n    function burner() external view returns (address) {\n        return _burner;\n    }\n}\n"},"InterfaceResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\nimport \"./AddrResolver.sol\";\n\ncontract InterfaceResolver is ResolverBase, AddrResolver {\n    bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256(\"interfaceImplementer(bytes32,bytes4)\"));\n    bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;\n\n    event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);\n\n    mapping(bytes32=\u003emapping(bytes4=\u003eaddress)) interfaces;\n\n    /**\n     * Sets an interface associated with a name.\n     * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.\n     * @param node The node to update.\n     * @param interfaceID The EIP 168 interface ID.\n     * @param implementer The address of a contract that implements this interface for this node.\n     */\n    function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {\n        interfaces[node][interfaceID] = implementer;\n        emit InterfaceChanged(node, interfaceID, implementer);\n    }\n\n    /**\n     * Returns the address of a contract that implements the specified interface for this name.\n     * If an implementer has not been set for this interfaceID and name, the resolver will query\n     * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that\n     * contract implements EIP168 and returns `true` for the specified interfaceID, its address\n     * will be returned.\n     * @param node The ENS node to query.\n     * @param interfaceID The EIP 168 interface ID to check for.\n     * @return The address that implements this interface, or 0 if the interface is unsupported.\n     */\n    function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {\n        address implementer = interfaces[node][interfaceID];\n        if(implementer != address(0)) {\n            return implementer;\n        }\n\n        address a = addr(node);\n        if(a == address(0)) {\n            return address(0);\n        }\n\n        (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature(\"supportsInterface(bytes4)\", INTERFACE_META_ID));\n        if(!success || returnData.length \u003c 32 || returnData[31] == 0) {\n            // EIP 168 not supported by target\n            return address(0);\n        }\n\n        (success, returnData) = a.staticcall(abi.encodeWithSignature(\"supportsInterface(bytes4)\", interfaceID));\n        if(!success || returnData.length \u003c 32 || returnData[31] == 0) {\n            // Specified interface not supported by target\n            return address(0);\n        }\n\n        return a;\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}\n"},"isValidSignatureExporter.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./wallet.sol\";\n\n\ninterface IWallet {\n    function isValidSignature(bytes calldata, bytes calldata) external view returns (bytes4);\n}\n\n\ncontract IsValidSignatureExporter {\n    address walletAddress;\n\n    constructor(address _wallet) public {\n        walletAddress = _wallet;\n    }\n\n    /// @dev exports isValidSignature(bytes,bytes) aka EIP-1271, so it can tested (no overloading in Go)\n    function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {\n        return IWallet(walletAddress).isValidSignature(_data, _signature);\n    }\n}\n"},"licence.sol":{"content":"/**\n *  Licence - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\nimport \"./SafeERC20.sol\";\nimport \"./controllable.sol\";\nimport \"./ensResolvable.sol\";\nimport \"./transferrable.sol\";\n\n\n/// @title ILicence interface describes methods for loading a TokenCard and updating licence amount.\ninterface ILicence {\n    function load(address, uint256) external payable;\n\n    function updateLicenceAmount(uint256) external;\n}\n\n\n/// @title Licence loads the TokenCard and transfers the licence amout to the TKN Holder Contract.\n/// @notice the rest of the amount gets sent to the CryptoFloat\ncontract Licence is Transferrable, ENSResolvable, Controllable {\n    using SafeMath for uint256;\n    using SafeERC20 for ERC20;\n\n    /*******************/\n    /*     Events     */\n    /*****************/\n\n    event UpdatedLicenceDAO(address _newDAO);\n    event UpdatedCryptoFloat(address _newFloat);\n    event UpdatedTokenHolder(address _newHolder);\n    event UpdatedTKNContractAddress(address _newTKN);\n    event UpdatedLicenceAmount(uint256 _newAmount);\n\n    event TransferredToTokenHolder(address _from, address _to, address _asset, uint256 _amount);\n    event TransferredToCryptoFloat(address _from, address _to, address _asset, uint256 _amount);\n\n    event Claimed(address _to, address _asset, uint256 _amount);\n\n    /// @notice This is 100% scaled up by a factor of 10 to give us an extra 1 decimal place of precision\n    uint256 public constant MAX_AMOUNT_SCALE = 1000;\n    uint256 public constant MIN_AMOUNT_SCALE = 1;\n\n    address private _tknContractAddress = 0xaAAf91D9b90dF800Df4F55c205fd6989c977E73a; // solium-disable-line uppercase\n\n    address payable private _cryptoFloat;\n    address payable private _tokenHolder;\n    address private _licenceDAO;\n\n    bool private _lockedCryptoFloat;\n    bool private _lockedTokenHolder;\n    bool private _lockedLicenceDAO;\n    bool private _lockedTKNContractAddress;\n\n    /// @notice This is the _licenceAmountScaled by a factor of 10\n    /// @dev i.e. 1% is 10 _licenceAmountScaled, 0.1% is 1 _licenceAmountScaled\n    uint256 private _licenceAmountScaled;\n\n    /// @notice Reverts if called by any address other than the DAO contract.\n    modifier onlyDAO() {\n        require(msg.sender == _licenceDAO, \"the sender isn\u0027t the DAO\");\n        _;\n    }\n\n    /// @notice Constructor initializes the card licence contract.\n    /// @param _licence_ is the initial card licence amount. this number is scaled 10 = 1%, 9 = 0.9%\n    /// @param _float_ is the address of the multi-sig cryptocurrency float contract.\n    /// @param _holder_ is the address of the token holder contract\n    /// @param _tknAddress_ is the address of the TKN ERC20 contract\n    /// @param _ens_ is the address of the ENS Registry\n    /// @param _controllerNode_ is the ENS node corresponding to the controller\n    constructor(uint256 _licence_, address payable _float_, address payable _holder_, address _tknAddress_, address _ens_, bytes32 _controllerNode_)\n        public\n        ENSResolvable(_ens_)\n        Controllable(_controllerNode_)\n    {\n        require(MIN_AMOUNT_SCALE \u003c= _licence_ \u0026\u0026 _licence_ \u003c= MAX_AMOUNT_SCALE, \"licence amount out of range\");\n        _licenceAmountScaled = _licence_;\n        _cryptoFloat = _float_;\n        _tokenHolder = _holder_;\n        if (_tknAddress_ != address(0)) {\n            _tknContractAddress = _tknAddress_;\n        }\n    }\n\n    /// @notice Ether can be deposited from any source, so this contract should be payable by anyone.\n    function() external payable {}\n\n    /// @notice this allows for people to see the scaled licence amount\n    /// @return the scaled licence amount, used to calculate the split when loading.\n    function licenceAmountScaled() external view returns (uint256) {\n        return _licenceAmountScaled;\n    }\n\n    /// @notice allows one to see the address of the CryptoFloat\n    /// @return the address of the multi-sig cryptocurrency float contract.\n    function cryptoFloat() external view returns (address) {\n        return _cryptoFloat;\n    }\n\n    /// @notice allows one to see the address TKN holder contract\n    /// @return the address of the token holder contract.\n    function tokenHolder() external view returns (address) {\n        return _tokenHolder;\n    }\n\n    /// @notice allows one to see the address of the DAO\n    /// @return the address of the DAO contract.\n    function licenceDAO() external view returns (address) {\n        return _licenceDAO;\n    }\n\n    /// @notice The address of the TKN token\n    /// @return the address of the TKN contract.\n    function tknContractAddress() external view returns (address) {\n        return _tknContractAddress;\n    }\n\n    /// @notice This locks the cryptoFloat address\n    /// @dev so that it can no longer be updated\n    function lockFloat() external onlyAdmin {\n        _lockedCryptoFloat = true;\n    }\n\n    /// @notice This locks the TokenHolder address\n    /// @dev so that it can no longer be updated\n    function lockHolder() external onlyAdmin {\n        _lockedTokenHolder = true;\n    }\n\n    /// @notice This locks the DAO address\n    /// @dev so that it can no longer be updated\n    function lockLicenceDAO() external onlyAdmin {\n        _lockedLicenceDAO = true;\n    }\n\n    /// @notice This locks the TKN address\n    /// @dev so that it can no longer be updated\n    function lockTKNContractAddress() external onlyAdmin {\n        _lockedTKNContractAddress = true;\n    }\n\n    /// @notice Updates the address of the cyptoFloat.\n    /// @param _newFloat This is the new address for the CryptoFloat\n    function updateFloat(address payable _newFloat) external onlyAdmin {\n        require(!floatLocked(), \"float is locked\");\n        _cryptoFloat = _newFloat;\n        emit UpdatedCryptoFloat(_newFloat);\n    }\n\n    /// @notice Updates the address of the Holder contract.\n    /// @param _newHolder This is the new address for the TokenHolder\n    function updateHolder(address payable _newHolder) external onlyAdmin {\n        require(!holderLocked(), \"holder contract is locked\");\n        _tokenHolder = _newHolder;\n        emit UpdatedTokenHolder(_newHolder);\n    }\n\n    /// @notice Updates the address of the DAO contract.\n    /// @param _newDAO This is the new address for the Licence DAO\n    function updateLicenceDAO(address _newDAO) external onlyAdmin {\n        require(!licenceDAOLocked(), \"DAO is locked\");\n        _licenceDAO = _newDAO;\n        emit UpdatedLicenceDAO(_newDAO);\n    }\n\n    /// @notice Updates the address of the TKN contract.\n    /// @param _newTKN This is the new address for the TKN contract\n    function updateTKNContractAddress(address _newTKN) external onlyAdmin {\n        require(!tknContractAddressLocked(), \"TKN is locked\");\n        _tknContractAddress = _newTKN;\n        emit UpdatedTKNContractAddress(_newTKN);\n    }\n\n    /// @notice Updates the TKN licence amount\n    /// @param _newAmount is a number between MIN_AMOUNT_SCALE (1) and MAX_AMOUNT_SCALE\n    function updateLicenceAmount(uint256 _newAmount) external onlyDAO {\n        require(MIN_AMOUNT_SCALE \u003c= _newAmount \u0026\u0026 _newAmount \u003c= MAX_AMOUNT_SCALE, \"licence amount out of range\");\n        _licenceAmountScaled = _newAmount;\n        emit UpdatedLicenceAmount(_newAmount);\n    }\n\n    /// @notice Load the holder and float contracts based on the licence amount and asset amount.\n    /// @param _asset is the address of an ERC20 token or 0x0 for ether.\n    /// @param _amount is the amount of assets to be transferred including the licence amount.\n    function load(address _asset, uint256 _amount) external payable {\n        uint256 loadAmount = _amount;\n        // If TKN then no licence to be paid\n        if (_asset == _tknContractAddress) {\n            ERC20(_asset).safeTransferFrom(msg.sender, _cryptoFloat, loadAmount);\n        } else {\n            loadAmount = _amount.mul(MAX_AMOUNT_SCALE).div(_licenceAmountScaled + MAX_AMOUNT_SCALE);\n            uint256 licenceAmount = _amount.sub(loadAmount);\n\n            if (_asset != address(0)) {\n                ERC20(_asset).safeTransferFrom(msg.sender, _tokenHolder, licenceAmount);\n                ERC20(_asset).safeTransferFrom(msg.sender, _cryptoFloat, loadAmount);\n            } else {\n                require(msg.value == _amount, \"ETH sent is not equal to amount\");\n                _tokenHolder.transfer(licenceAmount);\n                _cryptoFloat.transfer(loadAmount);\n            }\n\n            emit TransferredToTokenHolder(msg.sender, _tokenHolder, _asset, licenceAmount);\n        }\n\n        emit TransferredToCryptoFloat(msg.sender, _cryptoFloat, _asset, loadAmount);\n    }\n\n    //// @notice Withdraw tokens from the smart contract to the specified account.\n    function claim(address payable _to, address _asset, uint256 _amount) external onlyAdmin {\n        _safeTransfer(_to, _asset, _amount);\n        emit Claimed(_to, _asset, _amount);\n    }\n\n    /// @notice returns whether or not the CryptoFloat address is locked\n    function floatLocked() public view returns (bool) {\n        return _lockedCryptoFloat;\n    }\n\n    /// @notice returns whether or not the TokenHolder address is locked\n    function holderLocked() public view returns (bool) {\n        return _lockedTokenHolder;\n    }\n\n    /// @notice returns whether or not the Licence DAO address is locked\n    function licenceDAOLocked() public view returns (bool) {\n        return _lockedLicenceDAO;\n    }\n\n    /// @notice returns whether or not the TKN address is locked\n    function tknContractAddressLocked() public view returns (bool) {\n        return _lockedTKNContractAddress;\n    }\n}\n"},"Migrations.sol":{"content":"pragma solidity \u003e=0.4.21 \u003c0.7.0;\n\ncontract Migrations {\n  address public owner;\n  uint public last_completed_migration;\n\n  constructor() public {\n    owner = msg.sender;\n  }\n\n  modifier restricted() {\n    if (msg.sender == owner) _;\n  }\n\n  function setCompleted(uint completed) public restricted {\n    last_completed_migration = completed;\n  }\n}\n"},"NameResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract NameResolver is ResolverBase {\n    bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;\n\n    event NameChanged(bytes32 indexed node, string name);\n\n    mapping(bytes32=\u003estring) names;\n\n    /**\n     * Sets the name associated with an ENS node, for reverse records.\n     * May only be called by the owner of that node in the ENS registry.\n     * @param node The node to update.\n     * @param name The name to set.\n     */\n    function setName(bytes32 node, string calldata name) external authorised(node) {\n        names[node] = name;\n        emit NameChanged(node, name);\n    }\n\n    /**\n     * Returns the name associated with an ENS node, for reverse records.\n     * Defined in EIP181.\n     * @param node The ENS node to query.\n     * @return The associated name.\n     */\n    function name(bytes32 node) external view returns (string memory) {\n        return names[node];\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}\n"},"nonCompliantToken.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\n\n\n/// @title NonCompliantToken is a mock ERC20 token that is not compatible with the ERC20 interface.\ncontract NonCompliantToken {\n    using SafeMath for uint256;\n\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n    /// @dev Total supply of tokens in circulation.\n    uint256 public totalSupply;\n\n    /// @dev Balances for each account.\n    mapping(address =\u003e uint256) public balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint256)) public allowance;\n\n    /// @dev Transfer a token. This throws on insufficient balance.\n    function transfer(address to, uint256 amount) public {\n        require(balanceOf[msg.sender] \u003e= amount, \"insufficient balance\");\n        balanceOf[msg.sender] -= amount;\n        balanceOf[to] += amount;\n        emit Transfer(msg.sender, to, amount);\n    }\n\n    function transferFrom(address _from, address _to, uint256 _value) public {\n        if (_to == address(0)) revert();\n        if (balanceOf[_from] \u003c _value) revert();\n\n        uint256 allowed = allowance[_from][msg.sender];\n        if (allowed \u003c _value) revert();\n\n        balanceOf[_to] = SafeMath.add(balanceOf[_to], _value);\n        balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value);\n        allowance[_from][msg.sender] = SafeMath.sub(allowed, _value);\n        emit Transfer(_from, _to, _value);\n    }\n\n    function approve(address _spender, uint256 _value) public {\n        //require user to set to zero before resetting to nonzero\n        if ((_value != 0) \u0026\u0026 (allowance[msg.sender][_spender] != 0)) {\n            revert();\n        }\n\n        allowance[msg.sender][_spender] = _value;\n        emit Approval(msg.sender, _spender, _value);\n    }\n\n    /// @dev Credit an address.\n    function credit(address to, uint256 amount) public returns (bool) {\n        balanceOf[to] += amount;\n        totalSupply += amount;\n        return true;\n    }\n\n    /// @dev Debit an address.\n    function debit(address from, uint256 amount) public {\n        balanceOf[from] -= amount;\n        totalSupply -= amount;\n    }\n}\n"},"oracle.sol":{"content":"/**\n *  Oracle - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./controllable.sol\";\nimport \"./transferrable.sol\";\nimport \"./ensResolvable.sol\";\nimport \"./date.sol\";\nimport \"./parseIntScientific.sol\";\nimport \"./tokenWhitelistable.sol\";\nimport \"./SafeMath.sol\";\nimport \"./oraclizeAPI_0.5.sol\";\nimport \"./base64.sol\";\n\n\n/// @title Oracle provides asset exchange rates and conversion functionality.\ncontract Oracle is ENSResolvable, usingOraclize, Transferrable, Base64, Date, Controllable, ParseIntScientific, TokenWhitelistable {\n    using strings for *;\n    using SafeMath for uint256;\n\n    /*******************/\n    /*     Events     */\n    /*****************/\n\n    event SetGasPrice(address _sender, uint256 _gasPrice);\n\n    event RequestedUpdate(string _symbol, bytes32 _queryID);\n    event FailedUpdateRequest(string _reason);\n\n    event VerifiedProof(bytes _publicKey, string _result);\n\n    event SetCryptoComparePublicKey(address _sender, bytes _publicKey);\n\n    event Claimed(address _to, address _asset, uint256 _amount);\n\n    /**********************/\n    /*     Constants     */\n    /********************/\n\n    uint256 private constant _PROOF_LEN = 165;\n    uint256 private constant _ECDSA_SIG_LEN = 65;\n    uint256 private constant _ENCODING_BYTES = 2;\n    uint256 private constant _HEADERS_LEN = _PROOF_LEN - 2 * _ENCODING_BYTES - _ECDSA_SIG_LEN; // 2 bytes encoding headers length + 2 for signature.\n    uint256 private constant _DIGEST_BASE64_LEN = 44; //base64 encoding of the SHA256 hash (32-bytes) of the result: fixed length.\n    uint256 private constant _DIGEST_OFFSET = _HEADERS_LEN - _DIGEST_BASE64_LEN; // the starting position of the result hash in the headers string.\n\n    uint256 private constant _MAX_BYTE_SIZE = 256; //for calculating length encoding\n\n    // This is how the cryptocompare json begins\n    bytes32 private constant _PREFIX_HASH = keccak256(\u0027{\"ETH\":\u0027);\n\n    bytes public cryptoCompareAPIPublicKey;\n    mapping(bytes32 =\u003e address) private _queryToToken;\n\n    /// @notice Construct the oracle with multiple controllers, address resolver and custom gas price.\n    /// @param _resolver_ is the address of the oraclize resolver\n    /// @param _ens_ is the address of the ENS.\n    /// @param _controllerNode_ is the ENS node corresponding to the Controller.\n    /// @param _tokenWhitelistNode_ is the ENS corresponding to the Token Whitelist.\n    constructor(address _resolver_, address _ens_, bytes32 _controllerNode_, bytes32 _tokenWhitelistNode_)\n        public\n        ENSResolvable(_ens_)\n        Controllable(_controllerNode_)\n        TokenWhitelistable(_tokenWhitelistNode_)\n    {\n        cryptoCompareAPIPublicKey = hex\"a0f4f688350018ad1b9785991c0bde5f704b005dc79972b114dbed4a615a983710bfc647ebe5a320daa28771dce6a2d104f5efa2e4a85ba3760b76d46f8571ca\";\n        OAR = OraclizeAddrResolverI(_resolver_);\n        oraclize_setCustomGasPrice(10000000000);\n        oraclize_setProof(proofType_Native);\n    }\n\n    /// @notice Updates the Crypto Compare public API key.\n    /// @param _publicKey new Crypto Compare public API key\n    function updateCryptoCompareAPIPublicKey(bytes calldata _publicKey) external onlyAdmin {\n        cryptoCompareAPIPublicKey = _publicKey;\n        emit SetCryptoComparePublicKey(msg.sender, _publicKey);\n    }\n\n    /// @notice Sets the gas price used by Oraclize query.\n    /// @param _gasPrice in wei for Oraclize\n    function setCustomGasPrice(uint256 _gasPrice) external onlyController {\n        oraclize_setCustomGasPrice(_gasPrice);\n        emit SetGasPrice(msg.sender, _gasPrice);\n    }\n\n    /// @notice Update ERC20 token exchange rates for all supported tokens.\n    /// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback\n    function updateTokenRates(uint256 _gasLimit) external payable onlyController {\n        _updateTokenRates(_gasLimit);\n    }\n\n    /// @notice Update ERC20 token exchange rates for the list of tokens provided.\n    /// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback\n    /// @param _tokenList the list of tokens that need to be updated\n    function updateTokenRatesList(uint256 _gasLimit, address[] calldata _tokenList) external payable onlyController {\n        _updateTokenRatesList(_gasLimit, _tokenList);\n    }\n\n    /// @notice Withdraw tokens from the smart contract to the specified account.\n    function claim(address payable _to, address _asset, uint256 _amount) external onlyAdmin {\n        _safeTransfer(_to, _asset, _amount);\n        emit Claimed(_to, _asset, _amount);\n    }\n\n    /// @notice Handle Oraclize query callback and verifiy the provided origin proof.\n    /// @param _queryID Oraclize query ID.\n    /// @param _result query result in JSON format.\n    /// @param _proof origin proof from crypto compare.\n    // solium-disable-next-line mixedcase\n    function __callback(bytes32 _queryID, string memory _result, bytes memory _proof) public {\n        // Require that the caller is the Oraclize contract.\n        require(msg.sender == oraclize_cbAddress(), \"sender is not oraclize\");\n        // Use the query ID to find the matching token address.\n        address token = _queryToToken[_queryID];\n        // Get the corresponding token object.\n        (, , , bool available, , , uint256 lastUpdate) = _getTokenInfo(token);\n        require(available, \"token must be available\");\n\n        bool valid;\n        uint256 timestamp;\n        (valid, timestamp) = _verifyProof(_result, _proof, cryptoCompareAPIPublicKey, lastUpdate);\n\n        // Require that the proof is valid.\n        if (valid) {\n            // Parse the JSON result to get the rate in wei.\n            uint256 parsedRate = _parseIntScientificWei(parseRate(_result));\n            // Set the update time of the token rate.\n            uint256 parsedLastUpdate = timestamp;\n            // Remove query from the list.\n            delete _queryToToken[_queryID];\n\n            _updateTokenRate(token, parsedRate, parsedLastUpdate);\n        }\n    }\n\n    /// @notice Extracts JSON rate value from the response object.\n    /// @param _json body of the JSON response from the CryptoCompare API.\n    function parseRate(string memory _json) internal pure returns (string memory) {\n        uint256 jsonLen = abi.encodePacked(_json).length;\n        //{\"ETH\":}.length = 8, assuming a (maximum of) 18 digit prevision\n        require(jsonLen \u003e 8 \u0026\u0026 jsonLen \u003c= 28, \"misformatted input\");\n\n        bytes memory jsonPrefix = new bytes(7);\n        copyBytes(abi.encodePacked(_json), 0, 7, jsonPrefix, 0);\n        require(keccak256(jsonPrefix) == _PREFIX_HASH, \"prefix mismatch\");\n\n        strings.slice memory body = _json.toSlice();\n        body.split(\":\".toSlice());\n        //we are sure that \u0027:\u0027 is included in the string, body now contains the rate+\u0027}\u0027\n        jsonLen = body._len;\n        body.until(\"}\".toSlice());\n        require(body._len == jsonLen - 1, \"not json format\");\n        //ensure that the json is properly terminated with a \u0027}\u0027\n        return body.toString();\n    }\n\n    /// @notice Re-usable helper function that performs the Oraclize Query.\n    /// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback\n    function _updateTokenRates(uint256 _gasLimit) private {\n        address[] memory tokenAddresses = _tokenAddressArray();\n        // Check if there are any existing tokens.\n        if (tokenAddresses.length == 0) {\n            // Emit a query failure event.\n            emit FailedUpdateRequest(\"no tokens\");\n            // Check if the contract has enough Ether to pay for the query.\n        } else if (oraclize_getPrice(\"URL\") * tokenAddresses.length \u003e address(this).balance) {\n            // Emit a query failure event.\n            emit FailedUpdateRequest(\"insufficient balance\");\n        } else {\n            // Set up the cryptocompare API query strings.\n            strings.slice memory apiPrefix = \"https://min-api.cryptocompare.com/data/price?fsym=\".toSlice();\n            strings.slice memory apiSuffix = \"\u0026tsyms=ETH\u0026sign=true\".toSlice();\n\n            // Create a new oraclize query for each supported token.\n            for (uint256 i = 0; i \u003c tokenAddresses.length; i++) {\n                // Store the token symbol used in the query.\n                (string memory symbol, , , , , , ) = _getTokenInfo(tokenAddresses[i]);\n\n                strings.slice memory sym = symbol.toSlice();\n                // Create a new oraclize query from the component strings.\n                bytes32 queryID = oraclize_query(\"URL\", apiPrefix.concat(sym).toSlice().concat(apiSuffix), _gasLimit);\n                // Store the query ID together with the associated token address.\n                _queryToToken[queryID] = tokenAddresses[i];\n                // Emit the query success event.\n                emit RequestedUpdate(sym.toString(), queryID);\n            }\n        }\n    }\n\n    /// @notice Re-usable helper function that performs the Oraclize Query for a specific list of tokens.\n    /// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback.\n    /// @param _tokenList the list of tokens that need to be updated.\n    function _updateTokenRatesList(uint256 _gasLimit, address[] memory _tokenList) private {\n        // Check if there are any existing tokens.\n        if (_tokenList.length == 0) {\n            // Emit a query failure event.\n            emit FailedUpdateRequest(\"empty token list\");\n            // Check if the contract has enough Ether to pay for the query.\n        } else if (oraclize_getPrice(\"URL\") * _tokenList.length \u003e address(this).balance) {\n            // Emit a query failure event.\n            emit FailedUpdateRequest(\"insufficient balance\");\n        } else {\n            // Set up the cryptocompare API query strings.\n            strings.slice memory apiPrefix = \"https://min-api.cryptocompare.com/data/price?fsym=\".toSlice();\n            strings.slice memory apiSuffix = \"\u0026tsyms=ETH\u0026sign=true\".toSlice();\n\n            // Create a new oraclize query for each supported token.\n            for (uint256 i = 0; i \u003c _tokenList.length; i++) {\n                //token must exist, revert if it doesn\u0027t\n                (string memory tokenSymbol, , , bool available, , , ) = _getTokenInfo(_tokenList[i]);\n                require(available, \"token must be available\");\n                // Store the token symbol used in the query.\n                strings.slice memory symbol = tokenSymbol.toSlice();\n                // Create a new oraclize query from the component strings.\n                bytes32 queryID = oraclize_query(\"URL\", apiPrefix.concat(symbol).toSlice().concat(apiSuffix), _gasLimit);\n                // Store the query ID together with the associated token address.\n                _queryToToken[queryID] = _tokenList[i];\n                // Emit the query success event.\n                emit RequestedUpdate(symbol.toString(), queryID);\n            }\n        }\n    }\n\n    /// @notice Verify the origin proof returned by the cryptocompare API.\n    /// @param _result query result in JSON format.\n    /// @param _proof origin proof from cryptocompare.\n    /// @param _publicKey cryptocompare public key.\n    /// @param _lastUpdate timestamp of the last time the requested token was updated.\n    function _verifyProof(string memory _result, bytes memory _proof, bytes memory _publicKey, uint256 _lastUpdate) private returns (bool, uint256) {\n        // expecting fixed length proofs\n        if (_proof.length != _PROOF_LEN) {\n            revert(\"invalid proof length\");\n        }\n\n        // proof should be 65 bytes long: R (32 bytes) + S (32 bytes) + v (1 byte)\n        if (uint256(uint8(_proof[1])) != _ECDSA_SIG_LEN) {\n            revert(\"invalid signature length\");\n        }\n\n        bytes memory signature = new bytes(_ECDSA_SIG_LEN);\n\n        signature = copyBytes(_proof, 2, _ECDSA_SIG_LEN, signature, 0);\n\n        // Extract the headers, big endian encoding of headers length\n        if (\n            uint256(uint8(_proof[_ENCODING_BYTES + _ECDSA_SIG_LEN])) * _MAX_BYTE_SIZE + uint256(uint8(_proof[_ENCODING_BYTES + _ECDSA_SIG_LEN + 1])) !=\n            _HEADERS_LEN\n        ) {\n            revert(\"invalid headers length\");\n        }\n\n        bytes memory headers = new bytes(_HEADERS_LEN);\n        headers = copyBytes(_proof, 2 * _ENCODING_BYTES + _ECDSA_SIG_LEN, _HEADERS_LEN, headers, 0);\n\n        // Check if the signature is valid and if the signer address is matching.\n        if (!_verifySignature(headers, signature, _publicKey)) {\n            revert(\"invalid signature\");\n        }\n\n        // Check if the date is valid.\n        bytes memory dateHeader = new bytes(20);\n        // keep only the relevant string(e.g. \"16 Nov 2018 16:22:18\")\n        dateHeader = copyBytes(headers, 11, 20, dateHeader, 0);\n\n        bool dateValid;\n        uint256 timestamp;\n        (dateValid, timestamp) = _verifyDate(string(dateHeader), _lastUpdate);\n\n        // Check whether the date returned is valid or not\n        if (!dateValid) {\n            revert(\"invalid date\");\n        }\n\n        // Check if the signed digest hash matches the result hash.\n        bytes memory digest = new bytes(_DIGEST_BASE64_LEN);\n        digest = copyBytes(headers, _DIGEST_OFFSET, _DIGEST_BASE64_LEN, digest, 0);\n\n        if (keccak256(abi.encodePacked(sha256(abi.encodePacked(_result)))) != keccak256(_base64decode(digest))) {\n            revert(\"result hash not matching\");\n        }\n\n        emit VerifiedProof(_publicKey, _result);\n        return (true, timestamp);\n    }\n\n    /// @notice Verify the HTTP headers and the signature\n    /// @param _headers HTTP headers provided by the cryptocompare api\n    /// @param _signature signature provided by the cryptocompare api\n    /// @param _publicKey cryptocompare public key.\n    function _verifySignature(bytes memory _headers, bytes memory _signature, bytes memory _publicKey) private returns (bool) {\n        address signer;\n        bool signatureOK;\n\n        // Checks if the signature is valid by hashing the headers\n        (signatureOK, signer) = ecrecovery(sha256(_headers), _signature);\n        return signatureOK \u0026\u0026 signer == address(uint160(uint256(keccak256(_publicKey))));\n    }\n\n    /// @notice Verify the signed HTTP date header.\n    /// @param _dateHeader extracted date string e.g. Wed, 12 Sep 2018 15:18:14 GMT.\n    /// @param _lastUpdate timestamp of the last time the requested token was updated.\n    function _verifyDate(string memory _dateHeader, uint256 _lastUpdate) private pure returns (bool, uint256) {\n        // called by verifyProof(), _dateHeader is always a string of length = 20\n        assert(abi.encodePacked(_dateHeader).length == 20);\n\n        // Split the date string and get individual date components.\n        strings.slice memory date = _dateHeader.toSlice();\n        strings.slice memory timeDelimiter = \":\".toSlice();\n        strings.slice memory dateDelimiter = \" \".toSlice();\n\n        uint256 day = _parseIntScientific(date.split(dateDelimiter).toString());\n        require(day \u003e 0 \u0026\u0026 day \u003c 32, \"day error\");\n\n        uint256 month = _monthToNumber(date.split(dateDelimiter).toString());\n        require(month \u003e 0 \u0026\u0026 month \u003c 13, \"month error\");\n\n        uint256 year = _parseIntScientific(date.split(dateDelimiter).toString());\n        require(year \u003e 2017 \u0026\u0026 year \u003c 3000, \"year error\");\n\n        uint256 hour = _parseIntScientific(date.split(timeDelimiter).toString());\n        require(hour \u003c 25, \"hour error\");\n\n        uint256 minute = _parseIntScientific(date.split(timeDelimiter).toString());\n        require(minute \u003c 60, \"minute error\");\n\n        uint256 second = _parseIntScientific(date.split(timeDelimiter).toString());\n        require(second \u003c 60, \"second error\");\n\n        uint256 timestamp = year * (10**10) + month * (10**8) + day * (10**6) + hour * (10**4) + minute * (10**2) + second;\n\n        return (timestamp \u003e _lastUpdate, timestamp);\n    }\n}\n"},"oraclize.sol":{"content":"pragma solidity ^0.5.17;\n\n\ncontract OraclizeConnector {\n    address public cbAddress;\n    uint256 gasPrice;\n    bytes1 public proofType;\n\n    constructor(address _cbAddress) public {\n        cbAddress = _cbAddress;\n    }\n\n    function query(string memory _arg) private pure returns (bytes32) {\n        return keccak256(bytes(_arg));\n    }\n\n    function query(uint256 _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32) {\n        if (_timestamp == 0 \u0026\u0026 bytes(_datasource).length == 0) {\n            return query(_arg);\n        }\n        return keccak256(bytes(_arg));\n    }\n\n    function query_withGasLimit(uint256 _timestamp, string calldata _datasource, string calldata _arg, uint256 _gaslimit) external payable returns (bytes32) {\n        if (_timestamp == 0 \u0026\u0026 bytes(_datasource).length == 0 \u0026\u0026 _gaslimit == 0) {\n            return query(_arg);\n        }\n        return keccak256(bytes(_arg));\n    }\n\n    function getPrice(string memory _datasource) public pure returns (uint256) {\n        if (bytes(_datasource).length == 0) {\n            return 1000000;\n        }\n        return 1000000; //10^6\n    }\n\n    function getPrice(string memory _datasource, uint256 gaslimit) public pure returns (uint256) {\n        if (gaslimit == 0) {\n            return getPrice(_datasource);\n        }\n        return 1000000; //10^6\n    }\n\n    function setProofType(bytes1 _proofType) external {\n        proofType = _proofType;\n    }\n\n    function setCustomGasPrice(uint256 _gasPrice) external {\n        gasPrice = _gasPrice;\n    }\n}\n\n\ncontract OraclizeAddrResolver {\n    address private oraclizedAddress;\n\n    constructor(address _oraclizedAddress) public {\n        oraclizedAddress = _oraclizedAddress;\n    }\n\n    function getAddress() public view returns (address) {\n        return oraclizedAddress;\n    }\n}\n"},"oraclizeAPI_0.5.sol":{"content":"/*\n\nORACLIZE_API\n\nCopyright (c) 2015-2016 Oraclize SRL\nCopyright (c) 2016 Oraclize LTD\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*/\npragma solidity \u003e= 0.5.0 \u003c 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI!\n\n// Dummy contract only used to emit to end-user they are using wrong solc\ncontract solcChecker {\n/* INCOMPATIBLE SOLC: import the following instead: \"github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol\" */ function f(bytes calldata x) external;\n}\n\ncontract OraclizeI {\n\n    address public cbAddress;\n\n    function setProofType(byte _proofType) external;\n    function setCustomGasPrice(uint _gasPrice) external;\n    function getPrice(string memory _datasource) public returns (uint _dsprice);\n    function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);\n    function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice);\n    function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id);\n    function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);\n    function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id);\n    function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);\n    function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);\n    function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);\n}\n\ncontract OraclizeAddrResolverI {\n    function getAddress() public returns (address _address);\n}\n/*\n\nBegin solidity-cborutils\n\nhttps://github.com/smartcontractkit/solidity-cborutils\n\nMIT License\n\nCopyright (c) 2018 SmartContract ChainLink, Ltd.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*/\nlibrary Buffer {\n\n    struct buffer {\n        bytes buf;\n        uint capacity;\n    }\n\n    function init(buffer memory _buf, uint _capacity) internal pure {\n        uint capacity = _capacity;\n        if (capacity % 32 != 0) {\n            capacity += 32 - (capacity % 32);\n        }\n        _buf.capacity = capacity; // Allocate space for the buffer data\n        assembly {\n            let ptr := mload(0x40)\n            mstore(_buf, ptr)\n            mstore(ptr, 0)\n            mstore(0x40, add(ptr, capacity))\n        }\n    }\n\n    function resize(buffer memory _buf, uint _capacity) private pure {\n        bytes memory oldbuf = _buf.buf;\n        init(_buf, _capacity);\n        append(_buf, oldbuf);\n    }\n\n    function max(uint _a, uint _b) private pure returns (uint _max) {\n        if (_a \u003e _b) {\n            return _a;\n        }\n        return _b;\n    }\n    /**\n      * @dev Appends a byte array to the end of the buffer. Resizes if doing so\n      *      would exceed the capacity of the buffer.\n      * @param _buf The buffer to append to.\n      * @param _data The data to append.\n      * @return The original buffer.\n      *\n      */\n    function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {\n        if (_data.length + _buf.buf.length \u003e _buf.capacity) {\n            resize(_buf, max(_buf.capacity, _data.length) * 2);\n        }\n        uint dest;\n        uint src;\n        uint len = _data.length;\n        assembly {\n            let bufptr := mload(_buf) // Memory address of the buffer data\n            let buflen := mload(bufptr) // Length of existing buffer data\n            dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)\n            mstore(bufptr, add(buflen, mload(_data))) // Update buffer length\n            src := add(_data, 32)\n        }\n        for(; len \u003e= 32; len -= 32) { // Copy word-length chunks while possible\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n        uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n        return _buf;\n    }\n    /**\n      *\n      * @dev Appends a byte to the end of the buffer. Resizes if doing so would\n      * exceed the capacity of the buffer.\n      * @param _buf The buffer to append to.\n      * @param _data The data to append.\n      * @return The original buffer.\n      *\n      */\n    function append(buffer memory _buf, uint8 _data) internal pure {\n        if (_buf.buf.length + 1 \u003e _buf.capacity) {\n            resize(_buf, _buf.capacity * 2);\n        }\n        assembly {\n            let bufptr := mload(_buf) // Memory address of the buffer data\n            let buflen := mload(bufptr) // Length of existing buffer data\n            let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)\n            mstore8(dest, _data)\n            mstore(bufptr, add(buflen, 1)) // Update buffer length\n        }\n    }\n    /**\n      *\n      * @dev Appends a byte to the end of the buffer. Resizes if doing so would\n      * exceed the capacity of the buffer.\n      * @param _buf The buffer to append to.\n      * @param _data The data to append.\n      * @return The original buffer.\n      *\n      */\n    function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {\n        if (_len + _buf.buf.length \u003e _buf.capacity) {\n            resize(_buf, max(_buf.capacity, _len) * 2);\n        }\n        uint mask = 256 ** _len - 1;\n        assembly {\n            let bufptr := mload(_buf) // Memory address of the buffer data\n            let buflen := mload(bufptr) // Length of existing buffer data\n            let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len\n            mstore(dest, or(and(mload(dest), not(mask)), _data))\n            mstore(bufptr, add(buflen, _len)) // Update buffer length\n        }\n        return _buf;\n    }\n}\n\nlibrary CBOR {\n\n    using Buffer for Buffer.buffer;\n\n    uint8 private constant MAJOR_TYPE_INT = 0;\n    uint8 private constant MAJOR_TYPE_MAP = 5;\n    uint8 private constant MAJOR_TYPE_BYTES = 2;\n    uint8 private constant MAJOR_TYPE_ARRAY = 4;\n    uint8 private constant MAJOR_TYPE_STRING = 3;\n    uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;\n    uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;\n\n    function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {\n        if (_value \u003c= 23) {\n            _buf.append(uint8((_major \u003c\u003c 5) | _value));\n        } else if (_value \u003c= 0xFF) {\n            _buf.append(uint8((_major \u003c\u003c 5) | 24));\n            _buf.appendInt(_value, 1);\n        } else if (_value \u003c= 0xFFFF) {\n            _buf.append(uint8((_major \u003c\u003c 5) | 25));\n            _buf.appendInt(_value, 2);\n        } else if (_value \u003c= 0xFFFFFFFF) {\n            _buf.append(uint8((_major \u003c\u003c 5) | 26));\n            _buf.appendInt(_value, 4);\n        } else if (_value \u003c= 0xFFFFFFFFFFFFFFFF) {\n            _buf.append(uint8((_major \u003c\u003c 5) | 27));\n            _buf.appendInt(_value, 8);\n        }\n    }\n\n    function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {\n        _buf.append(uint8((_major \u003c\u003c 5) | 31));\n    }\n\n    function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {\n        encodeType(_buf, MAJOR_TYPE_INT, _value);\n    }\n\n    function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {\n        if (_value \u003e= 0) {\n            encodeType(_buf, MAJOR_TYPE_INT, uint(_value));\n        } else {\n            encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));\n        }\n    }\n\n    function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {\n        encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);\n        _buf.append(_value);\n    }\n\n    function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {\n        encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);\n        _buf.append(bytes(_value));\n    }\n\n    function startArray(Buffer.buffer memory _buf) internal pure {\n        encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);\n    }\n\n    function startMap(Buffer.buffer memory _buf) internal pure {\n        encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);\n    }\n\n    function endSequence(Buffer.buffer memory _buf) internal pure {\n        encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);\n    }\n}\n/*\n\nEnd solidity-cborutils\n\n*/\ncontract usingOraclize {\n\n    using CBOR for Buffer.buffer;\n\n    OraclizeI oraclize;\n    OraclizeAddrResolverI OAR;\n\n    uint constant day = 60 * 60 * 24;\n    uint constant week = 60 * 60 * 24 * 7;\n    uint constant month = 60 * 60 * 24 * 30;\n\n    byte constant proofType_NONE = 0x00;\n    byte constant proofType_Ledger = 0x30;\n    byte constant proofType_Native = 0xF0;\n    byte constant proofStorage_IPFS = 0x01;\n    byte constant proofType_Android = 0x40;\n    byte constant proofType_TLSNotary = 0x10;\n\n    string oraclize_network_name;\n    uint8 constant networkID_auto = 0;\n    uint8 constant networkID_morden = 2;\n    uint8 constant networkID_mainnet = 1;\n    uint8 constant networkID_testnet = 2;\n    uint8 constant networkID_consensys = 161;\n\n    mapping(bytes32 =\u003e bytes32) oraclize_randomDS_args;\n    mapping(bytes32 =\u003e bool) oraclize_randomDS_sessionKeysHashVerified;\n\n    modifier oraclizeAPI {\n        if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {\n            oraclize_setNetwork(networkID_auto);\n        }\n        if (address(oraclize) != OAR.getAddress()) {\n            oraclize = OraclizeI(OAR.getAddress());\n        }\n        _;\n    }\n\n    modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {\n        // RandomDS Proof Step 1: The prefix has to match \u0027LP\\x01\u0027 (Ledger Proof version 1)\n        require((_proof[0] == \"L\") \u0026\u0026 (_proof[1] == \"P\") \u0026\u0026 (uint8(_proof[2]) == uint8(1)));\n        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());\n        require(proofVerified);\n        _;\n    }\n\n    function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {\n      _networkID; // NOTE: Silence the warning and remain backwards compatible\n      return oraclize_setNetwork();\n    }\n\n    function oraclize_setNetworkName(string memory _network_name) internal {\n        oraclize_network_name = _network_name;\n    }\n\n    function oraclize_getNetworkName() internal view returns (string memory _networkName) {\n        return oraclize_network_name;\n    }\n\n    function oraclize_setNetwork() internal returns (bool _networkSet) {\n        if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) \u003e 0) { //mainnet\n            OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);\n            oraclize_setNetworkName(\"eth_mainnet\");\n            return true;\n        }\n        if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) \u003e 0) { //ropsten testnet\n            OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);\n            oraclize_setNetworkName(\"eth_ropsten3\");\n            return true;\n        }\n        if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) \u003e 0) { //kovan testnet\n            OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);\n            oraclize_setNetworkName(\"eth_kovan\");\n            return true;\n        }\n        if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) \u003e 0) { //rinkeby testnet\n            OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);\n            oraclize_setNetworkName(\"eth_rinkeby\");\n            return true;\n        }\n        if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) \u003e 0) { //goerli testnet\n            OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);\n            oraclize_setNetworkName(\"eth_goerli\");\n            return true;\n        }\n        if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) \u003e 0) { //ethereum-bridge\n            OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);\n            return true;\n        }\n        if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) \u003e 0) { //ether.camp ide\n            OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);\n            return true;\n        }\n        if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) \u003e 0) { //browser-solidity\n            OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);\n            return true;\n        }\n        return false;\n    }\n    /**\n     * @dev The following `__callback` functions are just placeholders ideally\n     *      meant to be defined in child contract when proofs are used.\n     *      The function bodies simply silence compiler warnings.\n     */\n    /* function __callback(bytes32 _myid, string memory _result) public {\n        __callback(_myid, _result, new bytes(0));\n    } */\n\n    function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public {\n      _myid; _result; _proof;\n      oraclize_randomDS_args[bytes32(0)] = bytes32(0);\n    }\n\n    function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) {\n        return oraclize.getPrice(_datasource);\n    }\n\n    function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) {\n        return oraclize.getPrice(_datasource, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query.value(price)(0, _datasource, _arg);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query.value(price)(_timestamp, _datasource, _arg);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource,_gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n           return 0; // Unexpectedly high price\n        }\n        return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = stra2cbor(_argN);\n        return oraclize.queryN.value(price)(0, _datasource, args);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = stra2cbor(_argN);\n        return oraclize.queryN.value(price)(_timestamp, _datasource, args);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = stra2cbor(_argN);\n        return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = stra2cbor(_argN);\n        return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        string[] memory dynargs = new string[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = ba2cbor(_argN);\n        return oraclize.queryN.value(price)(0, _datasource, args);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource);\n        if (price \u003e 1 ether + tx.gasprice * 200000) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = ba2cbor(_argN);\n        return oraclize.queryN.value(price)(_timestamp, _datasource, args);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = ba2cbor(_argN);\n        return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        uint price = oraclize.getPrice(_datasource, _gasLimit);\n        if (price \u003e 1 ether + tx.gasprice * _gasLimit) {\n            return 0; // Unexpectedly high price\n        }\n        bytes memory args = ba2cbor(_argN);\n        return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](1);\n        dynargs[0] = _args[0];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](2);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](3);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](4);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_timestamp, _datasource, dynargs);\n    }\n\n    function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {\n        bytes[] memory dynargs = new bytes[](5);\n        dynargs[0] = _args[0];\n        dynargs[1] = _args[1];\n        dynargs[2] = _args[2];\n        dynargs[3] = _args[3];\n        dynargs[4] = _args[4];\n        return oraclize_query(_datasource, dynargs, _gasLimit);\n    }\n\n    function oraclize_setProof(byte _proofP) oraclizeAPI internal {\n        return oraclize.setProofType(_proofP);\n    }\n\n\n    function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) {\n        return oraclize.cbAddress();\n    }\n\n    function getCodeSize(address _addr) view internal returns (uint _size) {\n        assembly {\n            _size := extcodesize(_addr)\n        }\n    }\n\n    function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal {\n        return oraclize.setCustomGasPrice(_gasPrice);\n    }\n\n    function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) {\n        return oraclize.randomDS_getSessionPubKeyHash();\n    }\n\n    function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {\n        bytes memory tmp = bytes(_a);\n        uint160 iaddr = 0;\n        uint160 b1;\n        uint160 b2;\n        for (uint i = 2; i \u003c 2 + 2 * 20; i += 2) {\n            iaddr *= 256;\n            b1 = uint160(uint8(tmp[i]));\n            b2 = uint160(uint8(tmp[i + 1]));\n            if ((b1 \u003e= 97) \u0026\u0026 (b1 \u003c= 102)) {\n                b1 -= 87;\n            } else if ((b1 \u003e= 65) \u0026\u0026 (b1 \u003c= 70)) {\n                b1 -= 55;\n            } else if ((b1 \u003e= 48) \u0026\u0026 (b1 \u003c= 57)) {\n                b1 -= 48;\n            }\n            if ((b2 \u003e= 97) \u0026\u0026 (b2 \u003c= 102)) {\n                b2 -= 87;\n            } else if ((b2 \u003e= 65) \u0026\u0026 (b2 \u003c= 70)) {\n                b2 -= 55;\n            } else if ((b2 \u003e= 48) \u0026\u0026 (b2 \u003c= 57)) {\n                b2 -= 48;\n            }\n            iaddr += (b1 * 16 + b2);\n        }\n        return address(iaddr);\n    }\n\n    function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {\n        bytes memory a = bytes(_a);\n        bytes memory b = bytes(_b);\n        uint minLength = a.length;\n        if (b.length \u003c minLength) {\n            minLength = b.length;\n        }\n        for (uint i = 0; i \u003c minLength; i ++) {\n            if (a[i] \u003c b[i]) {\n                return -1;\n            } else if (a[i] \u003e b[i]) {\n                return 1;\n            }\n        }\n        if (a.length \u003c b.length) {\n            return -1;\n        } else if (a.length \u003e b.length) {\n            return 1;\n        } else {\n            return 0;\n        }\n    }\n\n    function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {\n        bytes memory h = bytes(_haystack);\n        bytes memory n = bytes(_needle);\n        if (h.length \u003c 1 || n.length \u003c 1 || (n.length \u003e h.length)) {\n            return -1;\n        } else if (h.length \u003e (2 ** 128 - 1)) {\n            return -1;\n        } else {\n            uint subindex = 0;\n            for (uint i = 0; i \u003c h.length; i++) {\n                if (h[i] == n[0]) {\n                    subindex = 1;\n                    while(subindex \u003c n.length \u0026\u0026 (i + subindex) \u003c h.length \u0026\u0026 h[i + subindex] == n[subindex]) {\n                        subindex++;\n                    }\n                    if (subindex == n.length) {\n                        return int(i);\n                    }\n                }\n            }\n            return -1;\n        }\n    }\n\n    function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, \"\", \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, _d, \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {\n        bytes memory _ba = bytes(_a);\n        bytes memory _bb = bytes(_b);\n        bytes memory _bc = bytes(_c);\n        bytes memory _bd = bytes(_d);\n        bytes memory _be = bytes(_e);\n        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);\n        bytes memory babcde = bytes(abcde);\n        uint k = 0;\n        uint i = 0;\n        for (i = 0; i \u003c _ba.length; i++) {\n            babcde[k++] = _ba[i];\n        }\n        for (i = 0; i \u003c _bb.length; i++) {\n            babcde[k++] = _bb[i];\n        }\n        for (i = 0; i \u003c _bc.length; i++) {\n            babcde[k++] = _bc[i];\n        }\n        for (i = 0; i \u003c _bd.length; i++) {\n            babcde[k++] = _bd[i];\n        }\n        for (i = 0; i \u003c _be.length; i++) {\n            babcde[k++] = _be[i];\n        }\n        return string(babcde);\n    }\n\n    function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return safeParseInt(_a, 0);\n    }\n\n    function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) break;\n                    else _b--;\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                require(!decimals, \u0027More than one decimal encountered in string!\u0027);\n                decimals = true;\n            } else {\n                revert(\"Non-numeral character encountered in string!\");\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function parseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return parseInt(_a, 0);\n    }\n\n    function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) {\n                       break;\n                   } else {\n                       _b--;\n                   }\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                decimals = true;\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n        if (_i == 0) {\n            return \"0\";\n        }\n        uint j = _i;\n        uint len;\n        while (j != 0) {\n            len++;\n            j /= 10;\n        }\n        bytes memory bstr = new bytes(len);\n        uint k = len - 1;\n        while (_i != 0) {\n            bstr[k--] = byte(uint8(48 + _i % 10));\n            _i /= 10;\n        }\n        return string(bstr);\n    }\n\n    function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {\n        safeMemoryCleaner();\n        Buffer.buffer memory buf;\n        Buffer.init(buf, 1024);\n        buf.startArray();\n        for (uint i = 0; i \u003c _arr.length; i++) {\n            buf.encodeString(_arr[i]);\n        }\n        buf.endSequence();\n        return buf.buf;\n    }\n\n    function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {\n        safeMemoryCleaner();\n        Buffer.buffer memory buf;\n        Buffer.init(buf, 1024);\n        buf.startArray();\n        for (uint i = 0; i \u003c _arr.length; i++) {\n            buf.encodeBytes(_arr[i]);\n        }\n        buf.endSequence();\n        return buf.buf;\n    }\n\n    function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {\n        require((_nbytes \u003e 0) \u0026\u0026 (_nbytes \u003c= 32));\n        _delay *= 10; // Convert from seconds to ledger timer ticks\n        bytes memory nbytes = new bytes(1);\n        nbytes[0] = byte(uint8(_nbytes));\n        bytes memory unonce = new bytes(32);\n        bytes memory sessionKeyHash = new bytes(32);\n        bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();\n        assembly {\n            mstore(unonce, 0x20)\n            /*\n             The following variables can be relaxed.\n             Check the relaxed random contract at https://github.com/oraclize/ethereum-examples\n             for an idea on how to override and replace commit hash variables.\n            */\n            mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))\n            mstore(sessionKeyHash, 0x20)\n            mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)\n        }\n        bytes memory delay = new bytes(32);\n        assembly {\n            mstore(add(delay, 0x20), _delay)\n        }\n        bytes memory delay_bytes8 = new bytes(8);\n        copyBytes(delay, 24, 8, delay_bytes8, 0);\n        bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];\n        bytes32 queryId = oraclize_query(\"random\", args, _customGasLimit);\n        bytes memory delay_bytes8_left = new bytes(8);\n        assembly {\n            let x := mload(add(delay_bytes8, 0x20))\n            mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))\n            mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))\n        }\n        oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));\n        return queryId;\n    }\n\n    function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {\n        oraclize_randomDS_args[_queryId] = _commitment;\n    }\n\n    function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {\n        bool sigok;\n        address signer;\n        bytes32 sigr;\n        bytes32 sigs;\n        bytes memory sigr_ = new bytes(32);\n        uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);\n        sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);\n        bytes memory sigs_ = new bytes(32);\n        offset += 32 + 2;\n        sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);\n        assembly {\n            sigr := mload(add(sigr_, 32))\n            sigs := mload(add(sigs_, 32))\n        }\n        (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);\n        if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {\n            return true;\n        } else {\n            (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);\n            return (address(uint160(uint256(keccak256(_pubkey)))) == signer);\n        }\n    }\n\n    function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {\n        bool sigok;\n        // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)\n        bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);\n        copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);\n        bytes memory appkey1_pubkey = new bytes(64);\n        copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);\n        bytes memory tosign2 = new bytes(1 + 65 + 32);\n        tosign2[0] = byte(uint8(1)); //role\n        copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);\n        bytes memory CODEHASH = hex\"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c\";\n        copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);\n        sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);\n        if (!sigok) {\n            return false;\n        }\n        // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)\n        bytes memory LEDGERKEY = hex\"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4\";\n        bytes memory tosign3 = new bytes(1 + 65);\n        tosign3[0] = 0xFE;\n        copyBytes(_proof, 3, 65, tosign3, 1);\n        bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);\n        copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);\n        sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);\n        return sigok;\n    }\n\n    function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {\n        // Random DS Proof Step 1: The prefix has to match \u0027LP\\x01\u0027 (Ledger Proof version 1)\n        if ((_proof[0] != \"L\") || (_proof[1] != \"P\") || (uint8(_proof[2]) != uint8(1))) {\n            return 1;\n        }\n        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());\n        if (!proofVerified) {\n            return 2;\n        }\n        return 0;\n    }\n\n    function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {\n        bool match_ = true;\n        require(_prefix.length == _nRandomBytes);\n        for (uint256 i = 0; i\u003c _nRandomBytes; i++) {\n            if (_content[i] != _prefix[i]) {\n                match_ = false;\n            }\n        }\n        return match_;\n    }\n\n    function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {\n        // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)\n        uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;\n        bytes memory keyhash = new bytes(32);\n        copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);\n        if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {\n            return false;\n        }\n        bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);\n        copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);\n        // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if \u0027_result\u0027 is the _prefix of sha256(sig1)\n        if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {\n            return false;\n        }\n        // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.\n        // This is to verify that the computed args match with the ones specified in the query.\n        bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);\n        copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);\n        bytes memory sessionPubkey = new bytes(64);\n        uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;\n        copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);\n        bytes32 sessionPubkeyHash = sha256(sessionPubkey);\n        if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match\n            delete oraclize_randomDS_args[_queryId];\n        } else return false;\n        // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)\n        bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);\n        copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);\n        if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {\n            return false;\n        }\n        // Verify if sessionPubkeyHash was verified already, if not.. let\u0027s do it!\n        if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {\n            oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);\n        }\n        return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];\n    }\n    /*\n     The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license\n    */\n    function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {\n        uint minLength = _length + _toOffset;\n        require(_to.length \u003e= minLength); // Buffer too small. Should be a better way?\n        uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables\n        uint j = 32 + _toOffset;\n        while (i \u003c (32 + _fromOffset + _length)) {\n            assembly {\n                let tmp := mload(add(_from, i))\n                mstore(add(_to, j), tmp)\n            }\n            i += 32;\n            j += 32;\n        }\n        return _to;\n    }\n    /*\n     The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license\n     Duplicate Solidity\u0027s ecrecover, but catching the CALL return value\n    */\n    function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {\n        /*\n         We do our own memory management here. Solidity uses memory offset\n         0x40 to store the current end of memory. We write past it (as\n         writes are memory extensions), but don\u0027t update the offset so\n         Solidity will reuse it. The memory used here is only needed for\n         this context.\n         FIXME: inline assembly can\u0027t access return values\n        */\n        bool ret;\n        address addr;\n        assembly {\n            let size := mload(0x40)\n            mstore(size, _hash)\n            mstore(add(size, 32), _v)\n            mstore(add(size, 64), _r)\n            mstore(add(size, 96), _s)\n            ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.\n            addr := mload(size)\n        }\n        return (ret, addr);\n    }\n    /*\n     The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license\n    */\n    function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {\n        bytes32 r;\n        bytes32 s;\n        uint8 v;\n        if (_sig.length != 65) {\n            return (false, address(0));\n        }\n        /*\n         The signature format is a compact form of:\n           {bytes32 r}{bytes32 s}{uint8 v}\n         Compact means, uint8 is not padded to 32 bytes.\n        */\n        assembly {\n            r := mload(add(_sig, 32))\n            s := mload(add(_sig, 64))\n            /*\n             Here we are loading the last 32 bytes. We exploit the fact that\n             \u0027mload\u0027 will pad with zeroes if we overread.\n             There is no \u0027mload8\u0027 to do this, but that would be nicer.\n            */\n            v := byte(0, mload(add(_sig, 96)))\n            /*\n              Alternative solution:\n              \u0027byte\u0027 is not working due to the Solidity parser, so lets\n              use the second best option, \u0027and\u0027\n              v := and(mload(add(_sig, 65)), 255)\n            */\n        }\n        /*\n         albeit non-transactional signatures are not specified by the YP, one would expect it\n         to match the YP range of [27, 28]\n         geth uses [0, 1] and some clients have followed. This might change, see:\n         https://github.com/ethereum/go-ethereum/issues/2053\n        */\n        if (v \u003c 27) {\n            v += 27;\n        }\n        if (v != 27 \u0026\u0026 v != 28) {\n            return (false, address(0));\n        }\n        return safer_ecrecover(_hash, v, r, s);\n    }\n\n    function safeMemoryCleaner() internal pure {\n        assembly {\n            let fmem := mload(0x40)\n            codecopy(fmem, codesize, sub(msize, fmem))\n        }\n    }\n}\n/*\n\nEND ORACLIZE_API\n\n*/\n"},"ownable.sol":{"content":"/**\n *  Ownable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\n\n/// @title Ownable has an owner address and provides basic authorization control functions.\n/// This contract is modified version of the MIT OpenZepplin Ownable contract\n/// This contract allows for the transferOwnership operation to be made impossible\n/// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol\ncontract Ownable {\n    event TransferredOwnership(address _from, address _to);\n    event LockedOwnership(address _locked);\n\n    address payable private _owner;\n    bool private _isTransferable;\n\n    /// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable.\n    constructor(address payable _account_, bool _transferable_) internal {\n        _owner = _account_;\n        _isTransferable = _transferable_;\n        // Emit the LockedOwnership event if no longer transferable.\n        if (!_isTransferable) {\n            emit LockedOwnership(_account_);\n        }\n        emit TransferredOwnership(address(0), _account_);\n    }\n\n    /// @notice Reverts if called by any account other than the owner.\n    modifier onlyOwner() {\n        require(_isOwner(msg.sender), \"sender is not an owner\");\n        _;\n    }\n\n    /// @notice Allows the current owner to transfer control of the contract to a new address.\n    /// @param _account address to transfer ownership to.\n    /// @param _transferable indicates whether to keep the ownership transferable.\n    function transferOwnership(address payable _account, bool _transferable) external onlyOwner {\n        // Require that the ownership is transferable.\n        require(_isTransferable, \"ownership is not transferable\");\n        // Require that the new owner is not the zero address.\n        require(_account != address(0), \"owner cannot be set to zero address\");\n        // Set the transferable flag to the value _transferable passed in.\n        _isTransferable = _transferable;\n        // Emit the LockedOwnership event if no longer transferable.\n        if (!_transferable) {\n            emit LockedOwnership(_account);\n        }\n        // Emit the ownership transfer event.\n        emit TransferredOwnership(_owner, _account);\n        // Set the owner to the provided address.\n        _owner = _account;\n    }\n\n    /// @notice check if the ownership is transferable.\n    /// @return true if the ownership is transferable.\n    function isTransferable() external view returns (bool) {\n        return _isTransferable;\n    }\n\n    /// @notice Allows the current owner to relinquish control of the contract.\n    /// @dev Renouncing to ownership will leave the contract without an owner and unusable.\n    /// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore.\n    function renounceOwnership() external onlyOwner {\n        // Require that the ownership is transferable.\n        require(_isTransferable, \"ownership is not transferable\");\n        // note that this could be terminal\n        _owner = address(0);\n\n        emit TransferredOwnership(_owner, address(0));\n    }\n\n    /// @notice Find out owner address\n    /// @return address of the owner.\n    function owner() public view returns (address payable) {\n        return _owner;\n    }\n\n    /// @notice Check if owner address\n    /// @return true if sender is the owner of the contract.\n    function _isOwner(address _address) internal view returns (bool) {\n        return _address == _owner;\n    }\n}\n"},"parseIntScientific.sol":{"content":"/**\n *  ParseIntScientific - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n*/\n\npragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\n\n\n/// @title ParseIntScientific provides floating point in scientific notation (e.g. e-5) parsing functionality.\ncontract ParseIntScientific {\n    using SafeMath for uint256;\n\n    bytes1 private constant _PLUS_ASCII = bytes1(uint8(43)); //decimal value of \u0027+\u0027\n    bytes1 private constant _DASH_ASCII = bytes1(uint8(45)); //decimal value of \u0027-\u0027\n    bytes1 private constant _DOT_ASCII = bytes1(uint8(46)); //decimal value of \u0027.\u0027\n    bytes1 private constant _ZERO_ASCII = bytes1(uint8(48)); //decimal value of \u00270\u0027\n    bytes1 private constant _NINE_ASCII = bytes1(uint8(57)); //decimal value of \u00279\u0027\n    bytes1 private constant _E_ASCII = bytes1(uint8(69)); //decimal value of \u0027E\u0027\n    bytes1 private constant _LOWERCASE_E_ASCII = bytes1(uint8(101)); //decimal value of \u0027e\u0027\n\n    /// @notice ParseIntScientific delegates the call to _parseIntScientific(string, uint) with the 2nd argument being 0.\n    function _parseIntScientific(string memory _inString) internal pure returns (uint256) {\n        return _parseIntScientific(_inString, 0);\n    }\n\n    /// @notice ParseIntScientificWei parses a rate expressed in ETH and returns its wei denomination\n    function _parseIntScientificWei(string memory _inString) internal pure returns (uint256) {\n        return _parseIntScientific(_inString, 18);\n    }\n\n    /// @notice ParseIntScientific parses a JSON standard - floating point number.\n    /// @param _inString is input string.\n    /// @param _magnitudeMult multiplies the number with 10^_magnitudeMult.\n    function _parseIntScientific(string memory _inString, uint256 _magnitudeMult) internal pure returns (uint256) {\n        bytes memory inBytes = bytes(_inString);\n        uint256 mint = 0; // the final uint returned\n        uint256 mintDec = 0; // the uint following the decimal point\n        uint256 mintExp = 0; // the exponent\n        uint256 decMinted = 0; // how many decimals were \u0027minted\u0027.\n        uint256 expIndex = 0; // the position in the byte array that \u0027e\u0027 was found (if found)\n        bool integral = false; // indicates the existence of the integral part, it should always exist (even if 0) e.g. \u0027e+1\u0027  or \u0027.1\u0027 is not valid\n        bool decimals = false; // indicates a decimal number, set to true if \u0027.\u0027 is found\n        bool exp = false; // indicates if the number being parsed has an exponential representation\n        bool minus = false; // indicated if the exponent is negative\n        bool plus = false; // indicated if the exponent is positive\n        uint256 i;\n        for (i = 0; i \u003c inBytes.length; i++) {\n            if ((inBytes[i] \u003e= _ZERO_ASCII) \u0026\u0026 (inBytes[i] \u003c= _NINE_ASCII) \u0026\u0026 (!exp)) {\n                // \u0027e\u0027 not encountered yet, minting integer part or decimals\n                if (decimals) {\n                    // \u0027.\u0027 encountered\n                    // use safeMath in case there is an overflow\n                    mintDec = mintDec.mul(10);\n                    mintDec = mintDec.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));\n                    decMinted++; //keep track of the #decimals\n                } else {\n                    // integral part (before \u0027.\u0027)\n                    integral = true;\n                    // use safeMath in case there is an overflow\n                    mint = mint.mul(10);\n                    mint = mint.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));\n                }\n            } else if ((inBytes[i] \u003e= _ZERO_ASCII) \u0026\u0026 (inBytes[i] \u003c= _NINE_ASCII) \u0026\u0026 (exp)) {\n                //exponential notation (e-/+) has been detected, mint the exponent\n                mintExp = mintExp.mul(10);\n                mintExp = mintExp.add(uint8(inBytes[i]) - uint8(_ZERO_ASCII));\n            } else if (inBytes[i] == _DOT_ASCII) {\n                //an integral part before should always exist before \u0027.\u0027\n                require(integral, \"missing integral part\");\n                // an extra decimal point makes the format invalid\n                require(!decimals, \"duplicate decimal point\");\n                //the decimal point should always be before the exponent\n                require(!exp, \"decimal after exponent\");\n                decimals = true;\n            } else if (inBytes[i] == _DASH_ASCII) {\n                // an extra \u0027-\u0027 should be considered an invalid character\n                require(!minus, \"duplicate -\");\n                require(!plus, \"extra sign\");\n                require(expIndex + 1 == i, \"- sign not immediately after e\");\n                minus = true;\n            } else if (inBytes[i] == _PLUS_ASCII) {\n                // an extra \u0027+\u0027 should be considered an invalid character\n                require(!plus, \"duplicate +\");\n                require(!minus, \"extra sign\");\n                require(expIndex + 1 == i, \"+ sign not immediately after e\");\n                plus = true;\n            } else if ((inBytes[i] == _E_ASCII) || (inBytes[i] == _LOWERCASE_E_ASCII)) {\n                //an integral part before should always exist before \u0027e\u0027\n                require(integral, \"missing integral part\");\n                // an extra \u0027e\u0027 or \u0027E\u0027 should be considered an invalid character\n                require(!exp, \"duplicate exponent symbol\");\n                exp = true;\n                expIndex = i;\n            } else {\n                revert(\"invalid digit\");\n            }\n        }\n\n        if (minus || plus) {\n            // end of string e[x|-] without specifying the exponent\n            require(i \u003e expIndex + 2);\n        } else if (exp) {\n            // end of string (e) without specifying the exponent\n            require(i \u003e expIndex + 1);\n        }\n\n        if (minus) {\n            // e^(-x)\n            if (mintExp \u003e= _magnitudeMult) {\n                // the (negative) exponent is bigger than the given parameter for \"shifting left\".\n                // use integer division to reduce the precision.\n                require(mintExp - _magnitudeMult \u003c 78, \"exponent \u003e 77\"); //\n                mint /= 10**(mintExp - _magnitudeMult);\n                return mint;\n            } else {\n                // the (negative) exponent is smaller than the given parameter for \"shifting left\".\n                //no need for underflow check\n                _magnitudeMult = _magnitudeMult - mintExp;\n            }\n        } else {\n            // e^(+x), positive exponent or no exponent\n            // just shift left as many times as indicated by the exponent and the shift parameter\n            _magnitudeMult = _magnitudeMult.add(mintExp);\n        }\n\n        if (_magnitudeMult \u003e= decMinted) {\n            // the decimals are fewer or equal than the shifts: use all of them\n            // shift number and add the decimals at the end\n            // include decimals if present in the original input\n            require(decMinted \u003c 78, \"more than 77 decimal digits parsed\"); //\n            mint = mint.mul(10**(decMinted));\n            mint = mint.add(mintDec);\n            //// add zeros at the end if the decimals were fewer than #_magnitudeMult\n            require(_magnitudeMult - decMinted \u003c 78, \"exponent \u003e 77\"); //\n            mint = mint.mul(10**(_magnitudeMult - decMinted));\n        } else {\n            // the decimals are more than the #_magnitudeMult shifts\n            // use only the ones needed, discard the rest\n            decMinted -= _magnitudeMult;\n            require(decMinted \u003c 78, \"more than 77 decimal digits parsed\"); //\n            mintDec /= 10**(decMinted);\n            // shift number and add the decimals at the end\n            require(_magnitudeMult \u003c 78, \"more than 77 decimal digits parsed\"); //\n            mint = mint.mul(10**(_magnitudeMult));\n            mint = mint.add(mintDec);\n        }\n        return mint;\n    }\n}\n"},"parseIntScientificExporter.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./parseIntScientific.sol\";\n\n\ncontract ParseIntScientificExporter is ParseIntScientific {\n    /// @dev exports _parseIntScientific(string) as an external function.\n    function parseIntScientific(string calldata _a) external pure returns (uint256) {\n        return _parseIntScientific(_a);\n    }\n\n    /// @dev exports _parseIntScientific(string, uint) as an external function.\n    function parseIntScientificDecimals(string calldata _a, uint256 _b) external pure returns (uint256) {\n        return _parseIntScientific(_a, _b);\n    }\n\n    /// @dev exports _parseIntScientificWei(string) as an external function.\n    function parseIntScientificWei(string calldata _a) external pure returns (uint256) {\n        return _parseIntScientificWei(_a);\n    }\n}\n"},"PubkeyResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract PubkeyResolver is ResolverBase {\n    bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;\n\n    event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);\n\n    struct PublicKey {\n        bytes32 x;\n        bytes32 y;\n    }\n\n    mapping(bytes32=\u003ePublicKey) pubkeys;\n\n    /**\n     * Sets the SECP256k1 public key associated with an ENS node.\n     * @param node The ENS node to query\n     * @param x the X coordinate of the curve point for the public key.\n     * @param y the Y coordinate of the curve point for the public key.\n     */\n    function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {\n        pubkeys[node] = PublicKey(x, y);\n        emit PubkeyChanged(node, x, y);\n    }\n\n    /**\n     * Returns the SECP256k1 public key associated with an ENS node.\n     * Defined in EIP 619.\n     * @param node The ENS node to query\n     * @return x, y the X and Y coordinates of the curve point for the public key.\n     */\n    function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {\n        return (pubkeys[node].x, pubkeys[node].y);\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}\n"},"PublicResolver.sol":{"content":"/**\n * BSD 2-Clause License\n *\n * Copyright (c) 2018, True Names Limited\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\npragma solidity ^0.5.0;\npragma experimental ABIEncoderV2;\n\nimport \"./ENS.sol\";\nimport \"./ABIResolver.sol\";\nimport \"./AddrResolver.sol\";\nimport \"./ContentHashResolver.sol\";\nimport \"./DNSResolver.sol\";\nimport \"./InterfaceResolver.sol\";\nimport \"./NameResolver.sol\";\nimport \"./PubkeyResolver.sol\";\nimport \"./TextResolver.sol\";\n\n/**\n * A simple resolver anyone can use; only allows the owner of a node to set its\n * address.\n */\ncontract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {\n    ENS ens;\n\n    /**\n     * A mapping of authorisations. An address that is authorised for a name\n     * may make any changes to the name that the owner could, but may not update\n     * the set of authorisations.\n     * (node, owner, caller) =\u003e isAuthorised\n     */\n    mapping(bytes32=\u003emapping(address=\u003emapping(address=\u003ebool))) public authorisations;\n\n    event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);\n\n    constructor(ENS _ens) public {\n        ens = _ens;\n    }\n\n    /**\n     * @dev Sets or clears an authorisation.\n     * Authorisations are specific to the caller. Any account can set an authorisation\n     * for any name, but the authorisation that is checked will be that of the\n     * current owner of a name. Thus, transferring a name effectively clears any\n     * existing authorisations, and new authorisations can be set in advance of\n     * an ownership transfer if desired.\n     *\n     * @param node The name to change the authorisation on.\n     * @param target The address that is to be authorised or deauthorised.\n     * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.\n     */\n    function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {\n        authorisations[node][msg.sender][target] = isAuthorised;\n        emit AuthorisationChanged(node, msg.sender, target, isAuthorised);\n    }\n\n    function isAuthorised(bytes32 node) internal view returns(bool) {\n        address owner = ens.owner(node);\n        return owner == msg.sender || authorisations[node][owner][msg.sender];\n    }\n\n    function multicall(bytes[] calldata data) external returns(bytes[] memory results) {\n        results = new bytes[](data.length);\n        for(uint i = 0; i \u003c data.length; i++) {\n            (bool success, bytes memory result) = address(this).delegatecall(data[i]);\n            require(success);\n            results[i] = result;\n        }\n        return results;\n    }\n}\n"},"ResolverBase.sol":{"content":"pragma solidity ^0.5.0;\n\ncontract ResolverBase {\n    bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == INTERFACE_META_ID;\n    }\n\n    function isAuthorised(bytes32 node) internal view returns(bool);\n\n    modifier authorised(bytes32 node) {\n        require(isAuthorised(node));\n        _;\n    }\n\n    function bytesToAddress(bytes memory b) internal pure returns(address payable a) {\n        require(b.length == 20);\n        assembly {\n            a := div(mload(add(b, 32)), exp(256, 12))\n        }\n    }\n\n    function addressToBytes(address a) internal pure returns(bytes memory b) {\n        b = new bytes(20);\n        assembly {\n            mstore(add(b, 32), mul(a, exp(256, 12)))\n        }\n    }\n}\n"},"RRUtils.sol":{"content":"pragma solidity \u003e0.4.23;\n\nimport \"./ENSBytesUtils.sol\";\n\n/**\n* @dev RRUtils is a library that provides utilities for parsing DNS resource records.\n*/\nlibrary RRUtils {\n    using ENSBytesUtils for *;\n\n    /**\n    * @dev Returns the number of bytes in the DNS name at \u0027offset\u0027 in \u0027self\u0027.\n    * @param self The byte array to read a name from.\n    * @param offset The offset to start reading at.\n    * @return The length of the DNS name at \u0027offset\u0027, in bytes.\n    */\n    function nameLength(bytes memory self, uint offset) internal pure returns(uint) {\n        uint idx = offset;\n        while (true) {\n            assert(idx \u003c self.length);\n            uint labelLen = self.readUint8(idx);\n            idx += labelLen + 1;\n            if (labelLen == 0) {\n                break;\n            }\n        }\n        return idx - offset;\n    }\n\n    /**\n    * @dev Returns a DNS format name at the specified offset of self.\n    * @param self The byte array to read a name from.\n    * @param offset The offset to start reading at.\n    * @return The name.\n    */\n    function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {\n        uint len = nameLength(self, offset);\n        return self.substring(offset, len);\n    }\n\n    /**\n    * @dev Returns the number of labels in the DNS name at \u0027offset\u0027 in \u0027self\u0027.\n    * @param self The byte array to read a name from.\n    * @param offset The offset to start reading at.\n    * @return The number of labels in the DNS name at \u0027offset\u0027, in bytes.\n    */\n    function labelCount(bytes memory self, uint offset) internal pure returns(uint) {\n        uint count = 0;\n        while (true) {\n            assert(offset \u003c self.length);\n            uint labelLen = self.readUint8(offset);\n            offset += labelLen + 1;\n            if (labelLen == 0) {\n                break;\n            }\n            count += 1;\n        }\n        return count;\n    }\n\n    /**\n    * @dev An iterator over resource records.\n    */\n    struct RRIterator {\n        bytes data;\n        uint offset;\n        uint16 dnstype;\n        uint16 class;\n        uint32 ttl;\n        uint rdataOffset;\n        uint nextOffset;\n    }\n\n    /**\n    * @dev Begins iterating over resource records.\n    * @param self The byte string to read from.\n    * @param offset The offset to start reading at.\n    * @return An iterator object.\n    */\n    function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {\n        ret.data = self;\n        ret.nextOffset = offset;\n        next(ret);\n    }\n\n    /**\n    * @dev Returns true iff there are more RRs to iterate.\n    * @param iter The iterator to check.\n    * @return True iff the iterator has finished.\n    */\n    function done(RRIterator memory iter) internal pure returns(bool) {\n        return iter.offset \u003e= iter.data.length;\n    }\n\n    /**\n    * @dev Moves the iterator to the next resource record.\n    * @param iter The iterator to advance.\n    */\n    function next(RRIterator memory iter) internal pure {\n        iter.offset = iter.nextOffset;\n        if (iter.offset \u003e= iter.data.length) {\n            return;\n        }\n\n        // Skip the name\n        uint off = iter.offset + nameLength(iter.data, iter.offset);\n\n        // Read type, class, and ttl\n        iter.dnstype = iter.data.readUint16(off);\n        off += 2;\n        iter.class = iter.data.readUint16(off);\n        off += 2;\n        iter.ttl = iter.data.readUint32(off);\n        off += 4;\n\n        // Read the rdata\n        uint rdataLength = iter.data.readUint16(off);\n        off += 2;\n        iter.rdataOffset = off;\n        iter.nextOffset = off + rdataLength;\n    }\n\n    /**\n    * @dev Returns the name of the current record.\n    * @param iter The iterator.\n    * @return A new bytes object containing the owner name from the RR.\n    */\n    function name(RRIterator memory iter) internal pure returns(bytes memory) {\n        return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));\n    }\n\n    /**\n    * @dev Returns the rdata portion of the current record.\n    * @param iter The iterator.\n    * @return A new bytes object containing the RR\u0027s RDATA.\n    */\n    function rdata(RRIterator memory iter) internal pure returns(bytes memory) {\n        return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);\n    }\n\n    /**\n    * @dev Checks if a given RR type exists in a type bitmap.\n    * @param self The byte string to read the type bitmap from.\n    * @param offset The offset to start reading at.\n    * @param rrtype The RR type to check for.\n    * @return True if the type is found in the bitmap, false otherwise.\n    */\n    function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {\n        uint8 typeWindow = uint8(rrtype \u003e\u003e 8);\n        uint8 windowByte = uint8((rrtype \u0026 0xff) / 8);\n        uint8 windowBitmask = uint8(uint8(1) \u003c\u003c (uint8(7) - uint8(rrtype \u0026 0x7)));\n        for (uint off = offset; off \u003c self.length;) {\n            uint8 window = self.readUint8(off);\n            uint8 len = self.readUint8(off + 1);\n            if (typeWindow \u003c window) {\n                // We\u0027ve gone past our window; it\u0027s not here.\n                return false;\n            } else if (typeWindow == window) {\n                // Check this type bitmap\n                if (len * 8 \u003c= windowByte) {\n                    // Our type is past the end of the bitmap\n                    return false;\n                }\n                return (self.readUint8(off + windowByte + 2) \u0026 windowBitmask) != 0;\n            } else {\n                // Skip this type bitmap\n                off += len + 2;\n            }\n        }\n\n        return false;\n    }\n\n    function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {\n        if (self.equals(other)) {\n            return 0;\n        }\n\n        uint off;\n        uint otheroff;\n        uint prevoff;\n        uint otherprevoff;\n        uint counts = labelCount(self, 0);\n        uint othercounts = labelCount(other, 0);\n\n        // Keep removing labels from the front of the name until both names are equal length\n        while (counts \u003e othercounts) {\n            prevoff = off;\n            off = progress(self, off);\n            counts--;\n        }\n\n        while (othercounts \u003e counts) {\n            otherprevoff = otheroff;\n            otheroff = progress(other, otheroff);\n            othercounts--;\n        }\n\n        // Compare the last nonequal labels to each other\n        while (counts \u003e 0 \u0026\u0026 !self.equals(off, other, otheroff)) {\n            prevoff = off;\n            off = progress(self, off);\n            otherprevoff = otheroff;\n            otheroff = progress(other, otheroff);\n            counts -= 1;\n        }\n\n        if (off == 0) {\n            return -1;\n        }\n        if(otheroff == 0) {\n            return 1;\n        }\n\n        return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));\n    }\n\n    function progress(bytes memory body, uint off) internal pure returns(uint) {\n        return off + 1 + body.readUint8(off);\n    }\n}\n"},"SafeERC20.sol":{"content":"/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2019 zOS Global Limited\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\npragma solidity ^0.5.0;\n\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using SafeMath for uint256;\n    using Address for address;\n\n    function safeTransfer(ERC20 token, address to, uint256 value) internal {\n        callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {\n        callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    function safeApprove(ERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // \u0027safeIncreaseAllowance\u0027 and \u0027safeDecreaseAllowance\u0027\n        // solhint-disable-next-line max-line-length\n        require((value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).add(value);\n        callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).sub(value);\n        callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function callOptionalReturn(ERC20 token, bytes memory data) internal {\n        // We need to perform a low level call here, to bypass Solidity\u0027s return data size checking mechanism, since\n        // we\u0027re implementing it ourselves.\n\n        // A Solidity high level call has three parts:\n        //  1. The target address is checked to verify it contains contract code\n        //  2. The call itself is made, and success asserted\n        //  3. The return value is decoded, which in turn checks the size of the returned data.\n        // solhint-disable-next-line max-line-length\n        require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = address(token).call(data);\n        require(success, \"SafeERC20: low-level call failed\");\n\n        if (returndata.length \u003e 0) { // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"},"SafeMath.sol":{"content":"pragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c \u003e= a, \"SafeMath: addition overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b \u003c= a, \"SafeMath: subtraction overflow\");\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n        // benefit is lost if \u0027b\u0027 is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b \u003e 0, \"SafeMath: division by zero\");\n        uint256 c = a / b;\n        // assert(a == b * c + a % b); // There is no case in which this doesn\u0027t hold\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b != 0, \"SafeMath: modulo by zero\");\n        return a % b;\n    }\n}\n"},"strings.sol":{"content":"/*\n * Copyright 2016 Nick Johnson\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * @title String \u0026 slice utility library for Solidity contracts.\n * @author Nick Johnson \[email protected]\u003e\n *\n * @dev Functionality in this library is largely implemented using an\n *      abstraction called a \u0027slice\u0027. A slice represents a part of a string -\n *      anything from the entire string to a single character, or even no\n *      characters at all (a 0-length slice). Since a slice only has to specify\n *      an offset and a length, copying and manipulating slices is a lot less\n *      expensive than copying and manipulating the strings they reference.\n *\n *      To further reduce gas costs, most functions on slice that need to return\n *      a slice modify the original one instead of allocating a new one; for\n *      instance, `s.split(\".\")` will return the text up to the first \u0027.\u0027,\n *      modifying s to only contain the remainder of the string after the \u0027.\u0027.\n *      In situations where you do not want to modify the original slice, you\n *      can make a copy first with `.copy()`, for example:\n *      `s.copy().split(\".\")`. Try and avoid using this idiom in loops; since\n *      Solidity has no memory management, it will result in allocating many\n *      short-lived slices that are later discarded.\n *\n *      Functions that return two slices come in two versions: a non-allocating\n *      version that takes the second slice as an argument, modifying it in\n *      place, and an allocating version that allocates and returns the second\n *      slice; see `nextRune` for example.\n *\n *      Functions that have to copy string data will return strings rather than\n *      slices; these can be cast back to slices for further processing if\n *      required.\n *\n *      For convenience, some functions are provided with non-modifying\n *      variants that create a new slice and return both; for instance,\n *      `s.splitNew(\u0027.\u0027)` leaves s unmodified, and returns two values\n *      corresponding to the left and right parts of the string.\n */\n\npragma solidity ^0.5.0;\n\nlibrary strings {\n    struct slice {\n        uint _len;\n        uint _ptr;\n    }\n\n    function memcpy(uint dest, uint src, uint len) private pure {\n        // Copy word-length chunks while possible\n        for(; len \u003e= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        // Copy remaining bytes\n        uint mask = 256 ** (32 - len) - 1;\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n    }\n\n    /*\n     * @dev Returns a slice containing the entire string.\n     * @param self The string to make a slice from.\n     * @return A newly allocated slice containing the entire string.\n     */\n    function toSlice(string memory self) internal pure returns (slice memory) {\n        uint ptr;\n        assembly {\n            ptr := add(self, 0x20)\n        }\n        return slice(bytes(self).length, ptr);\n    }\n\n    /*\n     * @dev Returns the length of a null-terminated bytes32 string.\n     * @param self The value to find the length of.\n     * @return The length of the string, from 0 to 32.\n     */\n    function len(bytes32 self) internal pure returns (uint) {\n        uint ret;\n        if (self == 0)\n            return 0;\n        if (uint(self) \u0026 0xffffffffffffffffffffffffffffffff == 0) {\n            ret += 16;\n            self = bytes32(uint(self) / 0x100000000000000000000000000000000);\n        }\n        if (uint(self) \u0026 0xffffffffffffffff == 0) {\n            ret += 8;\n            self = bytes32(uint(self) / 0x10000000000000000);\n        }\n        if (uint(self) \u0026 0xffffffff == 0) {\n            ret += 4;\n            self = bytes32(uint(self) / 0x100000000);\n        }\n        if (uint(self) \u0026 0xffff == 0) {\n            ret += 2;\n            self = bytes32(uint(self) / 0x10000);\n        }\n        if (uint(self) \u0026 0xff == 0) {\n            ret += 1;\n        }\n        return 32 - ret;\n    }\n\n    /*\n     * @dev Returns a slice containing the entire bytes32, interpreted as a\n     *      null-terminated utf-8 string.\n     * @param self The bytes32 value to convert to a slice.\n     * @return A new slice containing the value of the input argument up to the\n     *         first null.\n     */\n    function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {\n        // Allocate space for `self` in memory, copy it there, and point ret at it\n        assembly {\n            let ptr := mload(0x40)\n            mstore(0x40, add(ptr, 0x20))\n            mstore(ptr, self)\n            mstore(add(ret, 0x20), ptr)\n        }\n        ret._len = len(self);\n    }\n\n    /*\n     * @dev Returns a new slice containing the same data as the current slice.\n     * @param self The slice to copy.\n     * @return A new slice containing the same data as `self`.\n     */\n    function copy(slice memory self) internal pure returns (slice memory) {\n        return slice(self._len, self._ptr);\n    }\n\n    /*\n     * @dev Copies a slice to a new string.\n     * @param self The slice to copy.\n     * @return A newly allocated string containing the slice\u0027s text.\n     */\n    function toString(slice memory self) internal pure returns (string memory) {\n        string memory ret = new string(self._len);\n        uint retptr;\n        assembly { retptr := add(ret, 32) }\n\n        memcpy(retptr, self._ptr, self._len);\n        return ret;\n    }\n\n    /*\n     * @dev Returns the length in runes of the slice. Note that this operation\n     *      takes time proportional to the length of the slice; avoid using it\n     *      in loops, and call `slice.empty()` if you only need to know whether\n     *      the slice is empty or not.\n     * @param self The slice to operate on.\n     * @return The length of the slice in runes.\n     */\n    function len(slice memory self) internal pure returns (uint l) {\n        // Starting at ptr-31 means the LSB will be the byte we care about\n        uint ptr = self._ptr - 31;\n        uint end = ptr + self._len;\n        for (l = 0; ptr \u003c end; l++) {\n            uint8 b;\n            assembly { b := and(mload(ptr), 0xFF) }\n            if (b \u003c 0x80) {\n                ptr += 1;\n            } else if (b \u003c 0xE0) {\n                ptr += 2;\n            } else if (b \u003c 0xF0) {\n                ptr += 3;\n            } else if (b \u003c 0xF8) {\n                ptr += 4;\n            } else if (b \u003c 0xFC) {\n                ptr += 5;\n            } else {\n                ptr += 6;\n            }\n        }\n    }\n\n    /*\n     * @dev Returns true if the slice is empty (has a length of 0).\n     * @param self The slice to operate on.\n     * @return True if the slice is empty, False otherwise.\n     */\n    function empty(slice memory self) internal pure returns (bool) {\n        return self._len == 0;\n    }\n\n    /*\n     * @dev Returns a positive number if `other` comes lexicographically after\n     *      `self`, a negative number if it comes before, or zero if the\n     *      contents of the two slices are equal. Comparison is done per-rune,\n     *      on unicode codepoints.\n     * @param self The first slice to compare.\n     * @param other The second slice to compare.\n     * @return The result of the comparison.\n     */\n    function compare(slice memory self, slice memory other) internal pure returns (int) {\n        uint shortest = self._len;\n        if (other._len \u003c self._len)\n            shortest = other._len;\n\n        uint selfptr = self._ptr;\n        uint otherptr = other._ptr;\n        for (uint idx = 0; idx \u003c shortest; idx += 32) {\n            uint a;\n            uint b;\n            assembly {\n                a := mload(selfptr)\n                b := mload(otherptr)\n            }\n            if (a != b) {\n                // Mask out irrelevant bytes and check again\n                uint256 mask = uint256(-1); // 0xffff...\n                if (shortest \u003c 32) {\n                    mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\n                }\n                uint256 diff = (a \u0026 mask) - (b \u0026 mask);\n                if (diff != 0)\n                    return int(diff);\n            }\n            selfptr += 32;\n            otherptr += 32;\n        }\n        return int(self._len) - int(other._len);\n    }\n\n    /*\n     * @dev Returns true if the two slices contain the same text.\n     * @param self The first slice to compare.\n     * @param self The second slice to compare.\n     * @return True if the slices are equal, false otherwise.\n     */\n    function equals(slice memory self, slice memory other) internal pure returns (bool) {\n        return compare(self, other) == 0;\n    }\n\n    /*\n     * @dev Extracts the first rune in the slice into `rune`, advancing the\n     *      slice to point to the next rune and returning `self`.\n     * @param self The slice to operate on.\n     * @param rune The slice that will contain the first rune.\n     * @return `rune`.\n     */\n    function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {\n        rune._ptr = self._ptr;\n\n        if (self._len == 0) {\n            rune._len = 0;\n            return rune;\n        }\n\n        uint l;\n        uint b;\n        // Load the first byte of the rune into the LSBs of b\n        assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\n        if (b \u003c 0x80) {\n            l = 1;\n        } else if (b \u003c 0xE0) {\n            l = 2;\n        } else if (b \u003c 0xF0) {\n            l = 3;\n        } else {\n            l = 4;\n        }\n\n        // Check for truncated codepoints\n        if (l \u003e self._len) {\n            rune._len = self._len;\n            self._ptr += self._len;\n            self._len = 0;\n            return rune;\n        }\n\n        self._ptr += l;\n        self._len -= l;\n        rune._len = l;\n        return rune;\n    }\n\n    /*\n     * @dev Returns the first rune in the slice, advancing the slice to point\n     *      to the next rune.\n     * @param self The slice to operate on.\n     * @return A slice containing only the first rune from `self`.\n     */\n    function nextRune(slice memory self) internal pure returns (slice memory ret) {\n        nextRune(self, ret);\n    }\n\n    /*\n     * @dev Returns the number of the first codepoint in the slice.\n     * @param self The slice to operate on.\n     * @return The number of the first codepoint in the slice.\n     */\n    function ord(slice memory self) internal pure returns (uint ret) {\n        if (self._len == 0) {\n            return 0;\n        }\n\n        uint word;\n        uint length;\n        uint divisor = 2 ** 248;\n\n        // Load the rune into the MSBs of b\n        assembly { word:= mload(mload(add(self, 32))) }\n        uint b = word / divisor;\n        if (b \u003c 0x80) {\n            ret = b;\n            length = 1;\n        } else if (b \u003c 0xE0) {\n            ret = b \u0026 0x1F;\n            length = 2;\n        } else if (b \u003c 0xF0) {\n            ret = b \u0026 0x0F;\n            length = 3;\n        } else {\n            ret = b \u0026 0x07;\n            length = 4;\n        }\n\n        // Check for truncated codepoints\n        if (length \u003e self._len) {\n            return 0;\n        }\n\n        for (uint i = 1; i \u003c length; i++) {\n            divisor = divisor / 256;\n            b = (word / divisor) \u0026 0xFF;\n            if (b \u0026 0xC0 != 0x80) {\n                // Invalid UTF-8 sequence\n                return 0;\n            }\n            ret = (ret * 64) | (b \u0026 0x3F);\n        }\n\n        return ret;\n    }\n\n    /*\n     * @dev Returns the keccak-256 hash of the slice.\n     * @param self The slice to hash.\n     * @return The hash of the slice.\n     */\n    function keccak(slice memory self) internal pure returns (bytes32 ret) {\n        assembly {\n            ret := keccak256(mload(add(self, 32)), mload(self))\n        }\n    }\n\n    /*\n     * @dev Returns true if `self` starts with `needle`.\n     * @param self The slice to operate on.\n     * @param needle The slice to search for.\n     * @return True if the slice starts with the provided text, false otherwise.\n     */\n    function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {\n        if (self._len \u003c needle._len) {\n            return false;\n        }\n\n        if (self._ptr == needle._ptr) {\n            return true;\n        }\n\n        bool equal;\n        assembly {\n            let length := mload(needle)\n            let selfptr := mload(add(self, 0x20))\n            let needleptr := mload(add(needle, 0x20))\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\n        }\n        return equal;\n    }\n\n    /*\n     * @dev If `self` starts with `needle`, `needle` is removed from the\n     *      beginning of `self`. Otherwise, `self` is unmodified.\n     * @param self The slice to operate on.\n     * @param needle The slice to search for.\n     * @return `self`\n     */\n    function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {\n        if (self._len \u003c needle._len) {\n            return self;\n        }\n\n        bool equal = true;\n        if (self._ptr != needle._ptr) {\n            assembly {\n                let length := mload(needle)\n                let selfptr := mload(add(self, 0x20))\n                let needleptr := mload(add(needle, 0x20))\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\n            }\n        }\n\n        if (equal) {\n            self._len -= needle._len;\n            self._ptr += needle._len;\n        }\n\n        return self;\n    }\n\n    /*\n     * @dev Returns true if the slice ends with `needle`.\n     * @param self The slice to operate on.\n     * @param needle The slice to search for.\n     * @return True if the slice starts with the provided text, false otherwise.\n     */\n    function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {\n        if (self._len \u003c needle._len) {\n            return false;\n        }\n\n        uint selfptr = self._ptr + self._len - needle._len;\n\n        if (selfptr == needle._ptr) {\n            return true;\n        }\n\n        bool equal;\n        assembly {\n            let length := mload(needle)\n            let needleptr := mload(add(needle, 0x20))\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\n        }\n\n        return equal;\n    }\n\n    /*\n     * @dev If `self` ends with `needle`, `needle` is removed from the\n     *      end of `self`. Otherwise, `self` is unmodified.\n     * @param self The slice to operate on.\n     * @param needle The slice to search for.\n     * @return `self`\n     */\n    function until(slice memory self, slice memory needle) internal pure returns (slice memory) {\n        if (self._len \u003c needle._len) {\n            return self;\n        }\n\n        uint selfptr = self._ptr + self._len - needle._len;\n        bool equal = true;\n        if (selfptr != needle._ptr) {\n            assembly {\n                let length := mload(needle)\n                let needleptr := mload(add(needle, 0x20))\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\n            }\n        }\n\n        if (equal) {\n            self._len -= needle._len;\n        }\n\n        return self;\n    }\n\n    // Returns the memory address of the first byte of the first occurrence of\n    // `needle` in `self`, or the first byte after `self` if not found.\n    function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\n        uint ptr = selfptr;\n        uint idx;\n\n        if (needlelen \u003c= selflen) {\n            if (needlelen \u003c= 32) {\n                bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\n\n                bytes32 needledata;\n                assembly { needledata := and(mload(needleptr), mask) }\n\n                uint end = selfptr + selflen - needlelen;\n                bytes32 ptrdata;\n                assembly { ptrdata := and(mload(ptr), mask) }\n\n                while (ptrdata != needledata) {\n                    if (ptr \u003e= end)\n                        return selfptr + selflen;\n                    ptr++;\n                    assembly { ptrdata := and(mload(ptr), mask) }\n                }\n                return ptr;\n            } else {\n                // For long needles, use hashing\n                bytes32 hash;\n                assembly { hash := keccak256(needleptr, needlelen) }\n\n                for (idx = 0; idx \u003c= selflen - needlelen; idx++) {\n                    bytes32 testHash;\n                    assembly { testHash := keccak256(ptr, needlelen) }\n                    if (hash == testHash)\n                        return ptr;\n                    ptr += 1;\n                }\n            }\n        }\n        return selfptr + selflen;\n    }\n\n    // Returns the memory address of the first byte after the last occurrence of\n    // `needle` in `self`, or the address of `self` if not found.\n    function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\n        uint ptr;\n\n        if (needlelen \u003c= selflen) {\n            if (needlelen \u003c= 32) {\n                bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\n\n                bytes32 needledata;\n                assembly { needledata := and(mload(needleptr), mask) }\n\n                ptr = selfptr + selflen - needlelen;\n                bytes32 ptrdata;\n                assembly { ptrdata := and(mload(ptr), mask) }\n\n                while (ptrdata != needledata) {\n                    if (ptr \u003c= selfptr)\n                        return selfptr;\n                    ptr--;\n                    assembly { ptrdata := and(mload(ptr), mask) }\n                }\n                return ptr + needlelen;\n            } else {\n                // For long needles, use hashing\n                bytes32 hash;\n                assembly { hash := keccak256(needleptr, needlelen) }\n                ptr = selfptr + (selflen - needlelen);\n                while (ptr \u003e= selfptr) {\n                    bytes32 testHash;\n                    assembly { testHash := keccak256(ptr, needlelen) }\n                    if (hash == testHash)\n                        return ptr + needlelen;\n                    ptr -= 1;\n                }\n            }\n        }\n        return selfptr;\n    }\n\n    /*\n     * @dev Modifies `self` to contain everything from the first occurrence of\n     *      `needle` to the end of the slice. `self` is set to the empty slice\n     *      if `needle` is not found.\n     * @param self The slice to search and modify.\n     * @param needle The text to search for.\n     * @return `self`.\n     */\n    function find(slice memory self, slice memory needle) internal pure returns (slice memory) {\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\n        self._len -= ptr - self._ptr;\n        self._ptr = ptr;\n        return self;\n    }\n\n    /*\n     * @dev Modifies `self` to contain the part of the string from the start of\n     *      `self` to the end of the first occurrence of `needle`. If `needle`\n     *      is not found, `self` is set to the empty slice.\n     * @param self The slice to search and modify.\n     * @param needle The text to search for.\n     * @return `self`.\n     */\n    function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\n        self._len = ptr - self._ptr;\n        return self;\n    }\n\n    /*\n     * @dev Splits the slice, setting `self` to everything after the first\n     *      occurrence of `needle`, and `token` to everything before it. If\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\n     *      and `token` is set to the entirety of `self`.\n     * @param self The slice to split.\n     * @param needle The text to search for in `self`.\n     * @param token An output parameter to which the first token is written.\n     * @return `token`.\n     */\n    function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\n        token._ptr = self._ptr;\n        token._len = ptr - self._ptr;\n        if (ptr == self._ptr + self._len) {\n            // Not found\n            self._len = 0;\n        } else {\n            self._len -= token._len + needle._len;\n            self._ptr = ptr + needle._len;\n        }\n        return token;\n    }\n\n    /*\n     * @dev Splits the slice, setting `self` to everything after the first\n     *      occurrence of `needle`, and returning everything before it. If\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\n     *      and the entirety of `self` is returned.\n     * @param self The slice to split.\n     * @param needle The text to search for in `self`.\n     * @return The part of `self` up to the first occurrence of `delim`.\n     */\n    function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {\n        split(self, needle, token);\n    }\n\n    /*\n     * @dev Splits the slice, setting `self` to everything before the last\n     *      occurrence of `needle`, and `token` to everything after it. If\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\n     *      and `token` is set to the entirety of `self`.\n     * @param self The slice to split.\n     * @param needle The text to search for in `self`.\n     * @param token An output parameter to which the first token is written.\n     * @return `token`.\n     */\n    function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\n        token._ptr = ptr;\n        token._len = self._len - (ptr - self._ptr);\n        if (ptr == self._ptr) {\n            // Not found\n            self._len = 0;\n        } else {\n            self._len -= token._len + needle._len;\n        }\n        return token;\n    }\n\n    /*\n     * @dev Splits the slice, setting `self` to everything before the last\n     *      occurrence of `needle`, and returning everything after it. If\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\n     *      and the entirety of `self` is returned.\n     * @param self The slice to split.\n     * @param needle The text to search for in `self`.\n     * @return The part of `self` after the last occurrence of `delim`.\n     */\n    function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {\n        rsplit(self, needle, token);\n    }\n\n    /*\n     * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.\n     * @param self The slice to search.\n     * @param needle The text to search for in `self`.\n     * @return The number of occurrences of `needle` found in `self`.\n     */\n    function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;\n        while (ptr \u003c= self._ptr + self._len) {\n            cnt++;\n            ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;\n        }\n    }\n\n    /*\n     * @dev Returns True if `self` contains `needle`.\n     * @param self The slice to search.\n     * @param needle The text to search for in `self`.\n     * @return True if `needle` is found in `self`, false otherwise.\n     */\n    function contains(slice memory self, slice memory needle) internal pure returns (bool) {\n        return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;\n    }\n\n    /*\n     * @dev Returns a newly allocated string containing the concatenation of\n     *      `self` and `other`.\n     * @param self The first slice to concatenate.\n     * @param other The second slice to concatenate.\n     * @return The concatenation of the two strings.\n     */\n    function concat(slice memory self, slice memory other) internal pure returns (string memory) {\n        string memory ret = new string(self._len + other._len);\n        uint retptr;\n        assembly { retptr := add(ret, 32) }\n        memcpy(retptr, self._ptr, self._len);\n        memcpy(retptr + self._len, other._ptr, other._len);\n        return ret;\n    }\n\n    /*\n     * @dev Joins an array of slices, using `self` as a delimiter, returning a\n     *      newly allocated string.\n     * @param self The delimiter to use.\n     * @param parts A list of slices to join.\n     * @return A newly allocated string containing all the slices in `parts`,\n     *         joined with `self`.\n     */\n    function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {\n        if (parts.length == 0)\n            return \"\";\n\n        uint length = self._len * (parts.length - 1);\n        for (uint i = 0; i \u003c parts.length; i++) {\n            length += parts[i]._len;\n        }\n\n        string memory ret = new string(length);\n        uint retptr;\n        assembly { retptr := add(ret, 32) }\n\n        for (uint i = 0; i \u003c parts.length; i++) {\n            memcpy(retptr, parts[i]._ptr, parts[i]._len);\n            retptr += parts[i]._len;\n            if (i \u003c parts.length - 1) {\n                memcpy(retptr, self._ptr, self._len);\n                retptr += self._len;\n            }\n        }\n\n        return ret;\n    }\n}\n"},"TextResolver.sol":{"content":"pragma solidity ^0.5.0;\n\nimport \"./ResolverBase.sol\";\n\ncontract TextResolver is ResolverBase {\n    bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;\n\n    event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);\n\n    mapping(bytes32=\u003emapping(string=\u003estring)) texts;\n\n    /**\n     * Sets the text data associated with an ENS node and key.\n     * May only be called by the owner of that node in the ENS registry.\n     * @param node The node to update.\n     * @param key The key to set.\n     * @param value The text data value to set.\n     */\n    function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {\n        texts[node][key] = value;\n        emit TextChanged(node, key, key);\n    }\n\n    /**\n     * Returns the text data associated with an ENS node and key.\n     * @param node The ENS node to query.\n     * @param key The text data key to query.\n     * @return The associated text data.\n     */\n    function text(bytes32 node, string calldata key) external view returns (string memory) {\n        return texts[node][key];\n    }\n\n    function supportsInterface(bytes4 interfaceID) public pure returns(bool) {\n        return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);\n    }\n}"},"token.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./SafeMath.sol\";\n\n\n/// @title Token is a mock ERC20 token used for testing.\ncontract Token {\n    using SafeMath for uint256;\n\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n    /// @dev Total supply of tokens in circulation.\n    uint256 public totalSupply;\n\n    /// @dev Balances for each account.\n    mapping(address =\u003e uint256) public balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint256)) public allowance;\n\n    /// @dev Transfer a token. This throws on insufficient balance.\n    function transfer(address to, uint256 amount) public returns (bool) {\n        require(balanceOf[msg.sender] \u003e= amount);\n        balanceOf[msg.sender] -= amount;\n        balanceOf[to] += amount;\n        emit Transfer(msg.sender, to, amount);\n        return true;\n    }\n\n    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\n        if (_to == address(0)) return false;\n        if (balanceOf[_from] \u003c _value) return false;\n\n        uint256 allowed = allowance[_from][msg.sender];\n        if (allowed \u003c _value) return false; //PROBLEM!\n        /* require(_value \u003c= allowed, \"amount exceeds allowance\"); */\n\n        balanceOf[_to] = SafeMath.add(balanceOf[_to], _value);\n        balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value);\n        allowance[_from][msg.sender] = SafeMath.sub(allowed, _value);\n        emit Transfer(_from, _to, _value);\n        return true;\n    }\n\n    function approve(address _spender, uint256 _value) public returns (bool) {\n        //require user to set to zero before resetting to nonzero\n        if ((_value != 0) \u0026\u0026 (allowance[msg.sender][_spender] != 0)) {\n            return false;\n        }\n\n        allowance[msg.sender][_spender] = _value;\n        emit Approval(msg.sender, _spender, _value);\n        return true;\n    }\n\n    /// @dev Credit an address.\n    function credit(address to, uint256 amount) public returns (bool) {\n        balanceOf[to] += amount;\n        totalSupply += amount;\n        return true;\n    }\n\n    /// @dev Debit an address.\n    function debit(address from, uint256 amount) public {\n        balanceOf[from] -= amount;\n        totalSupply -= amount;\n    }\n}\n"},"tokenWhitelist.sol":{"content":"/**\n *  TokenWhitelist - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./controllable.sol\";\nimport \"./transferrable.sol\";\nimport \"./bytesUtils.sol\";\nimport \"./strings.sol\";\nimport \"./SafeMath.sol\";\n\n\n/// @title The ITokenWhitelist interface provides access to a whitelist of tokens.\ninterface ITokenWhitelist {\n    function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);\n\n    function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);\n\n    function tokenAddressArray() external view returns (address[] memory);\n\n    function redeemableTokens() external view returns (address[] memory);\n\n    function methodIdWhitelist(bytes4) external view returns (bool);\n\n    function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint256);\n\n    function stablecoin() external view returns (address);\n\n    function updateTokenRate(address, uint256, uint256) external;\n}\n\n\n/// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract\ncontract TokenWhitelist is ENSResolvable, Controllable, Transferrable {\n    using strings for *;\n    using SafeMath for uint256;\n    using BytesUtils for bytes;\n\n    event UpdatedTokenRate(address _sender, address _token, uint256 _rate);\n\n    event UpdatedTokenLoadable(address _sender, address _token, bool _loadable);\n    event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable);\n\n    event AddedToken(address _sender, address _token, string _symbol, uint256 _magnitude, bool _loadable, bool _redeemable);\n    event RemovedToken(address _sender, address _token);\n\n    event AddedMethodId(bytes4 _methodId);\n    event RemovedMethodId(bytes4 _methodId);\n    event AddedExclusiveMethod(address _token, bytes4 _methodId);\n    event RemovedExclusiveMethod(address _token, bytes4 _methodId);\n\n    event Claimed(address _to, address _asset, uint256 _amount);\n\n    /// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens\n    bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) =\u003e 0x095ea7b3\n    bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) =\u003e 0x42966c68\n    bytes4 private constant _TRANSFER = 0xa9059cbb; // keccak256(transfer(address,uint256)) =\u003e 0xa9059cbb\n    bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) =\u003e 0x23b872dd\n\n    struct Token {\n        string symbol; // Token symbol\n        uint256 magnitude; // 10^decimals\n        uint256 rate; // Token exchange rate in wei\n        bool available; // Flags if the token is available or not\n        bool loadable; // Flags if token is loadable to the TokenCard\n        bool redeemable; // Flags if token is redeemable in the TKN Holder contract\n        uint256 lastUpdate; // Time of the last rate update\n    }\n\n    mapping(address =\u003e Token) private _tokenInfoMap;\n\n    // @notice specifies whitelisted methodIds for protected tokens in wallet\u0027s excuteTranaction() e.g. keccak256(transfer(address,uint256)) =\u003e 0xa9059cbb\n    mapping(bytes4 =\u003e bool) private _methodIdWhitelist;\n\n    address[] private _tokenAddressArray;\n\n    /// @notice keeping track of how many redeemable tokens are in the tokenWhitelist\n    uint256 private _redeemableCounter;\n\n    /// @notice Address of the stablecoin.\n    address private _stablecoin;\n\n    /// @notice is registered ENS node identifying the oracle contract.\n    bytes32 private _oracleNode;\n\n    /// @notice Constructor initializes ENSResolvable, and Controllable.\n    /// @param _ens_ is the ENS registry address.\n    /// @param _oracleNode_ is the ENS node of the Oracle.\n    /// @param _controllerNode_ is our Controllers node.\n    /// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit.\n    constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_)\n        public\n        ENSResolvable(_ens_)\n        Controllable(_controllerNode_)\n    {\n        _oracleNode = _oracleNode_;\n        _stablecoin = _stablecoinAddress_;\n        //a priori ERC20 whitelisted methods\n        _methodIdWhitelist[_APPROVE] = true;\n        _methodIdWhitelist[_BURN] = true;\n        _methodIdWhitelist[_TRANSFER] = true;\n        _methodIdWhitelist[_TRANSFER_FROM] = true;\n    }\n\n    modifier onlyAdminOrOracle() {\n        address oracleAddress = _ensResolve(_oracleNode);\n        require(_isAdmin(msg.sender) || msg.sender == oracleAddress, \"either oracle or admin\");\n        _;\n    }\n\n    /// @notice Add ERC20 tokens to the list of whitelisted tokens.\n    /// @param _tokens ERC20 token contract addresses.\n    /// @param _symbols ERC20 token names.\n    /// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.\n    /// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard.\n    /// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract.\n    /// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211.\n    function addTokens(\n        address[] calldata _tokens,\n        bytes32[] calldata _symbols,\n        uint256[] calldata _magnitude,\n        bool[] calldata _loadable,\n        bool[] calldata _redeemable,\n        uint256 _lastUpdate\n    ) external onlyAdmin {\n        // Require that all parameters have the same length.\n        require(\n            _tokens.length == _symbols.length \u0026\u0026\n                _tokens.length == _magnitude.length \u0026\u0026\n                _tokens.length == _loadable.length \u0026\u0026\n                _tokens.length == _loadable.length,\n            \"parameter lengths do not match\"\n        );\n        // Add each token to the list of supported tokens.\n        for (uint256 i = 0; i \u003c _tokens.length; i++) {\n            // Require that the token isn\u0027t already available.\n            require(!_tokenInfoMap[_tokens[i]].available, \"token already available\");\n            // Store the intermediate values.\n            string memory symbol = _symbols[i].toSliceB32().toString();\n            // Add the token to the token list.\n            _tokenInfoMap[_tokens[i]] = Token({\n                symbol: symbol,\n                magnitude: _magnitude[i],\n                rate: 0,\n                available: true,\n                loadable: _loadable[i],\n                redeemable: _redeemable[i],\n                lastUpdate: _lastUpdate\n            });\n            // Add the token address to the address list.\n            _tokenAddressArray.push(_tokens[i]);\n            //if the token is redeemable increase the redeemableCounter\n            if (_redeemable[i]) {\n                _redeemableCounter = _redeemableCounter.add(1);\n            }\n            // Emit token addition event.\n            emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]);\n        }\n    }\n\n    /// @notice Remove ERC20 tokens from the whitelist of tokens.\n    /// @param _tokens ERC20 token contract addresses.\n    function removeTokens(address[] calldata _tokens) external onlyAdmin {\n        // Delete each token object from the list of supported tokens based on the addresses provided.\n        for (uint256 i = 0; i \u003c _tokens.length; i++) {\n            // Store the token address.\n            address token = _tokens[i];\n            //token must be available, reverts on duplicates as well\n            require(_tokenInfoMap[token].available, \"token is not available\");\n            //if the token is redeemable decrease the redeemableCounter\n            if (_tokenInfoMap[token].redeemable) {\n                _redeemableCounter = _redeemableCounter.sub(1);\n            }\n            // Delete the token object.\n            delete _tokenInfoMap[token];\n            // Remove the token address from the address list.\n            for (uint256 j = 0; j \u003c _tokenAddressArray.length.sub(1); j++) {\n                if (_tokenAddressArray[j] == token) {\n                    _tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)];\n                    break;\n                }\n            }\n            _tokenAddressArray.length--;\n            // Emit token removal event.\n            emit RemovedToken(msg.sender, token);\n        }\n    }\n\n    /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.\n    /// @param _data is the transaction payload.\n    function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint256) {\n        // Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload:\n        // 4 (signature)  + 32(address or uint256)\n        require(_data.length \u003e= 4 + 32, \"not enough method-encoding bytes\");\n        // Get the method signature\n        bytes4 signature = _data._bytesToBytes4(0);\n        // Check if method Id is supported\n        require(isERC20MethodSupported(_token, signature), \"unsupported method\");\n        // returns the recipient\u0027s address and amount is the value to be transferred\n        if (signature == _BURN) {\n            // 4 (signature) + 32(uint256)\n            return (_token, _data._bytesToUint256(4));\n        } else if (signature == _TRANSFER_FROM) {\n            // 4 (signature) + 32(address) + 32(address) + 32(uint256)\n            require(_data.length \u003e= 4 + 32 + 32 + 32, \"not enough data for transferFrom\");\n            return (_data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32));\n        } else {\n            //transfer or approve\n            // 4 (signature) + 32(address) + 32(uint)\n            require(_data.length \u003e= 4 + 32 + 32, \"not enough data for transfer/appprove\");\n            return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32));\n        }\n    }\n\n    /// @notice Toggles whether or not a token is loadable or not.\n    function setTokenLoadable(address _token, bool _loadable) external onlyAdmin {\n        // Require that the token exists.\n        require(_tokenInfoMap[_token].available, \"token is not available\");\n\n        // this sets the loadable flag to the value passed in\n        _tokenInfoMap[_token].loadable = _loadable;\n\n        emit UpdatedTokenLoadable(msg.sender, _token, _loadable);\n    }\n\n    /// @notice Toggles whether or not a token is redeemable or not.\n    function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin {\n        // Require that the token exists.\n        require(_tokenInfoMap[_token].available, \"token is not available\");\n\n        // this sets the redeemable flag to the value passed in\n        _tokenInfoMap[_token].redeemable = _redeemable;\n\n        emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable);\n    }\n\n    /// @notice Update ERC20 token exchange rate.\n    /// @param _token ERC20 token contract address.\n    /// @param _rate ERC20 token exchange rate in wei.\n    /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.\n    function updateTokenRate(address _token, uint256 _rate, uint256 _updateDate) external onlyAdminOrOracle {\n        // Require that the token exists.\n        require(_tokenInfoMap[_token].available, \"token is not available\");\n        // Update the token\u0027s rate.\n        _tokenInfoMap[_token].rate = _rate;\n        // Update the token\u0027s last update timestamp.\n        _tokenInfoMap[_token].lastUpdate = _updateDate;\n        // Emit the rate update event.\n        emit UpdatedTokenRate(msg.sender, _token, _rate);\n    }\n\n    //// @notice Withdraw tokens from the smart contract to the specified account.\n    function claim(address payable _to, address _asset, uint256 _amount) external onlyAdmin {\n        _safeTransfer(_to, _asset, _amount);\n        emit Claimed(_to, _asset, _amount);\n    }\n\n    /// @notice This returns all of the fields for a given token.\n    /// @param _a is the address of a given token.\n    /// @return string of the token\u0027s symbol.\n    /// @return uint of the token\u0027s magnitude.\n    /// @return uint of the token\u0027s exchange rate to ETH.\n    /// @return bool whether the token is available.\n    /// @return bool whether the token is loadable to the TokenCard.\n    /// @return bool whether the token is redeemable to the TKN Holder Contract.\n    /// @return uint of the lastUpdated time of the token\u0027s exchange rate.\n    function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        Token storage tokenInfo = _tokenInfoMap[_a];\n        return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate);\n    }\n\n    /// @notice This returns all of the fields for our StableCoin.\n    /// @return string of the token\u0027s symbol.\n    /// @return uint of the token\u0027s magnitude.\n    /// @return uint of the token\u0027s exchange rate to ETH.\n    /// @return bool whether the token is available.\n    /// @return bool whether the token is loadable to the TokenCard.\n    /// @return bool whether the token is redeemable to the TKN Holder Contract.\n    /// @return uint of the lastUpdated time of the token\u0027s exchange rate.\n    function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        Token storage stablecoinInfo = _tokenInfoMap[_stablecoin];\n        return (\n            stablecoinInfo.symbol,\n            stablecoinInfo.magnitude,\n            stablecoinInfo.rate,\n            stablecoinInfo.available,\n            stablecoinInfo.loadable,\n            stablecoinInfo.redeemable,\n            stablecoinInfo.lastUpdate\n        );\n    }\n\n    /// @notice This returns an array of all whitelisted token addresses.\n    /// @return address[] of whitelisted tokens.\n    function tokenAddressArray() external view returns (address[] memory) {\n        return _tokenAddressArray;\n    }\n\n    /// @notice This returns an array of all redeemable token addresses.\n    /// @return address[] of redeemable tokens.\n    function redeemableTokens() external view returns (address[] memory) {\n        address[] memory redeemableAddresses = new address[](_redeemableCounter);\n        uint256 redeemableIndex = 0;\n        for (uint256 i = 0; i \u003c _tokenAddressArray.length; i++) {\n            address token = _tokenAddressArray[i];\n            if (_tokenInfoMap[token].redeemable) {\n                redeemableAddresses[redeemableIndex] = token;\n                redeemableIndex += 1;\n            }\n        }\n        return redeemableAddresses;\n    }\n\n    /// @notice This returns true if a method Id is supported for the specific token.\n    /// @return true if _methodId is supported in general or just for the specific token.\n    function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) {\n        require(_tokenInfoMap[_token].available, \"non-existing token\");\n        return (_methodIdWhitelist[_methodId]);\n    }\n\n    /// @notice This returns true if the method is supported for all protected tokens.\n    /// @return true if _methodId is in the method whitelist.\n    function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) {\n        return (_methodIdWhitelist[_methodId]);\n    }\n\n    /// @notice This returns the number of redeemable tokens.\n    /// @return current # of redeemables.\n    function redeemableCounter() external view returns (uint256) {\n        return _redeemableCounter;\n    }\n\n    /// @notice This returns the address of our stablecoin of choice.\n    /// @return the address of the stablecoin contract.\n    function stablecoin() external view returns (address) {\n        return _stablecoin;\n    }\n\n    /// @notice this returns the node hash of our Oracle.\n    /// @return the oracle node registered in ENS.\n    function oracleNode() external view returns (bytes32) {\n        return _oracleNode;\n    }\n}\n"},"tokenWhitelistable.sol":{"content":"/**\n *  TokenWhitelistable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./tokenWhitelist.sol\";\nimport \"./ensResolvable.sol\";\n\n\n/// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS.\ncontract TokenWhitelistable is ENSResolvable {\n    /// @notice Is the registered ENS node identifying the tokenWhitelist contract\n    bytes32 private _tokenWhitelistNode;\n\n    /// @notice Constructor initializes the TokenWhitelistable object.\n    /// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist.\n    constructor(bytes32 _tokenWhitelistNode_) internal {\n        _tokenWhitelistNode = _tokenWhitelistNode_;\n    }\n\n    /// @notice This shows what TokenWhitelist is being used\n    /// @return TokenWhitelist\u0027s node registered in ENS.\n    function tokenWhitelistNode() external view returns (bytes32) {\n        return _tokenWhitelistNode;\n    }\n\n    /// @notice This returns all of the fields for a given token.\n    /// @param _a is the address of a given token.\n    /// @return string of the token\u0027s symbol.\n    /// @return uint of the token\u0027s magnitude.\n    /// @return uint of the token\u0027s exchange rate to ETH.\n    /// @return bool whether the token is available.\n    /// @return bool whether the token is loadable to the TokenCard.\n    /// @return bool whether the token is redeemable to the TKN Holder Contract.\n    /// @return uint of the lastUpdated time of the token\u0027s exchange rate.\n    function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a);\n    }\n\n    /// @notice This returns all of the fields for our stablecoin token.\n    /// @return string of the token\u0027s symbol.\n    /// @return uint of the token\u0027s magnitude.\n    /// @return uint of the token\u0027s exchange rate to ETH.\n    /// @return bool whether the token is available.\n    /// @return bool whether the token is loadable to the TokenCard.\n    /// @return bool whether the token is redeemable to the TKN Holder Contract.\n    /// @return uint of the lastUpdated time of the token\u0027s exchange rate.\n    function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo();\n    }\n\n    /// @notice This returns an array of our whitelisted addresses.\n    /// @return address[] of our whitelisted tokens.\n    function _tokenAddressArray() internal view returns (address[] memory) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray();\n    }\n\n    /// @notice This returns an array of all redeemable token addresses.\n    /// @return address[] of redeemable tokens.\n    function _redeemableTokens() internal view returns (address[] memory) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens();\n    }\n\n    /// @notice Update ERC20 token exchange rate.\n    /// @param _token ERC20 token contract address.\n    /// @param _rate ERC20 token exchange rate in wei.\n    /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.\n    function _updateTokenRate(address _token, uint256 _rate, uint256 _updateDate) internal {\n        ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate);\n    }\n\n    /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.\n    /// @param _data is the transaction payload.\n    function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint256) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data);\n    }\n\n    /// @notice Checks whether a token is available.\n    /// @return bool available or not.\n    function _isTokenAvailable(address _a) internal view returns (bool) {\n        (, , , bool available, , , ) = _getTokenInfo(_a);\n        return available;\n    }\n\n    /// @notice Checks whether a token is redeemable.\n    /// @return bool redeemable or not.\n    function _isTokenRedeemable(address _a) internal view returns (bool) {\n        (, , , , , bool redeemable, ) = _getTokenInfo(_a);\n        return redeemable;\n    }\n\n    /// @notice Checks whether a token is loadable.\n    /// @return bool loadable or not.\n    function _isTokenLoadable(address _a) internal view returns (bool) {\n        (, , , , bool loadable, , ) = _getTokenInfo(_a);\n        return loadable;\n    }\n\n    /// @notice This gets the address of the stablecoin.\n    /// @return the address of the stablecoin contract.\n    function _stablecoin() internal view returns (address) {\n        return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin();\n    }\n}\n"},"tokenWhitelistableExporter.sol":{"content":"pragma solidity ^0.5.17;\n\nimport \"./tokenWhitelistable.sol\";\nimport \"./ensResolvable.sol\";\n\n\ncontract TokenWhitelistableExporter is ENSResolvable, TokenWhitelistable {\n    constructor(address _ens_, bytes32 _tokenWhitelistName_) public ENSResolvable(_ens_) TokenWhitelistable(_tokenWhitelistName_) {}\n\n    function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        return _getTokenInfo(_a);\n    }\n\n    function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {\n        return _getStablecoinInfo();\n    }\n\n    function tokenAddressArray() external view returns (address[] memory) {\n        return _tokenAddressArray();\n    }\n\n    function redeemableTokens() external view returns (address[] memory) {\n        return _redeemableTokens();\n    }\n\n    function updateTokenRate(address _token, uint256 _rate, uint256 _updateDate) external {\n        return _updateTokenRate(_token, _rate, _updateDate);\n    }\n\n    function getERC20RecipientAndAmount(address _destination, bytes calldata _data) external view returns (address, uint256) {\n        return _getERC20RecipientAndAmount(_destination, _data);\n    }\n\n    function isTokenLoadable(address _a) external view returns (bool) {\n        return _isTokenLoadable(_a);\n    }\n\n    function isTokenAvailable(address _a) external view returns (bool) {\n        return _isTokenAvailable(_a);\n    }\n\n    function isTokenRedeemable(address _a) external view returns (bool) {\n        return _isTokenRedeemable(_a);\n    }\n}\n"},"transferrable.sol":{"content":"/**\n *  Transferrable - The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./ERC20.sol\";\nimport \"./SafeERC20.sol\";\n\n\n/// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself\ncontract Transferrable {\n    using SafeERC20 for ERC20;\n\n    /// @dev This function is used to move tokens sent accidentally to this contract method.\n    /// @dev The owner can chose the new destination address\n    /// @param _to is the recipient\u0027s address.\n    /// @param _asset is the address of an ERC20 token or 0x0 for ether.\n    /// @param _amount is the amount to be transferred in base units.\n    function _safeTransfer(address payable _to, address _asset, uint256 _amount) internal {\n        // address(0) is used to denote ETH\n        if (_asset == address(0)) {\n            _to.transfer(_amount);\n        } else {\n            ERC20(_asset).safeTransfer(_to, _amount);\n        }\n    }\n}\n"},"wallet.sol":{"content":"/**\n *  The Consumer Contract Wallet\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./licence.sol\";\nimport \"./ownable.sol\";\nimport \"./controllable.sol\";\nimport \"./balanceable.sol\";\nimport \"./transferrable.sol\";\nimport \"./ensResolvable.sol\";\nimport \"./tokenWhitelistable.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\nimport \"./ERC20.sol\";\nimport \"./SafeERC20.sol\";\nimport \"./ERC165.sol\";\nimport \"./ECDSA.sol\";\n\n\n/// @title ControllableOwnable combines Controllable and Ownable\n/// @dev providing an additional modifier to check if Owner or Controller\ncontract ControllableOwnable is Controllable, Ownable {\n    /// @dev Check if the sender is the Owner or one of the Controllers\n    modifier onlyOwnerOrController() {\n        require(_isOwner(msg.sender) || _isController(msg.sender), \"only owner||controller\");\n        _;\n    }\n}\n\n\n/// @title SelfCallableOwnable allows either owner or the contract itself to call its functions\n/// @dev providing an additional modifier to check if Owner or self is calling\n/// @dev the \"self\" here is used for the meta transactions\ncontract SelfCallableOwnable is Ownable {\n    /// @dev Check if the sender is the Owner or self\n    modifier onlyOwnerOrSelf() {\n        require(_isOwner(msg.sender) || msg.sender == address(this), \"only owner||self\");\n        _;\n    }\n}\n\n\n/// @title AddressWhitelist provides payee-whitelist functionality.\n/// @dev This contract will allow the user to maintain a whitelist of addresses\n/// @dev These addresses will live outside of the various spend limits\ncontract AddressWhitelist is ControllableOwnable, SelfCallableOwnable {\n    using SafeMath for uint256;\n\n    event AddedToWhitelist(address _sender, address[] _addresses);\n    event CancelledWhitelistAddition(address _sender, bytes32 _hash);\n    event SubmittedWhitelistAddition(address[] _addresses, bytes32 _hash);\n\n    event CancelledWhitelistRemoval(address _sender, bytes32 _hash);\n    event RemovedFromWhitelist(address _sender, address[] _addresses);\n    event SubmittedWhitelistRemoval(address[] _addresses, bytes32 _hash);\n\n    mapping(address =\u003e bool) public whitelistMap;\n    address[] public whitelistArray;\n    address[] private _pendingWhitelistAddition;\n    address[] private _pendingWhitelistRemoval;\n    bool public submittedWhitelistAddition;\n    bool public submittedWhitelistRemoval;\n    bool public isSetWhitelist;\n\n    /// @dev Check if the provided addresses contain the owner or the zero-address address.\n    modifier hasNoOwnerOrZeroAddress(address[] memory _addresses) {\n        for (uint256 i = 0; i \u003c _addresses.length; i++) {\n            require(!_isOwner(_addresses[i]), \"contains owner address\");\n            require(_addresses[i] != address(0), \"contains 0 address\");\n        }\n        _;\n    }\n\n    /// @dev Check that neither addition nor removal operations have already been submitted.\n    modifier noActiveSubmission() {\n        require(!submittedWhitelistAddition \u0026\u0026 !submittedWhitelistRemoval, \"whitelist sumbission pending\");\n        _;\n    }\n\n    /// @dev Cancel pending whitelist addition.\n    function cancelWhitelistAddition(bytes32 _hash) external onlyOwnerOrController {\n        // Check if operation has been submitted.\n        require(submittedWhitelistAddition, \"no pending submission\");\n        // Require that confirmation hash and the hash of the pending whitelist addition match\n        require(_hash == calculateHash(_pendingWhitelistAddition), \"non-matching pending whitelist hash\");\n        // Reset pending addresses.\n        delete _pendingWhitelistAddition;\n        // Reset the submitted operation flag.\n        submittedWhitelistAddition = false;\n        // Emit the cancellation event.\n        emit CancelledWhitelistAddition(msg.sender, _hash);\n    }\n\n    /// @dev Cancel pending removal of whitelisted addresses.\n    function cancelWhitelistRemoval(bytes32 _hash) external onlyOwnerOrController {\n        // Check if operation has been submitted.\n        require(submittedWhitelistRemoval, \"no pending submission\");\n        // Require that confirmation hash and the hash of the pending whitelist removal match\n        require(_hash == calculateHash(_pendingWhitelistRemoval), \"non-matching pending whitelist hash\");\n        // Reset pending addresses.\n        delete _pendingWhitelistRemoval;\n        // Reset pending addresses.\n        submittedWhitelistRemoval = false;\n        // Emit the cancellation event.\n        emit CancelledWhitelistRemoval(msg.sender, _hash);\n    }\n\n    /// @dev Confirm pending whitelist addition.\n    /// @dev This will only ever be applied post 2FA, by one of the Controllers\n    /// @param _hash is the hash of the pending whitelist array, a form of lamport lock\n    function confirmWhitelistAddition(bytes32 _hash) external onlyController {\n        // Require that the whitelist addition has been submitted.\n        require(submittedWhitelistAddition, \"no pending submission\");\n        // Require that confirmation hash and the hash of the pending whitelist addition match\n        require(_hash == calculateHash(_pendingWhitelistAddition), \"non-matching pending whitelist hash\");\n        // Whitelist pending addresses.\n        for (uint256 i = 0; i \u003c _pendingWhitelistAddition.length; i++) {\n            // check if it doesn\u0027t exist already.\n            if (!whitelistMap[_pendingWhitelistAddition[i]]) {\n                // add to the Map and the Array\n                whitelistMap[_pendingWhitelistAddition[i]] = true;\n                whitelistArray.push(_pendingWhitelistAddition[i]);\n            }\n        }\n        // Emit the addition event.\n        emit AddedToWhitelist(msg.sender, _pendingWhitelistAddition);\n        // Reset pending addresses.\n        delete _pendingWhitelistAddition;\n        // Reset the submission flag.\n        submittedWhitelistAddition = false;\n    }\n\n    /// @dev Confirm pending removal of whitelisted addresses.\n    function confirmWhitelistRemoval(bytes32 _hash) external onlyController {\n        // Require that the pending whitelist is not empty and the operation has been submitted.\n        require(submittedWhitelistRemoval, \"no pending submission\");\n        // Require that confirmation hash and the hash of the pending whitelist removal match\n        require(_hash == calculateHash(_pendingWhitelistRemoval), \"non-matching pending whitelist hash\");\n        // Remove pending addresses.\n        for (uint256 i = 0; i \u003c _pendingWhitelistRemoval.length; i++) {\n            // check if it exists\n            if (whitelistMap[_pendingWhitelistRemoval[i]]) {\n                whitelistMap[_pendingWhitelistRemoval[i]] = false;\n                for (uint256 j = 0; j \u003c whitelistArray.length.sub(1); j++) {\n                    if (whitelistArray[j] == _pendingWhitelistRemoval[i]) {\n                        whitelistArray[j] = whitelistArray[whitelistArray.length - 1];\n                        break;\n                    }\n                }\n                whitelistArray.length--;\n            }\n        }\n        // Emit the removal event.\n        emit RemovedFromWhitelist(msg.sender, _pendingWhitelistRemoval);\n        // Reset pending addresses.\n        delete _pendingWhitelistRemoval;\n        // Reset the submission flag.\n        submittedWhitelistRemoval = false;\n    }\n\n    /// @dev Getter for pending addition array.\n    function pendingWhitelistAddition() external view returns (address[] memory) {\n        return _pendingWhitelistAddition;\n    }\n\n    /// @dev Getter for pending removal array.\n    function pendingWhitelistRemoval() external view returns (address[] memory) {\n        return _pendingWhitelistRemoval;\n    }\n\n    /// @dev Add initial addresses to the whitelist.\n    /// @param _addresses are the Ethereum addresses to be whitelisted.\n    function setWhitelist(address[] calldata _addresses) external onlyOwnerOrSelf hasNoOwnerOrZeroAddress(_addresses) {\n        // Require that the whitelist has not been initialized.\n        require(!isSetWhitelist, \"whitelist initialized\");\n        // Add each of the provided addresses to the whitelist.\n        for (uint256 i = 0; i \u003c _addresses.length; i++) {\n            // Dedup addresses before writing to the whitelist\n            if (!whitelistMap[_addresses[i]]) {\n                // adds to the whitelist mapping\n                whitelistMap[_addresses[i]] = true;\n                // adds to the whitelist array\n                whitelistArray.push(_addresses[i]);\n            }\n        }\n        isSetWhitelist = true;\n        // Emit the addition event.\n        emit AddedToWhitelist(msg.sender, whitelistArray);\n    }\n\n    /// @dev Add addresses to the whitelist.\n    /// @param _addresses are the Ethereum addresses to be whitelisted.\n    function submitWhitelistAddition(address[] calldata _addresses) external onlyOwnerOrSelf noActiveSubmission hasNoOwnerOrZeroAddress(_addresses) {\n        // Require that the whitelist has been initialized.\n        require(isSetWhitelist, \"whitelist not initialized\");\n        // Require this array of addresses not empty\n        require(_addresses.length \u003e 0, \"empty whitelist\");\n        // Set the provided addresses to the pending addition addresses.\n        _pendingWhitelistAddition = _addresses;\n        // Flag the operation as submitted.\n        submittedWhitelistAddition = true;\n        // Emit the submission event.\n        emit SubmittedWhitelistAddition(_addresses, calculateHash(_addresses));\n    }\n\n    /// @dev Remove addresses from the whitelist.\n    /// @param _addresses are the Ethereum addresses to be removed.\n    function submitWhitelistRemoval(address[] calldata _addresses) external onlyOwnerOrSelf noActiveSubmission {\n        // Require that the whitelist has been initialized.\n        require(isSetWhitelist, \"whitelist not initialized\");\n        // Require that the array of addresses is not empty\n        require(_addresses.length \u003e 0, \"empty whitelist\");\n        // Add the provided addresses to the pending addition list.\n        _pendingWhitelistRemoval = _addresses;\n        // Flag the operation as submitted.\n        submittedWhitelistRemoval = true;\n        // Emit the submission event.\n        emit SubmittedWhitelistRemoval(_addresses, calculateHash(_addresses));\n    }\n\n    /// @dev Method used to hash our whitelist address arrays.\n    function calculateHash(address[] memory _addresses) public pure returns (bytes32) {\n        return keccak256(abi.encodePacked(_addresses));\n    }\n}\n\n\n/// @title DailyLimitTrait This trait allows for daily limits to be included in other contracts.\n/// This contract will allow for a DailyLimit object to be instantiated and used.\nlibrary DailyLimitTrait {\n    using SafeMath for uint256;\n\n    event UpdatedAvailableLimit();\n\n    struct DailyLimit {\n        uint256 value;\n        uint256 available;\n        uint256 limitTimestamp;\n        uint256 pending;\n        bool controllerConfirmationRequired;\n    }\n\n    /// @dev Confirm pending set daily limit operation.\n    function _confirmLimitUpdate(DailyLimit storage self, uint256 _amount) internal {\n        // Require that pending and confirmed spend limit are the same\n        require(self.pending == _amount, \"confirmed/submitted limit mismatch\");\n        // Modify spend limit based on the pending value.\n        _modifyLimit(self, self.pending);\n    }\n\n    /// @dev Use up amount within the daily limit. Will fail if amount is larger than daily limit.\n    function _enforceLimit(DailyLimit storage self, uint256 _amount) internal {\n        // Account for the spend limit daily reset.\n        _updateAvailableLimit(self);\n        require(self.available \u003e= _amount, \"available\u003camount\");\n        self.available = self.available.sub(_amount);\n    }\n\n    /// @dev Returns the available daily balance - accounts for daily limit reset.\n    /// @return amount of available to spend within the current day in base units.\n    function _getAvailableLimit(DailyLimit storage self) internal view returns (uint256) {\n        if (now \u003e self.limitTimestamp.add(24 hours)) {\n            return self.value;\n        } else {\n            return self.available;\n        }\n    }\n\n    /// @dev Modify the spend limit and spend available based on the provided value.\n    /// @dev _amount is the daily limit amount in wei.\n    function _modifyLimit(DailyLimit storage self, uint256 _amount) private {\n        // Account for the spend limit daily reset.\n        _updateAvailableLimit(self);\n        // Set the daily limit to the provided amount.\n        self.value = _amount;\n        // Lower the available limit if it\u0027s higher than the new daily limit.\n        if (self.available \u003e self.value) {\n            self.available = self.value;\n        }\n    }\n\n    /// @dev Set the daily limit.\n    /// @param _amount is the daily limit amount in base units.\n    function _setLimit(DailyLimit storage self, uint256 _amount) internal {\n        // Require that the spend limit has not been set yet.\n        require(!self.controllerConfirmationRequired, \"limit already set\");\n        // Modify spend limit based on the provided value.\n        _modifyLimit(self, _amount);\n        // Flag the operation as set.\n        self.controllerConfirmationRequired = true;\n    }\n\n    /// @dev Submit a daily limit update, needs to be confirmed.\n    /// @param _amount is the daily limit amount in base units.\n    function _submitLimitUpdate(DailyLimit storage self, uint256 _amount) internal {\n        // Require that the spend limit has been set.\n        require(self.controllerConfirmationRequired, \"limit hasn\u0027t been set yet\");\n        // Assign the provided amount to pending daily limit.\n        self.pending = _amount;\n    }\n\n    /// @dev Update available spend limit based on the daily reset.\n    function _updateAvailableLimit(DailyLimit storage self) private {\n        if (now \u003e self.limitTimestamp.add(24 hours)) {\n            // Update the current timestamp.\n            self.limitTimestamp = now;\n            // Set the available limit to the current spend limit.\n            self.available = self.value;\n            emit UpdatedAvailableLimit();\n        }\n    }\n}\n\n\n/// @title  it provides daily spend limit functionality.\ncontract SpendLimit is ControllableOwnable, SelfCallableOwnable {\n    event SetSpendLimit(address _sender, uint256 _amount);\n    event SubmittedSpendLimitUpdate(uint256 _amount);\n\n    using DailyLimitTrait for DailyLimitTrait.DailyLimit;\n\n    DailyLimitTrait.DailyLimit internal _spendLimit;\n\n    /// @dev Constructor initializes the daily spend limit in wei.\n    constructor(uint256 _limit_) internal {\n        _spendLimit = DailyLimitTrait.DailyLimit(_limit_, _limit_, now, 0, false);\n    }\n\n    /// @dev Confirm pending set daily limit operation.\n    function confirmSpendLimitUpdate(uint256 _amount) external onlyController {\n        _spendLimit._confirmLimitUpdate(_amount);\n        emit SetSpendLimit(msg.sender, _amount);\n    }\n\n    /// @dev Sets the initial daily spend (aka transfer) limit for non-whitelisted addresses.\n    /// @param _amount is the daily limit amount in wei.\n    function setSpendLimit(uint256 _amount) external onlyOwnerOrSelf {\n        _spendLimit._setLimit(_amount);\n        emit SetSpendLimit(msg.sender, _amount);\n    }\n\n    /// @dev View your available limit\n    function spendLimitAvailable() external view returns (uint256) {\n        return _spendLimit._getAvailableLimit();\n    }\n\n    /// @dev Is there an active spend limit change\n    function spendLimitPending() external view returns (uint256) {\n        return _spendLimit.pending;\n    }\n\n    /// @dev Has the spend limit been initialised\n    function spendLimitControllerConfirmationRequired() external view returns (bool) {\n        return _spendLimit.controllerConfirmationRequired;\n    }\n\n    /// @dev View how much has been spent already\n    function spendLimitValue() external view returns (uint256) {\n        return _spendLimit.value;\n    }\n\n    /// @dev Submit a daily transfer limit update for non-whitelisted addresses.\n    /// @param _amount is the daily limit amount in wei.\n    function submitSpendLimitUpdate(uint256 _amount) external onlyOwnerOrSelf {\n        _spendLimit._submitLimitUpdate(_amount);\n        emit SubmittedSpendLimitUpdate(_amount);\n    }\n}\n\n\n/// @title GasTopUpLimit provides daily limit functionality.\ncontract GasTopUpLimit is ControllableOwnable, SelfCallableOwnable {\n    event SetGasTopUpLimit(address _sender, uint256 _amount);\n    event SubmittedGasTopUpLimitUpdate(uint256 _amount);\n\n    uint256 private constant _MAXIMUM_GAS_TOPUP_LIMIT = 500 finney;\n    uint256 private constant _MINIMUM_GAS_TOPUP_LIMIT = 1 finney;\n\n    using DailyLimitTrait for DailyLimitTrait.DailyLimit;\n\n    DailyLimitTrait.DailyLimit internal _gasTopUpLimit;\n\n    /// @dev Constructor initializes the daily gas topup limit in wei.\n    constructor() internal {\n        _gasTopUpLimit = DailyLimitTrait.DailyLimit(_MAXIMUM_GAS_TOPUP_LIMIT, _MAXIMUM_GAS_TOPUP_LIMIT, now, 0, false);\n    }\n\n    /// @dev Confirm pending set top up gas limit operation.\n    function confirmGasTopUpLimitUpdate(uint256 _amount) external onlyController {\n        _gasTopUpLimit._confirmLimitUpdate(_amount);\n        emit SetGasTopUpLimit(msg.sender, _amount);\n    }\n\n    /// @dev View your available gas top-up limit\n    function gasTopUpLimitAvailable() external view returns (uint256) {\n        return _gasTopUpLimit._getAvailableLimit();\n    }\n\n    /// @dev Is there an active gas top-up limit change\n    function gasTopUpLimitPending() external view returns (uint256) {\n        return _gasTopUpLimit.pending;\n    }\n\n    /// @dev Has the gas top-up limit been initialised\n    function gasTopUpLimitControllerConfirmationRequired() external view returns (bool) {\n        return _gasTopUpLimit.controllerConfirmationRequired;\n    }\n\n    /// @dev View how much gas top-up has been spent already\n    function gasTopUpLimitValue() external view returns (uint256) {\n        return _gasTopUpLimit.value;\n    }\n\n    /// @dev Sets the daily gas top up limit.\n    /// @param _amount is the gas top up amount in wei.\n    function setGasTopUpLimit(uint256 _amount) external onlyOwnerOrSelf {\n        require(_MINIMUM_GAS_TOPUP_LIMIT \u003c= _amount \u0026\u0026 _amount \u003c= _MAXIMUM_GAS_TOPUP_LIMIT, \"out of range top-up\");\n        _gasTopUpLimit._setLimit(_amount);\n        emit SetGasTopUpLimit(msg.sender, _amount);\n    }\n\n    /// @dev Submit a daily gas top up limit update.\n    /// @param _amount is the daily top up gas limit amount in wei.\n    function submitGasTopUpLimitUpdate(uint256 _amount) external onlyOwnerOrSelf {\n        require(_MINIMUM_GAS_TOPUP_LIMIT \u003c= _amount \u0026\u0026 _amount \u003c= _MAXIMUM_GAS_TOPUP_LIMIT, \"out of range top-up\");\n        _gasTopUpLimit._submitLimitUpdate(_amount);\n        emit SubmittedGasTopUpLimitUpdate(_amount);\n    }\n}\n\n\n/// @title LoadLimit provides daily load limit functionality.\ncontract LoadLimit is ControllableOwnable, SelfCallableOwnable, TokenWhitelistable {\n    event SetLoadLimit(address _sender, uint256 _amount);\n    event SubmittedLoadLimitUpdate(uint256 _amount);\n\n    uint256 private constant _MAXIMUM_STABLECOIN_LOAD_LIMIT = 10000; // USD\n    uint256 private _maximumLoadLimit;\n\n    using DailyLimitTrait for DailyLimitTrait.DailyLimit;\n\n    DailyLimitTrait.DailyLimit internal _loadLimit;\n\n    constructor(bytes32 _tokenWhitelistNode_) internal TokenWhitelistable(_tokenWhitelistNode_) {\n        (, uint256 stablecoinMagnitude, , , , , ) = _getStablecoinInfo();\n        require(stablecoinMagnitude \u003e 0, \"no stablecoin\");\n        _maximumLoadLimit = _MAXIMUM_STABLECOIN_LOAD_LIMIT * stablecoinMagnitude;\n        _loadLimit = DailyLimitTrait.DailyLimit(_maximumLoadLimit, _maximumLoadLimit, now, 0, false);\n    }\n\n    /// @dev Sets a daily card load limit.\n    /// @param _amount is the card load amount in current stablecoin base units.\n    function setLoadLimit(uint256 _amount) external onlyOwnerOrSelf {\n        require(_amount \u003c= _maximumLoadLimit, \"out of range load amount\");\n        _loadLimit._setLimit(_amount);\n        emit SetLoadLimit(msg.sender, _amount);\n    }\n\n    /// @dev Submit a daily load limit update.\n    /// @param _amount is the daily load limit amount in wei.\n    function submitLoadLimitUpdate(uint256 _amount) external onlyOwnerOrSelf {\n        require(_amount \u003c= _maximumLoadLimit, \"out of range load amount\");\n        _loadLimit._submitLimitUpdate(_amount);\n        emit SubmittedLoadLimitUpdate(_amount);\n    }\n\n    /// @dev Confirm pending set load limit operation.\n    function confirmLoadLimitUpdate(uint256 _amount) external onlyController {\n        _loadLimit._confirmLimitUpdate(_amount);\n        emit SetLoadLimit(msg.sender, _amount);\n    }\n\n    /// @dev View your available load limit\n    function loadLimitAvailable() external view returns (uint256) {\n        return _loadLimit._getAvailableLimit();\n    }\n\n    /// @dev Is there an active load limit change\n    function loadLimitPending() external view returns (uint256) {\n        return _loadLimit.pending;\n    }\n\n    /// @dev Has the load limit been initialised\n    function loadLimitControllerConfirmationRequired() external view returns (bool) {\n        return _loadLimit.controllerConfirmationRequired;\n    }\n\n    /// @dev View how much laod limit has been spent already\n    function loadLimitValue() external view returns (uint256) {\n        return _loadLimit.value;\n    }\n}\n\n\n/// @title Asset wallet with extra security features, gas top up management and card integration.\ncontract Wallet is ENSResolvable, GasTopUpLimit, LoadLimit, AddressWhitelist, SpendLimit, ERC165, Transferrable, Balanceable {\n    using Address for address;\n    using ECDSA for bytes32;\n    using SafeERC20 for ERC20;\n    using SafeMath for uint256;\n\n    event BulkTransferred(address _to, address[] _assets);\n    event ExecutedRelayedTransaction(bytes _data, bytes _returndata);\n    event ExecutedTransaction(address _destination, uint256 _value, bytes _data, bytes _returndata);\n    event IncreasedRelayNonce(address _sender, uint256 _currentNonce);\n    event LoadedTokenCard(address _asset, uint256 _amount);\n    event Received(address _from, uint256 _amount);\n    event ToppedUpGas(address _sender, address _owner, uint256 _amount);\n    event Transferred(address _to, address _asset, uint256 _amount);\n    event UpdatedAvailableLimit(); // This is here because our tests don\u0027t inherit events from a library\n\n    string public constant WALLET_VERSION = \"3.2.0\";\n\n    // keccak256(\"isValidSignature(bytes,bytes)\") = 20c13b0bc670c284a9f19cdf7a533ca249404190f8dc132aac33e733b965269e\n    bytes4 private constant _EIP_1271 = 0x20c13b0b;\n    // keccak256(\"isValidSignature(bytes32,bytes)\") = 1626ba7e356f5979dd355a3d2bfb43e80420a480c3b854edce286a82d7496869\n    bytes4 private constant _EIP_1654 = 0x1626ba7e;\n\n    /// @dev Supported ERC165 interface ID.\n    bytes4 private constant _ERC165_INTERFACE_ID = 0x01ffc9a7; // solium-disable-line uppercase\n\n    /// @dev this is an internal nonce to prevent replay attacks from relayer\n    uint256 public relayNonce;\n\n    /// @dev Is the registered ENS node identifying the licence contract.\n    bytes32 private _licenceNode;\n\n    /// @dev Constructor initializes the wallet top up limit and the vault contract.\n    /// @param _owner_ is the owner account of the wallet contract.\n    /// @param _transferable_ indicates whether the contract ownership can be transferred.\n    /// @param _ens_ is the address of the ENS registry.\n    /// @param _tokenWhitelistNode_ is the ENS name node of the Token whitelist.\n    /// @param _controllerNode_ is the ENS name node of the Controller contract.\n    /// @param _licenceNode_ is the ENS name node of the Licence contract.\n    /// @param _spendLimit_ is the initial spend limit.\n    constructor(\n        address payable _owner_,\n        bool _transferable_,\n        address _ens_,\n        bytes32 _tokenWhitelistNode_,\n        bytes32 _controllerNode_,\n        bytes32 _licenceNode_,\n        uint256 _spendLimit_\n    ) public ENSResolvable(_ens_) SpendLimit(_spendLimit_) Ownable(_owner_, _transferable_) Controllable(_controllerNode_) LoadLimit(_tokenWhitelistNode_) {\n        _licenceNode = _licenceNode_;\n    }\n\n    /// @dev Checks if the value is not zero.\n    modifier isNotZero(uint256 _value) {\n        require(_value != 0, \"value=0\");\n        _;\n    }\n\n    /// @dev Ether can be deposited from any source, so this contract must be payable by anyone.\n    function() external payable {\n        emit Received(msg.sender, msg.value);\n    }\n\n    /// @dev This is a bulk transfer convenience function, used to migrate contracts.\n    /// @notice If any of the transfers fail, this will revert.\n    /// @param _to is the recipient\u0027s address, can\u0027t be the zero (0x0) address: transfer() will revert.\n    /// @param _assets is an array of addresses of ERC20 tokens or 0x0 for ether.\n    function bulkTransfer(address payable _to, address[] calldata _assets) external onlyOwnerOrSelf {\n        // check to make sure that _assets isn\u0027t empty\n        require(_assets.length != 0, \"asset array is empty\");\n        // This loops through all of the transfers to be made\n        for (uint256 i = 0; i \u003c _assets.length; i++) {\n            uint256 amount = _balance(address(this), _assets[i]);\n            // use our safe, daily limit protected transfer\n            transfer(_to, _assets[i], amount);\n        }\n\n        emit BulkTransferred(_to, _assets);\n    }\n\n    /// @dev This function allows for the controller to relay transactions on the owner\u0027s behalf,\n    /// the relayed message has to be signed by the owner.\n    /// @param _nonce only used for relayed transactions, must match the wallet\u0027s relayNonce.\n    /// @param _data abi encoded data payload.\n    /// @param _signature signed prefix + data.\n    function executeRelayedTransaction(uint256 _nonce, bytes calldata _data, bytes calldata _signature) external onlyController {\n        // Expecting prefixed data (\"monolith:\") indicating relayed transaction...\n        // ...and an Ethereum Signed Message to protect user from signing an actual Tx\n        uint256 id;\n        assembly {\n            id := chainid() //1 for Ethereum mainnet, \u003e 1 for public testnets.\n        }\n        bytes32 dataHash = keccak256(abi.encodePacked(\"monolith:\", id, address(this), _nonce, _data)).toEthSignedMessageHash();\n        // Verify signature validity i.e. signer == owner\n        require(isValidSignature(dataHash, _signature) == _EIP_1654, \"sig not valid\");\n        // Verify and increase relayNonce to prevent replay attacks from the relayer\n        require(_nonce == relayNonce, \"tx replay\");\n        _increaseRelayNonce();\n\n        // invoke wallet function with an external call\n        (bool success, bytes memory returndata) = address(this).call(_data);\n        require(success, string(returndata));\n\n        emit ExecutedRelayedTransaction(_data, returndata);\n    }\n\n    /// @dev This allows the user to cancel a transaction that was unexpectedly delayed by the relayer\n    function increaseRelayNonce() external onlyOwner {\n        _increaseRelayNonce();\n    }\n\n    /// @dev This bumps the relayNonce and emits an event accordingly\n    function _increaseRelayNonce() internal {\n        relayNonce++;\n\n        emit IncreasedRelayNonce(msg.sender, relayNonce);\n    }\n\n    /// @dev Implements EIP-1271: receives the raw data (bytes)\n    ///      https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1271.md\n    /// @param _data Arbitrary length data signed on the behalf of address(this)\n    /// @param _signature Signature byte array associated with _data\n    function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {\n        bytes32 dataHash = keccak256(abi.encodePacked(_data));\n        // isValidSignature call reverts if not valid.\n        require(isValidSignature(dataHash, _signature) == _EIP_1654, \"sig not valid\");\n        return _EIP_1271;\n    }\n\n    /// @return licence contract node registered in ENS.\n    function licenceNode() external view returns (bytes32) {\n        return _licenceNode;\n    }\n\n    /// @dev Load a token card with the specified asset amount.\n    /// @dev the amount send should be inclusive of the percent licence.\n    /// @param _asset is the address of an ERC20 token or 0x0 for ether.\n    /// @param _amount is the amount of assets to be transferred in base units.\n    function loadTokenCard(address _asset, uint256 _amount) external payable onlyOwnerOrSelf {\n        // check if token is allowed to be used for loading the card\n        require(_isTokenLoadable(_asset), \"token not loadable\");\n        // Convert token amount to stablecoin value.\n        uint256 stablecoinValue = convertToStablecoin(_asset, _amount);\n        // Check against the daily spent limit and update accordingly, require that the value is under remaining limit.\n        _loadLimit._enforceLimit(stablecoinValue);\n        // Get the TKN licenceAddress from ENS\n        address licenceAddress = _ensResolve(_licenceNode);\n        if (_asset != address(0)) {\n            ERC20(_asset).safeApprove(licenceAddress, _amount);\n            ILicence(licenceAddress).load(_asset, _amount);\n        } else {\n            ILicence(licenceAddress).load.value(_amount)(_asset, _amount);\n        }\n\n        emit LoadedTokenCard(_asset, _amount);\n    }\n\n    /// @dev Checks for interface support based on ERC165.\n    function supportsInterface(bytes4 _interfaceID) external view returns (bool) {\n        return _interfaceID == _ERC165_INTERFACE_ID;\n    }\n\n    /// @dev Refill owner\u0027s gas balance, revert if the transaction amount is too large\n    /// @param _amount is the amount of ether to transfer to the owner account in wei.\n    function topUpGas(uint256 _amount) external isNotZero(_amount) onlyOwnerOrController {\n        // Check against the daily spent limit and update accordingly, require that the value is under remaining limit.\n        _gasTopUpLimit._enforceLimit(_amount);\n        // Then perform the transfer\n        owner().transfer(_amount);\n        // Emit the gas top up event.\n        emit ToppedUpGas(msg.sender, owner(), _amount);\n    }\n\n    /// @dev This function allows for the wallet to send a batch of transactions instead of one,\n    /// it calls executeTransaction() so that the daily limit is enforced.\n    /// @param _transactionBatch data encoding the transactions to be sent,\n    /// following executeTransaction\u0027s format i.e. (destination, value, data)\n    function batchExecuteTransaction(bytes memory _transactionBatch) public onlyOwnerOrSelf {\n        uint256 batchLength = _transactionBatch.length + 32; // because the pos starts from 32\n        uint256 remainingBytesLength = _transactionBatch.length; // remaining bytes to be processed\n        uint256 pos = 32; //the first 32 bytes denote the byte array length, start from actual data\n\n        address destination; // destination address\n        uint256 value; // trasanction value\n        uint256 dataLength; // externall call data length\n        bytes memory data; // call data\n\n        while (pos \u003c batchLength) {\n            // there should always be at least 84 bytes remaining: the minimun #bytes required to encode a Tx\n            remainingBytesLength = remainingBytesLength.sub(84);\n            assembly {\n                // shift right by 96 bits (256 - 160) to get the destination address (and zero the excessive bytes)\n                destination := shr(96, mload(add(_transactionBatch, pos)))\n                // get value: pos + 20 bytes (destinnation address)\n                value := mload(add(_transactionBatch, add(pos, 20)))\n                // get data: pos  + 20 (destination address) + 32 (value) bytes\n                // the first 32 bytes denote the byte array length\n                dataLength := mload(add(_transactionBatch, add(pos, 52)))\n                data := add(_transactionBatch, add(pos, 52))\n            }\n            // pos += 20 + 32 + 32 + dataLength, reverts in case of overflow\n            pos = pos.add(dataLength).add(84);\n            // revert in case the encoded dataLength is gonna cause an out of bound access\n            require(pos \u003c= batchLength, \"out of bounds\");\n\n            // if length is 0 ignore the data field\n            if (dataLength == 0) {\n                data = bytes(\"\");\n            }\n            // call executeTransaction(), if one of them reverts then the whole batch reverts.\n            executeTransaction(destination, value, data);\n        }\n    }\n\n    /// @dev Convert ERC20 token amount to the corresponding ether amount.\n    /// @param _token ERC20 token contract address.\n    /// @param _amount amount of token in base units.\n    function convertToEther(address _token, uint256 _amount) public view returns (uint256) {\n        // Store the token in memory to save map entry lookup gas.\n        (, uint256 magnitude, uint256 rate, bool available, , , ) = _getTokenInfo(_token);\n        // If the token exists require that its rate is not zero.\n        if (available) {\n            require(rate != 0, \"rate=0\");\n            // Safely convert the token amount to ether based on the exchange rate.\n            return _amount.mul(rate).div(magnitude);\n        }\n        return 0;\n    }\n\n    /// @dev Convert ether or ERC20 token amount to the corresponding stablecoin amount.\n    /// @param _token ERC20 token contract address.\n    /// @param _amount amount of token in base units.\n    function convertToStablecoin(address _token, uint256 _amount) public view returns (uint256) {\n        // avoid the unnecessary calculations if the token to be loaded is the stablecoin itself\n        if (_token == _stablecoin()) {\n            return _amount;\n        }\n        uint256 amountToSend = _amount;\n\n        // 0x0 represents ether\n        if (_token != address(0)) {\n            // convert to eth first, same as convertToEther()\n            // Store the token in memory to save map entry lookup gas.\n            (, uint256 magnitude, uint256 rate, bool available, , , ) = _getTokenInfo(_token);\n            // require that token both exists in the whitelist and its rate is not zero.\n            require(available, \"token not available\");\n            require(rate != 0, \"rate=0\");\n            // Safely convert the token amount to ether based on the exchangeonly rate.\n            amountToSend = _amount.mul(rate).div(magnitude);\n        }\n        // _amountToSend now is in ether\n        // Get the stablecoin\u0027s magnitude and its current rate.\n        (, uint256 stablecoinMagnitude, uint256 stablecoinRate, bool stablecoinAvailable, , , ) = _getStablecoinInfo();\n        // Check if the stablecoin rate is set.\n        require(stablecoinAvailable, \"token not available\");\n        require(stablecoinRate != 0, \"stablecoin rate=0\");\n        // Safely convert the token amount to stablecoin based on its exchange rate and the stablecoin exchange rate.\n        return amountToSend.mul(stablecoinMagnitude).div(stablecoinRate);\n    }\n\n    /// @dev This function allows for the owner to send any transaction from the Wallet to arbitrary addresses\n    /// @param _destination address of the transaction\n    /// @param _value ETH amount in wei\n    /// @param _data transaction payload binary\n    function executeTransaction(address _destination, uint256 _value, bytes memory _data) public onlyOwnerOrSelf returns (bytes memory) {\n        // If value is send across as a part of this executeTransaction, this will be sent to any payable\n        // destination. As a result enforceLimit if destination is not whitelisted.\n        if (!whitelistMap[_destination]) {\n            _spendLimit._enforceLimit(_value);\n        }\n        // Check if the destination is a Contract and it is one of our supported tokens\n        if (address(_destination).isContract() \u0026\u0026 _isTokenAvailable(_destination)) {\n            // to is the recipient\u0027s address and amount is the value to be transferred\n            address to;\n            uint256 amount;\n            (to, amount) = _getERC20RecipientAndAmount(_destination, _data);\n            if (!whitelistMap[to]) {\n                // If the address (of the token contract, e.g) is not in the TokenWhitelist used by the convert method\n                // then etherValue will be zero\n                uint256 etherValue = convertToEther(_destination, amount);\n                _spendLimit._enforceLimit(etherValue);\n            }\n            // use callOptionalReturn provided in SafeERC20 in case the ERC20 method\n            // returns false instead of reverting!\n            ERC20(_destination).callOptionalReturn(_data);\n\n            // if ERC20 call completes, return a boolean \"true\" as bytes emulating ERC20\n            bytes memory b = new bytes(32);\n            b[31] = 0x01;\n\n            emit ExecutedTransaction(_destination, _value, _data, b);\n            return b;\n        }\n\n        (bool success, bytes memory returndata) = _destination.call.value(_value)(_data);\n        require(success, string(returndata));\n\n        emit ExecutedTransaction(_destination, _value, _data, returndata);\n        // returns all of the bytes returned by _destination contract\n        return returndata;\n    }\n\n    /// @dev Implements EIP-1654: receives the hashed message(bytes32)\n    /// https://github.com/ethereum/EIPs/issues/1654.md\n    /// @param _hashedData Hashed data signed on the behalf of address(this)\n    /// @param _signature Signature byte array associated with _dataHash\n    function isValidSignature(bytes32 _hashedData, bytes memory _signature) public view returns (bytes4) {\n        address from = _hashedData.recover(_signature);\n        require(_isOwner(from), \"invalid signature\");\n        return _EIP_1654;\n    }\n\n    /// @dev Transfers the specified asset to the recipient\u0027s address.\n    /// @param _to is the recipient\u0027s address.\n    /// @param _asset is the address of an ERC20 token or 0x0 for ether.\n    /// @param _amount is the amount of assets to be transferred in base units.\n    function transfer(address payable _to, address _asset, uint256 _amount) public onlyOwnerOrSelf isNotZero(_amount) {\n        // Checks if the _to address is not the zero-address\n        require(_to != address(0), \"destination=0\");\n\n        // If address is not whitelisted, take daily limit into account.\n        if (!whitelistMap[_to]) {\n            // initialize ether value in case the asset is ETH\n            uint256 etherValue = _amount;\n            // Convert token amount to ether value if asset is an ERC20 token.\n            if (_asset != address(0)) {\n                etherValue = convertToEther(_asset, _amount);\n            }\n            // Check against the daily spent limit and update accordingly\n            // Check against the daily spent limit and update accordingly, require that the value is under remaining limit.\n            _spendLimit._enforceLimit(etherValue);\n        }\n        // Transfer token or ether based on the provided address.\n        _safeTransfer(_to, _asset, _amount);\n        // Emit the transfer event.\n        emit Transferred(_to, _asset, _amount);\n    }\n}\n"},"walletCache.sol":{"content":"/**\n *  The Consumer Contract Wallet - Wallet Deployer Cache\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./wallet.sol\";\nimport \"./ensResolvable.sol\";\nimport \"./controllable.sol\";\n\n\n/// @title IWalletCache interface describes a method for poping an already cached wallet\ninterface IWalletCache {\n    function walletCachePop() external returns (Wallet);\n}\n\n\n//// @title Wallet cache with wallet pre-caching functionality.\ncontract WalletCache is ENSResolvable, Controllable {\n    event CachedWallet(Wallet _wallet);\n\n    /*****   Constants   *****/\n    // Default values for mainnet ENS\n    // licence.tokencard.eth\n    bytes32 private constant _DEFAULT_LICENCE_NODE = 0xd0ff8bd67f6e25e4e4b010df582a36a0ee9b78e49afe6cc1cff5dd5a83040330;\n    // token-whitelist.tokencard.eth\n    bytes32 private constant _DEFAULT_TOKEN_WHITELIST_NODE = 0xe84f90570f13fe09f288f2411ff9cf50da611ed0c7db7f73d48053ffc974d396;\n    // wallet-deployer.v3.tokencard.eth\n    bytes32 private constant _DEFAULT_WALLET_DEPLOYER_NODE = 0x1d0c0adbe6addd93659446311e0767a56b67d41ef38f0cb66dcf7560d28a5a38;\n\n    bytes32 public licenceNode = _DEFAULT_LICENCE_NODE;\n    bytes32 public tokenWhitelistNode = _DEFAULT_TOKEN_WHITELIST_NODE;\n    bytes32 public walletDeployerNode = _DEFAULT_WALLET_DEPLOYER_NODE;\n\n    Wallet[] public cachedWallets;\n\n    address public ens;\n    uint256 public defaultSpendLimit;\n\n    /// @notice parameters are passed in so that they can be used to construct new instances of the wallet\n    /// @dev pass in bytes32 to use the default, production node labels for ENS\n    constructor(\n        address _ens_,\n        uint256 _defaultSpendLimit_,\n        bytes32 _controllerNode_,\n        bytes32 _licenceNode_,\n        bytes32 _tokenWhitelistNode_,\n        bytes32 _walletDeployerNode_\n    ) public ENSResolvable(_ens_) Controllable(_controllerNode_) {\n        ens = _ens_;\n        defaultSpendLimit = _defaultSpendLimit_;\n\n        // Set licenceNode or use default\n        if (_licenceNode_ != bytes32(0)) {\n            licenceNode = _licenceNode_;\n        }\n        // Set tokenWhitelistNode or use default\n        if (_tokenWhitelistNode_ != bytes32(0)) {\n            tokenWhitelistNode = _tokenWhitelistNode_;\n        }\n        // Set walletDeployerNode or use default\n        if (_walletDeployerNode_ != bytes32(0)) {\n            walletDeployerNode = _walletDeployerNode_;\n        }\n    }\n\n    modifier onlyWalletDeployer() {\n        require(msg.sender == _ensResolve(walletDeployerNode), \"not called by wallet-deployer\");\n        _;\n    }\n\n    /// @notice This public method allows anyone to pre-cache wallets\n    function cacheWallet() public {\n        // the address(uint160()) cast is done as the Wallet owner (1st argument) needs to be payable\n        Wallet wallet = new Wallet(\n            address(uint160(_ensResolve(walletDeployerNode))),\n            true,\n            ens,\n            tokenWhitelistNode,\n            controllerNode(),\n            licenceNode,\n            defaultSpendLimit\n        );\n        cachedWallets.push(wallet);\n\n        emit CachedWallet(wallet);\n    }\n\n    /// @notice This public method allows only the wallet deployer to pop pre-cached wallets or create a new one in case there aren\u0027t any\n    function walletCachePop() external onlyWalletDeployer returns (Wallet) {\n        if (cachedWallets.length \u003c 1) {\n            cacheWallet();\n        }\n\n        Wallet wallet = cachedWallets[cachedWallets.length - 1];\n        cachedWallets.pop();\n\n        return wallet;\n    }\n\n    /// @notice returns the number of pre-cached wallets\n    function cachedWalletsCount() external view returns (uint256) {\n        return cachedWallets.length;\n    }\n}\n"},"walletDeployer.sol":{"content":"/**\n *  The Consumer Contract Wallet - Wallet Deployer\n *  Copyright (C) 2019 The Contract Wallet Company Limited\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see \u003chttps://www.gnu.org/licenses/\u003e.\n */\n\npragma solidity ^0.5.17;\n\nimport \"./wallet.sol\";\nimport \"./walletCache.sol\";\nimport \"./controllable.sol\";\n\n\n//// @title Wallet deployer with pre-caching if wallets functionality.\ncontract WalletDeployer is ENSResolvable, Controllable {\n    event DeployedWallet(Wallet _wallet, address _owner);\n    event MigratedWallet(Wallet _wallet, Wallet _oldWallet, address _owner, uint256 _paid);\n\n    /*****   Constants   *****/\n    // Default values for mainnet ENS\n    // wallet-cache.v3.tokencard.eth\n    bytes32 private constant _DEFAULT_WALLET_CACHE_NODE = 0xaf553cb0d77690819f9d6fbaa04416e1fdcfa01b2a9a833c7a11e6ae0bc1be88;\n    bytes32 public walletCacheNode = _DEFAULT_WALLET_CACHE_NODE;\n\n    mapping(address =\u003e address) public deployedWallets;\n\n    /// @notice it needs to know to address of the wallet cache\n\n    constructor(address _ens_, bytes32 _controllerNode_, bytes32 _walletCacheNode_) public ENSResolvable(_ens_) Controllable(_controllerNode_) {\n        // Set walletCacheNode or use default\n        if (_walletCacheNode_ != bytes32(0)) {\n            walletCacheNode = _walletCacheNode_;\n        }\n    }\n\n    /// @notice This function is used to deploy a Wallet for a given owner address\n    /// @param _owner is the owner address for the new Wallet to be\n    function deployWallet(address payable _owner) external onlyController {\n        Wallet wallet = IWalletCache(_ensResolve(walletCacheNode)).walletCachePop();\n        emit DeployedWallet(wallet, _owner);\n\n        deployedWallets[_owner] = address(wallet);\n\n        // This sets the changeableOwner boolean to false, i.e. no more change ownership\n        wallet.transferOwnership(_owner, false);\n    }\n\n    /// @notice This function is used to migrate an owner\u0027s security settings from a previous version of the wallet\n    /// @param _owner is the owner address for the new Wallet to be\n    /// @param _spendLimit is the user\u0027s set daily spend limit\n    /// @param _gasTopUpLimit is the user\u0027s set daily gas top-up limit\n    /// @param _whitelistedAddresses is the set of the user\u0027s whitelisted addresses\n    function migrateWallet(\n        address payable _owner,\n        Wallet _oldWallet,\n        bool _initializedSpendLimit,\n        bool _initializedGasTopUpLimit,\n        bool _initializedLoadLimit,\n        bool _initializedWhitelist,\n        uint256 _spendLimit,\n        uint256 _gasTopUpLimit,\n        uint256 _loadLimit,\n        address[] calldata _whitelistedAddresses\n    ) external payable onlyController {\n        require(deployedWallets[_owner] == address(0x0), \"wallet already deployed for owner\");\n        require(_oldWallet.owner() == _owner, \"owner mismatch\");\n\n        Wallet wallet = IWalletCache(_ensResolve(walletCacheNode)).walletCachePop();\n        emit MigratedWallet(wallet, _oldWallet, _owner, msg.value);\n\n        deployedWallets[_owner] = address(wallet);\n\n        // Sets up the security settings as per the _oldWallet\n        if (_initializedSpendLimit) {\n            wallet.setSpendLimit(_spendLimit);\n        }\n        if (_initializedGasTopUpLimit) {\n            wallet.setGasTopUpLimit(_gasTopUpLimit);\n        }\n        if (_initializedLoadLimit) {\n            wallet.setLoadLimit(_loadLimit);\n        }\n        if (_initializedWhitelist) {\n            wallet.setWhitelist(_whitelistedAddresses);\n        }\n\n        wallet.transferOwnership(_owner, false);\n\n        if (msg.value \u003e 0) {\n            _owner.transfer(msg.value);\n        }\n    }\n}\n"}}