File size: 59,366 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
{
  "language": "Solidity",
  "settings": {
    "evmVersion": "london",
    "libraries": {},
    "metadata": {
      "bytecodeHash": "ipfs",
      "useLiteralContent": true
    },
    "optimizer": {
      "enabled": true,
      "runs": 2000
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  },
  "sources": {
    "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n  function decimals() external view returns (uint8);\n\n  function description() external view returns (string memory);\n\n  function version() external view returns (uint256);\n\n  // getRoundData and latestRoundData should both raise \"No data present\"\n  // if they do not have data to report, instead of returning unset values\n  // which could be misinterpreted as actual reported values.\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n}\n"
    },
    "@openzeppelin/contracts/utils/Strings.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n            value /= 10;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        if (value == 0) {\n            return \"0x00\";\n        }\n        uint256 temp = value;\n        uint256 length = 0;\n        while (temp != 0) {\n            length++;\n            temp >>= 8;\n        }\n        return toHexString(value, length);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _HEX_SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\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    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS,\n        InvalidSignatureV\n    }\n\n    function _throwError(RecoverError error) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert(\"ECDSA: invalid signature\");\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert(\"ECDSA: invalid signature length\");\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert(\"ECDSA: invalid signature 's' value\");\n        } else if (error == RecoverError.InvalidSignatureV) {\n            revert(\"ECDSA: invalid signature 'v' value\");\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature` or error string. 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     * 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     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n        // Check the signature length\n        // - case 65: r,s,v signature (standard)\n        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use 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            return tryRecover(hash, v, r, s);\n        } else if (signature.length == 64) {\n            bytes32 r;\n            bytes32 vs;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly {\n                r := mload(add(signature, 0x20))\n                vs := mload(add(signature, 0x40))\n            }\n            return tryRecover(hash, r, vs);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength);\n        }\n    }\n\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     * 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        (address recovered, RecoverError error) = tryRecover(hash, signature);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address, RecoverError) {\n        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n        uint8 v = uint8((uint256(vs) >> 255) + 27);\n        return tryRecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     *\n     * _Available since v4.2._\n     */\n    function recover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address, RecoverError) {\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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS);\n        }\n        if (v != 27 && v != 28) {\n            return (address(0), RecoverError.InvalidSignatureV);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature);\n        }\n\n        return (signer, RecoverError.NoError);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\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    /**\n     * @dev Returns an Ethereum Signed Message, created from `s`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Typed Data, created from a\n     * `domainSeparator` and a `structHash`. This produces hash corresponding\n     * to the one signed with the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n     * JSON-RPC method as part of EIP-712.\n     *\n     * See {recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n    }\n}\n"
    },
    "src/Interfaces/IBondCalculator.sol": {
      "content": "// SPDX-License-Identifier: AGPL-1.0\r\n\r\npragma solidity >=0.7.5 <=0.8.10;\r\n\r\ninterface IBondCalculator {\r\n    function valuation(address tokenIn, uint256 amount_) external view returns (uint256 amountOut);\r\n}\r\n"
    },
    "src/Interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\ninterface IERC20 {\r\n    function totalSupply() external view returns (uint256);\r\n\r\n    function balanceOf(address account) external view returns (uint256);\r\n\r\n    function transfer(address recipient, uint256 amount) external returns (bool);\r\n\r\n    function allowance(address owner, address spender) external view returns (uint256);\r\n\r\n    function approve(address spender, uint256 amount) external returns (bool);\r\n\r\n    function transferFrom(\r\n        address sender,\r\n        address recipient,\r\n        uint256 amount\r\n    ) external returns (bool);\r\n\r\n    event Transfer(address indexed from, address indexed to, uint256 value);\r\n\r\n    event Approval(address indexed owner, address indexed spender, uint256 value);\r\n}\r\n"
    },
    "src/Interfaces/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IERC20.sol\";\r\n\r\ninterface IERC20Metadata is IERC20 {\r\n    function name() external view returns (string memory);\r\n\r\n    function symbol() external view returns (string memory);\r\n\r\n    function decimals() external view returns (uint8);\r\n}\r\n"
    },
    "src/Interfaces/INoteKeeper.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity >=0.7.5;\r\n\r\ninterface INoteKeeper {\r\n    /**\r\n     * @notice  Info for market note\r\n     * @dev     Note::payout is sTHEO remaining to be paid\r\n     *          Note::created is the time the Note was created\r\n     *          Note::matured is the timestamp when the Note is redeemable\r\n     *          Note::redeemed is time market was redeemed\r\n     *          Note::marketID is market ID of deposit. uint48 to avoid adding a slot.\r\n     */\r\n    struct Note {\r\n        uint256 payout;\r\n        uint48 created;\r\n        uint48 matured;\r\n        uint48 redeemed;\r\n        uint48 marketID;\r\n        uint48 discount;\r\n        bool autoStake;\r\n    }\r\n\r\n    function redeem(address _user, uint256[] memory _indexes) external returns (uint256);\r\n\r\n    function redeemAll(address _user) external returns (uint256);\r\n\r\n    function pushNote(address to, uint256 index) external;\r\n\r\n    function pullNote(address from, uint256 index) external returns (uint256 newIndex_);\r\n\r\n    function indexesFor(address _user) external view returns (uint256[] memory);\r\n\r\n    function pendingFor(address _user, uint256 _index)\r\n        external\r\n        view\r\n        returns (\r\n            uint256 payout_,\r\n            uint48 created_,\r\n            uint48 expiry_,\r\n            uint48 timeRemaining_,\r\n            bool matured_,\r\n            uint48 discount_\r\n        );\r\n}\r\n"
    },
    "src/Interfaces/IStakedTHEOToken.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IERC20.sol\";\r\n\r\ninterface IStakedTHEOToken is IERC20 {\r\n    function rebase(uint256 theoProfit_, uint256 epoch_) external returns (uint256);\r\n\r\n    function circulatingSupply() external view returns (uint256);\r\n\r\n    function balanceOf(address who) external view override returns (uint256);\r\n\r\n    function gonsForBalance(uint256 amount) external view returns (uint256);\r\n\r\n    function balanceForGons(uint256 gons) external view returns (uint256);\r\n\r\n    function index() external view returns (uint256);\r\n}\r\n"
    },
    "src/Interfaces/IStaking.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\ninterface IStaking {\r\n    function stake(\r\n        address _to,\r\n        uint256 _amount,\r\n        bool _claim\r\n    ) external returns (uint256, uint256 _index);\r\n\r\n    function claim(address _recipient, bool _rebasing) external returns (uint256);\r\n\r\n    function forfeit(uint256 _index) external;\r\n\r\n    function toggleLock() external;\r\n\r\n    function unstake(\r\n        address _to,\r\n        uint256 _amount,\r\n        bool _trigger,\r\n        bool _rebasing\r\n    ) external returns (uint256);\r\n\r\n    function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_);\r\n\r\n    function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_);\r\n\r\n    function rebase() external;\r\n\r\n    function index() external view returns (uint256);\r\n\r\n    function contractBalance() external view returns (uint256);\r\n\r\n    function totalStaked() external view returns (uint256);\r\n\r\n    function supplyInWarmup() external view returns (uint256);\r\n\r\n    function indexesFor(address _user) external view returns (uint256[] memory);\r\n\r\n    function claimAll(address _recipient) external returns (uint256);\r\n\r\n    function pushClaim(address _to, uint256 _index) external;\r\n\r\n    function pullClaim(address _from, uint256 _index) external returns (uint256 newIndex_);\r\n\r\n    function pushClaimForBond(address _to, uint256 _index) external returns (uint256 newIndex_);\r\n\r\n    function basis() external view returns (address);\r\n}\r\n"
    },
    "src/Interfaces/ITheopetraAuthority.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\ninterface ITheopetraAuthority {\r\n    /* ========== EVENTS ========== */\r\n\r\n    event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n    event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n    event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n    event ManagerPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n    event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n    event SignerPushed(address indexed from, address indexed to, bool _effectiveImmediately);\r\n\r\n    event GovernorPulled(address indexed from, address indexed to);\r\n    event GuardianPulled(address indexed from, address indexed to);\r\n    event PolicyPulled(address indexed from, address indexed to);\r\n    event ManagerPulled(address indexed from, address indexed to);\r\n    event VaultPulled(address indexed from, address indexed to);\r\n    event SignerPulled(address indexed from, address indexed to);\r\n\r\n    /* ========== VIEW ========== */\r\n\r\n    function governor() external view returns (address);\r\n\r\n    function guardian() external view returns (address);\r\n\r\n    function policy() external view returns (address);\r\n\r\n    function manager() external view returns (address);\r\n\r\n    function vault() external view returns (address);\r\n\r\n    function whitelistSigner() external view returns (address);\r\n}\r\n"
    },
    "src/Interfaces/ITreasury.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IBondCalculator.sol\";\r\n\r\ninterface ITreasury {\r\n    function deposit(\r\n        uint256 _amount,\r\n        address _token,\r\n        uint256 _profit\r\n    ) external returns (uint256);\r\n\r\n    function withdraw(uint256 _amount, address _token) external;\r\n\r\n    function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_);\r\n\r\n    function mint(address _recipient, uint256 _amount) external;\r\n\r\n    function manage(address _token, uint256 _amount) external;\r\n\r\n    function incurDebt(uint256 amount_, address token_) external;\r\n\r\n    function repayDebtWithReserve(uint256 amount_, address token_) external;\r\n\r\n    function tokenPerformanceUpdate() external;\r\n\r\n    function baseSupply() external view returns (uint256);\r\n\r\n    function deltaTokenPrice() external view returns (int256);\r\n\r\n    function deltaTreasuryYield() external view returns (int256);\r\n\r\n    function getTheoBondingCalculator() external view returns (IBondCalculator);\r\n\r\n    function setTheoBondingCalculator(address _theoBondingCalculator) external;\r\n}\r\n"
    },
    "src/Interfaces/IWhitelistBondDepository.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IERC20.sol\";\r\n\r\ninterface IWhitelistBondDepository {\r\n    /**\r\n     * @notice      Info about each type of market\r\n     * @dev         Market::capacity is capacity remaining\r\n     *              Market::quoteToken is token to accept as payment\r\n     *              Market::priceFeed is address of the price consumer, to return the USD value for the quote token when deposits are made\r\n     *              Market::capacityInQuote is in payment token (true) or in THEO (false, default)\r\n     *              Market::sold is base tokens out\r\n     *              Market::purchased quote tokens in\r\n     *              Market::usdPricePerTHEO is 9 decimal USD value for each THEO bond\r\n     */\r\n    struct Market {\r\n        uint256 capacity;\r\n        IERC20 quoteToken;\r\n        address priceFeed;\r\n        bool capacityInQuote;\r\n        uint64 sold;\r\n        uint256 purchased;\r\n        uint256 usdPricePerTHEO;\r\n    }\r\n\r\n    /**\r\n     * @notice      Info for creating new markets\r\n     * @dev         Terms::fixedTerm is fixed term or fixed expiration\r\n     *              Terms::vesting is length of time from deposit to maturity if fixed-term\r\n     *              Terms::conclusion is timestamp when market no longer offered (doubles as time when market matures if fixed-expiry)\r\n     */\r\n    struct Terms {\r\n        bool fixedTerm;\r\n        uint48 vesting;\r\n        uint48 conclusion;\r\n    }\r\n\r\n    /**\r\n     * @notice      Additional info about market\r\n     * @dev         Metadata::quoteDecimals is decimals of quote token\r\n     */\r\n    struct Metadata {\r\n        uint8 quoteDecimals;\r\n    }\r\n\r\n    struct DepositInfo {\r\n        uint256 payout_;\r\n        uint256 expiry_;\r\n        uint256 index_;\r\n    }\r\n\r\n    /**\r\n     * @notice deposit market\r\n     * @param _bid uint256\r\n     * @param _amount uint256\r\n     * @param _maxPrice uint256\r\n     * @param _user address\r\n     * @param _referral address\r\n     * @param signature bytes\r\n     * @return depositInfo DepositInfo\r\n     */\r\n    function deposit(\r\n        uint256 _bid,\r\n        uint256 _amount,\r\n        uint256 _maxPrice,\r\n        address _user,\r\n        address _referral,\r\n        bytes calldata signature\r\n    ) external returns (DepositInfo memory depositInfo);\r\n\r\n    /**\r\n     * @notice create market\r\n     * @param _quoteToken IERC20 is the token used to deposit\r\n     * @param _priceFeed address is address of the price consumer, to return the USD value for the quote token when deposits are made\r\n     * @param _market uint256[2] is [capacity, fixed bond price (9 decimals) USD per THEO]\r\n     * @param _booleans bool[2] is [capacity in quote, fixed term]\r\n     * @param _terms uint256[2] is [vesting, conclusion]\r\n     * @return id_ uint256 is ID of the market\r\n     */\r\n    function create(\r\n        IERC20 _quoteToken,\r\n        address _priceFeed,\r\n        uint256[2] memory _market,\r\n        bool[2] memory _booleans,\r\n        uint256[2] memory _terms\r\n    ) external returns (uint256 id_);\r\n\r\n    function close(uint256 _id) external;\r\n\r\n    function isLive(uint256 _bid) external view returns (bool);\r\n\r\n    function liveMarkets() external view returns (uint256[] memory);\r\n\r\n    function liveMarketsFor(address _quoteToken) external view returns (uint256[] memory);\r\n\r\n    function getMarkets() external view returns (uint256[] memory);\r\n\r\n    function getMarketsFor(address _quoteToken) external view returns (uint256[] memory);\r\n\r\n    function calculatePrice(uint256 _bid) external view returns (uint256);\r\n\r\n    function payoutFor(uint256 _amount, uint256 _bid) external view returns (uint256);\r\n}\r\n"
    },
    "src/Libraries/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity >=0.7.5;\r\n\r\nimport { IERC20 } from \"../Interfaces/IERC20.sol\";\r\n\r\n/// @notice Safe IERC20 and ETH transfer library that safely handles missing return values.\r\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol)\r\n/// Taken from Solmate\r\nlibrary SafeERC20 {\r\n    function safeTransferFrom(\r\n        IERC20 token,\r\n        address from,\r\n        address to,\r\n        uint256 amount\r\n    ) internal {\r\n        (bool success, bytes memory data) = address(token).call(\r\n            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)\r\n        );\r\n\r\n        require(success && (data.length == 0 || abi.decode(data, (bool))), \"TRANSFER_FROM_FAILED\");\r\n    }\r\n\r\n    function safeTransfer(\r\n        IERC20 token,\r\n        address to,\r\n        uint256 amount\r\n    ) internal {\r\n        (bool success, bytes memory data) = address(token).call(\r\n            abi.encodeWithSelector(IERC20.transfer.selector, to, amount)\r\n        );\r\n\r\n        require(success && (data.length == 0 || abi.decode(data, (bool))), \"TRANSFER_FAILED\");\r\n    }\r\n\r\n    function safeApprove(\r\n        IERC20 token,\r\n        address to,\r\n        uint256 amount\r\n    ) internal {\r\n        (bool success, bytes memory data) = address(token).call(\r\n            abi.encodeWithSelector(IERC20.approve.selector, to, amount)\r\n        );\r\n\r\n        require(success && (data.length == 0 || abi.decode(data, (bool))), \"APPROVE_FAILED\");\r\n    }\r\n\r\n    function safeTransferETH(address to, uint256 amount) internal {\r\n        (bool success, ) = to.call{ value: amount }(new bytes(0));\r\n\r\n        require(success, \"ETH_TRANSFER_FAILED\");\r\n    }\r\n}\r\n"
    },
    "src/Theopetra/PublicPreListBondDepository.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity ^0.8.10;\r\n\r\nimport \"../Types/NoteKeeper.sol\";\r\nimport \"../Types/Signed.sol\";\r\nimport \"../Types/PriceConsumerV3.sol\";\r\n\r\nimport \"../Libraries/SafeERC20.sol\";\r\n\r\nimport \"../Interfaces/IERC20Metadata.sol\";\r\nimport \"../Interfaces/IWhitelistBondDepository.sol\";\r\n\r\n/**\r\n * @title Theopetra Public Pre-List Bond Depository\r\n * @notice Based off of WhitelistTheopetraBondDepository, with the call to `verifySignature` removed,\r\n *         as well as the function `setWethHelper` and state variable `wethHelper` removed\r\n */\r\n\r\ncontract PublicPreListBondDepository is IWhitelistBondDepository, NoteKeeper, Signed, PriceConsumerV3 {\r\n    /* ======== DEPENDENCIES ======== */\r\n\r\n    using SafeERC20 for IERC20;\r\n\r\n    /* ======== EVENTS ======== */\r\n\r\n    event CreateMarket(\r\n        uint256 indexed id,\r\n        address indexed baseToken,\r\n        address indexed quoteToken,\r\n        uint256 fixedBondPrice\r\n    );\r\n    event CloseMarket(uint256 indexed id);\r\n    event Bond(uint256 indexed id, uint256 amount, uint256 price);\r\n\r\n    /* ======== STATE VARIABLES ======== */\r\n\r\n    // Storage\r\n    Market[] public markets; // persistent market data\r\n    Terms[] public terms; // deposit construction data\r\n    Metadata[] public metadata; // extraneous market data\r\n\r\n    // Queries\r\n    mapping(address => uint256[]) public marketsForQuote; // market IDs for quote token\r\n\r\n    /* ======== CONSTRUCTOR ======== */\r\n\r\n    constructor(\r\n        ITheopetraAuthority _authority,\r\n        IERC20 _theo,\r\n        IStakedTHEOToken _stheo,\r\n        IStaking _staking,\r\n        ITreasury _treasury\r\n    ) NoteKeeper(_authority, _theo, _stheo, _staking, _treasury) {\r\n        // save gas for users by bulk approving stake() transactions\r\n        _theo.approve(address(_staking), 1e45);\r\n    }\r\n\r\n    /* ======== DEPOSIT ======== */\r\n\r\n    /**\r\n     * @notice             deposit quote tokens in exchange for a bond from a specified market\r\n     * @param _id          the ID of the market\r\n     * @param _amount      the amount of quote token to spend\r\n     * @param _maxPrice    the maximum price at which to buy\r\n     * @param _user        the recipient of the payout\r\n     * @param _referral    the front end operator address\r\n     * @return depositInfo DepositInfo\r\n     */\r\n    function deposit(\r\n        uint256 _id,\r\n        uint256 _amount,\r\n        uint256 _maxPrice,\r\n        address _user,\r\n        address _referral,\r\n        bytes calldata signature\r\n    ) external override returns (DepositInfo memory depositInfo) {\r\n        Market storage market = markets[_id];\r\n        Terms memory term = terms[_id];\r\n        uint48 currentTime = uint48(block.timestamp);\r\n\r\n        // Markets end at a defined timestamp\r\n        // |-------------------------------------| t\r\n        require(currentTime < term.conclusion, \"Depository: market concluded\");\r\n\r\n        // Get the price of THEO in quote token terms\r\n        // i.e. the number of quote tokens per THEO\r\n        // With 9 decimal places\r\n        uint256 price = calculatePrice(_id);\r\n\r\n        // Users input a maximum price, which protects them from price changes after\r\n        // entering the mempool. max price is a slippage mitigation measure\r\n        require(price <= _maxPrice, \"Depository: more than max price\");\r\n\r\n        /**\r\n         * payout for the deposit = amount / price\r\n         *\r\n         * where\r\n         * payout = THEO out, in THEO decimals (9)\r\n         * amount = quote tokens in\r\n         * price = quote tokens per THEO, in THEO decimals (9)\r\n         *\r\n         * 1e18 = THEO decimals (9) + price decimals (9)\r\n         */\r\n        depositInfo.payout_ = ((_amount * 1e18) / price) / (10**metadata[_id].quoteDecimals);\r\n\r\n        /*\r\n         * each market is initialized with a capacity\r\n         *\r\n         * this is either the number of THEO that the market can sell\r\n         * (if capacity in quote is false),\r\n         *\r\n         * or the number of quote tokens that the market can buy\r\n         * (if capacity in quote is true)\r\n         */\r\n\r\n        require(\r\n            market.capacity >= (market.capacityInQuote ? _amount : depositInfo.payout_),\r\n            \"Depository: capacity exceeded\"\r\n        );\r\n\r\n        market.capacity -= market.capacityInQuote ? _amount : depositInfo.payout_;\r\n\r\n        if (market.capacity == 0) {\r\n            emit CloseMarket(_id);\r\n        }\r\n\r\n        /**\r\n         * bonds mature with a cliff at a set timestamp\r\n         * prior to the expiry timestamp, no payout tokens are accessible to the user\r\n         * after the expiry timestamp, the entire payout can be redeemed\r\n         *\r\n         * there are two types of bonds: fixed-term and fixed-expiration\r\n         *\r\n         * fixed-term bonds mature in a set amount of time from deposit\r\n         * i.e. term = 1 week. when alice deposits on day 1, her bond\r\n         * expires on day 8. when bob deposits on day 2, his bond expires day 9.\r\n         *\r\n         * fixed-expiration bonds mature at a set timestamp\r\n         * i.e. expiration = day 10. when alice deposits on day 1, her term\r\n         * is 9 days. when bob deposits on day 2, his term is 8 days.\r\n         */\r\n        depositInfo.expiry_ = term.fixedTerm ? term.vesting + currentTime : term.vesting;\r\n\r\n        // markets keep track of how many quote tokens have been\r\n        // purchased, and how much THEO has been sold\r\n        market.purchased += _amount;\r\n        market.sold += uint64(depositInfo.payout_);\r\n\r\n        emit Bond(_id, _amount, price);\r\n\r\n        /**\r\n         * user data is stored as Notes. these are isolated array entries\r\n         * storing the amount due, the time created, the time when payout\r\n         * is redeemable, the time when payout was redeemed, and the ID\r\n         * of the market deposited into\r\n         */\r\n        depositInfo.index_ = addNote(\r\n            _user,\r\n            depositInfo.payout_,\r\n            uint48(depositInfo.expiry_),\r\n            uint48(_id),\r\n            _referral,\r\n            0,\r\n            false\r\n        );\r\n\r\n        // transfer payment to treasury\r\n        market.quoteToken.safeTransferFrom(msg.sender, address(treasury), _amount);\r\n    }\r\n\r\n    /* ======== CREATE ======== */\r\n\r\n    /**\r\n     * @notice             creates a new market type\r\n     * @dev                current price should be in 9 decimals.\r\n     * @param _quoteToken  token used to deposit\r\n     * @param _market      [capacity (in THEO or quote), fixed bond price (9 decimals) USD per THEO]\r\n     * @param _booleans    [capacity in quote, fixed term]\r\n     * @param _terms       [vesting length (if fixed term) or vested timestamp, conclusion timestamp]\r\n     * @param _priceFeed   address of the price consumer, to return the USD value for the quote token when deposits are made\r\n     * @return id_         ID of new bond market\r\n     */\r\n    function create(\r\n        IERC20 _quoteToken,\r\n        address _priceFeed,\r\n        uint256[2] memory _market,\r\n        bool[2] memory _booleans,\r\n        uint256[2] memory _terms\r\n    ) external override onlyPolicy returns (uint256 id_) {\r\n        // the decimal count of the quote token\r\n        uint256 decimals = IERC20Metadata(address(_quoteToken)).decimals();\r\n\r\n        // depositing into, or getting info for, the created market uses this ID\r\n        id_ = markets.length;\r\n\r\n        markets.push(\r\n            Market({\r\n                quoteToken: _quoteToken,\r\n                priceFeed: _priceFeed,\r\n                capacityInQuote: _booleans[0],\r\n                capacity: _market[0],\r\n                purchased: 0,\r\n                sold: 0,\r\n                usdPricePerTHEO: _market[1]\r\n            })\r\n        );\r\n\r\n        terms.push(Terms({ fixedTerm: _booleans[1], vesting: uint48(_terms[0]), conclusion: uint48(_terms[1]) }));\r\n\r\n        metadata.push(Metadata({ quoteDecimals: uint8(decimals) }));\r\n\r\n        marketsForQuote[address(_quoteToken)].push(id_);\r\n\r\n        emit CreateMarket(id_, address(theo), address(_quoteToken), _market[1]);\r\n    }\r\n\r\n    /**\r\n     * @notice             disable existing market\r\n     * @param _id          ID of market to close\r\n     */\r\n    function close(uint256 _id) external override onlyPolicy {\r\n        terms[_id].conclusion = uint48(block.timestamp);\r\n        markets[_id].capacity = 0;\r\n        emit CloseMarket(_id);\r\n    }\r\n\r\n    /* ======== EXTERNAL VIEW ======== */\r\n\r\n    /**\r\n     * @notice             payout due for amount of quote tokens\r\n     * @param _amount      amount of quote tokens to spend\r\n     * @param _id          ID of market\r\n     * @return             amount of THEO to be paid in THEO decimals\r\n     *\r\n     * @dev 1e18 = theo decimals (9) + fixed bond price decimals (9)\r\n     */\r\n    function payoutFor(uint256 _amount, uint256 _id) external view override returns (uint256) {\r\n        Metadata memory meta = metadata[_id];\r\n        return (_amount * 1e18) / calculatePrice(_id) / 10**meta.quoteDecimals;\r\n    }\r\n\r\n    /**\r\n     * @notice             is a given market accepting deposits\r\n     * @param _id          ID of market\r\n     */\r\n    function isLive(uint256 _id) public view override returns (bool) {\r\n        return (markets[_id].capacity != 0 && terms[_id].conclusion > block.timestamp);\r\n    }\r\n\r\n    /**\r\n     * @notice returns an array of all active market IDs\r\n     */\r\n    function liveMarkets() external view override returns (uint256[] memory) {\r\n        uint256 num;\r\n        for (uint256 i = 0; i < markets.length; i++) {\r\n            if (isLive(i)) num++;\r\n        }\r\n\r\n        uint256[] memory ids = new uint256[](num);\r\n        uint256 nonce;\r\n        for (uint256 i = 0; i < markets.length; i++) {\r\n            if (isLive(i)) {\r\n                ids[nonce] = i;\r\n                nonce++;\r\n            }\r\n        }\r\n        return ids;\r\n    }\r\n\r\n    /**\r\n     * @notice             returns an array of all active market IDs for a given quote token\r\n     * @param _token       quote token to check for\r\n     */\r\n    function liveMarketsFor(address _token) external view override returns (uint256[] memory) {\r\n        uint256[] memory mkts = marketsForQuote[_token];\r\n        uint256 num;\r\n\r\n        for (uint256 i = 0; i < mkts.length; i++) {\r\n            if (isLive(mkts[i])) num++;\r\n        }\r\n\r\n        uint256[] memory ids = new uint256[](num);\r\n        uint256 nonce;\r\n\r\n        for (uint256 i = 0; i < mkts.length; i++) {\r\n            if (isLive(mkts[i])) {\r\n                ids[nonce] = mkts[i];\r\n                nonce++;\r\n            }\r\n        }\r\n        return ids;\r\n    }\r\n\r\n    /**\r\n     * @notice returns an array of market IDs for historical analysis\r\n     */\r\n    function getMarkets() external view override returns (uint256[] memory) {\r\n        uint256[] memory ids = new uint256[](markets.length);\r\n        for (uint256 i = 0; i < markets.length; i++) {\r\n                ids[i] = i;\r\n        }\r\n        return ids;\r\n    }\r\n\r\n    /**\r\n     * @notice             returns an array of all market IDs for a given quote token\r\n     * @param _token       quote token to check for\r\n     */\r\n    function getMarketsFor(address _token) external view override returns (uint256[] memory) {\r\n        uint256[] memory mkts = marketsForQuote[_token];\r\n        uint256[] memory ids = new uint256[](mkts.length);\r\n\r\n        for (uint256 i = 0; i < mkts.length; i++) {\r\n            ids[i] = mkts[i];\r\n        }\r\n        return ids;\r\n    }\r\n\r\n    /**\r\n     * @notice                  calculate the price of THEO in quote token terms; i.e. the number of quote tokens per THEO\r\n     * @dev                     get the latest price for the market's quote token in USD\r\n     *                          (`priceConsumerPrice`, with decimals `priceConsumerDecimals`)\r\n     *                          then `scalePrice` to scale the fixed bond price to THEO decimals when calculating `price`.\r\n     *                          finally, calculate `price` as quote tokens per THEO, in THEO decimals (9)\r\n     * @param _id               market ID\r\n     * @return                  uint256 price of THEO in quote token terms, in THEO decimals (9)\r\n     */\r\n    function calculatePrice(uint256 _id) public view override returns (uint256) {\r\n        (int256 priceConsumerPrice, uint8 priceConsumerDecimals) = getLatestPrice(markets[_id].priceFeed);\r\n\r\n        int256 scaledPrice = scalePrice(int256(markets[_id].usdPricePerTHEO), 9, 9 + priceConsumerDecimals);\r\n\r\n        uint256 price = uint256(scaledPrice / priceConsumerPrice);\r\n        return price;\r\n    }\r\n\r\n    /* ======== INTERNAL PURE ======== */\r\n\r\n    /**\r\n     * @param _price            fixed bond price (USD per THEO), 9 decimals\r\n     * @param _priceDecimals    decimals (9) used for the fixed bond price\r\n     * @param _decimals         sum of decimals for THEO token (9) + decimals for the price feed\r\n     */\r\n    function scalePrice(\r\n        int256 _price,\r\n        uint8 _priceDecimals,\r\n        uint8 _decimals\r\n    ) internal pure returns (int256) {\r\n        if (_priceDecimals < _decimals) {\r\n            return _price * int256(10**uint256(_decimals - _priceDecimals));\r\n        } else if (_priceDecimals > _decimals) {\r\n            return _price / int256(10**uint256(_priceDecimals - _decimals));\r\n        }\r\n        return _price;\r\n    }\r\n}\r\n"
    },
    "src/Types/FrontEndRewarder.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity ^0.8.10;\r\n\r\nimport \"../Types/TheopetraAccessControlled.sol\";\r\nimport \"../Interfaces/IERC20.sol\";\r\n\r\nabstract contract FrontEndRewarder is TheopetraAccessControlled {\r\n    /* ========= STATE VARIABLES ========== */\r\n\r\n    uint256 public daoReward; // % reward for dao (3 decimals: 100 = 1%)\r\n    uint256 public refReward; // % reward for referrer (3 decimals: 100 = 1%)\r\n    mapping(address => uint256) public rewards; // front end operator rewards\r\n    mapping(address => bool) public whitelisted; // whitelisted status for operators\r\n\r\n    IERC20 internal immutable theo; // reward token\r\n\r\n    event SetRewards(uint256 toRef, uint256 toDao);\r\n    constructor(ITheopetraAuthority _authority, IERC20 _theo) TheopetraAccessControlled(_authority) {\r\n        theo = _theo;\r\n    }\r\n\r\n    /* ========= EXTERNAL FUNCTIONS ========== */\r\n\r\n    // pay reward to front end operator\r\n    function getReward() external {\r\n        uint256 reward = rewards[msg.sender];\r\n\r\n        rewards[msg.sender] = 0;\r\n        theo.transfer(msg.sender, reward);\r\n    }\r\n\r\n    /* ========= INTERNAL ========== */\r\n\r\n    /**\r\n     * @notice add new market payout to user data\r\n     */\r\n    function _giveRewards(uint256 _payout, address _referral) internal returns (uint256) {\r\n        // first we calculate rewards paid to the DAO and to the front end operator (referrer)\r\n        uint256 toDAO = (_payout * daoReward) / 1e4;\r\n        uint256 toRef = (_payout * refReward) / 1e4;\r\n\r\n        // and store them in our rewards mapping\r\n        if (whitelisted[_referral]) {\r\n            rewards[_referral] += toRef;\r\n            rewards[authority.guardian()] += toDAO;\r\n        } else {\r\n            // the DAO receives both rewards if referrer is not whitelisted\r\n            rewards[authority.guardian()] += toDAO + toRef;\r\n        }\r\n        return toDAO + toRef;\r\n    }\r\n\r\n    /**\r\n     * @notice set rewards for front end operators and DAO\r\n     */\r\n    function setRewards(uint256 _toFrontEnd, uint256 _toDAO) external onlyGovernor {\r\n        refReward = _toFrontEnd;\r\n        daoReward = _toDAO;\r\n\r\n        emit SetRewards(_toFrontEnd, _toDAO);\r\n    }\r\n\r\n    /**\r\n     * @notice add or remove addresses from the reward whitelist\r\n     */\r\n    function whitelist(address _operator) external onlyPolicy {\r\n        whitelisted[_operator] = !whitelisted[_operator];\r\n    }\r\n}\r\n"
    },
    "src/Types/NoteKeeper.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity ^0.8.10;\r\n\r\nimport \"./FrontEndRewarder.sol\";\r\n\r\nimport \"../Interfaces/IStakedTHEOToken.sol\";\r\nimport \"../Interfaces/IStaking.sol\";\r\nimport \"../Interfaces/ITreasury.sol\";\r\nimport \"../Interfaces/INoteKeeper.sol\";\r\n\r\nabstract contract NoteKeeper is INoteKeeper, FrontEndRewarder {\r\n    mapping(address => Note[]) public notes; // user deposit data\r\n    mapping(address => mapping(uint256 => address)) private noteTransfers; // change note ownership\r\n    mapping(address => mapping(uint256 => uint256)) private noteForClaim; // index of staking claim for a user's note\r\n\r\n    event TreasuryUpdated(address addr);\r\n    event PushNote(address from, address to, uint256 noteId);\r\n    event PullNote(address from, address to, uint256 noteId);\r\n\r\n    IStakedTHEOToken internal immutable sTHEO;\r\n    IStaking internal immutable staking;\r\n    ITreasury internal treasury;\r\n\r\n    constructor(\r\n        ITheopetraAuthority _authority,\r\n        IERC20 _theo,\r\n        IStakedTHEOToken _stheo,\r\n        IStaking _staking,\r\n        ITreasury _treasury\r\n    ) FrontEndRewarder(_authority, _theo) {\r\n        sTHEO = _stheo;\r\n        staking = _staking;\r\n        treasury = _treasury;\r\n    }\r\n\r\n    // if treasury address changes on authority, update it\r\n    function updateTreasury() external {\r\n        require(\r\n            msg.sender == authority.governor() ||\r\n                msg.sender == authority.guardian() ||\r\n                msg.sender == authority.policy(),\r\n            \"Only authorized\"\r\n        );\r\n        address treasuryAddress = authority.vault();\r\n        treasury = ITreasury(treasuryAddress);\r\n        emit TreasuryUpdated(treasuryAddress);\r\n    }\r\n\r\n    /* ========== ADD ========== */\r\n\r\n    /**\r\n     * @notice             adds a new Note for a user, stores the front end & DAO rewards, and mints & stakes payout & rewards\r\n     * @param _user        the user that owns the Note\r\n     * @param _payout      the amount of THEO due to the user\r\n     * @param _expiry      the timestamp when the Note is redeemable\r\n     * @param _marketID    the ID of the market deposited into\r\n     * @param _discount    the discount on the bond (that is, the bond rate, variable). This is a proportion (that is, a percentage in its decimal form), with 9 decimals\r\n     * @return index_      the index of the Note in the user's array\r\n     */\r\n    function addNote(\r\n        address _user,\r\n        uint256 _payout,\r\n        uint48 _expiry,\r\n        uint48 _marketID,\r\n        address _referral,\r\n        uint48 _discount,\r\n        bool _autoStake\r\n    ) internal returns (uint256 index_) {\r\n        // the index of the note is the next in the user's array\r\n        index_ = notes[_user].length;\r\n\r\n        // the new note is pushed to the user's array\r\n        notes[_user].push(\r\n            Note({\r\n                payout: _payout,\r\n                created: uint48(block.timestamp),\r\n                matured: _expiry,\r\n                redeemed: 0,\r\n                marketID: _marketID,\r\n                discount: _discount,\r\n                autoStake: _autoStake\r\n            })\r\n        );\r\n\r\n        // front end operators can earn rewards by referring users\r\n        uint256 rewards = _giveRewards(_payout, _referral);\r\n\r\n        // mint and stake payout\r\n        treasury.mint(address(this), _payout + rewards);\r\n\r\n        if (_autoStake) {\r\n            // note that only the payout gets staked (front end rewards are in THEO)\r\n            // Get index for the claim to approve for pushing\r\n            (, uint256 claimIndex) = staking.stake(address(this), _payout, true);\r\n            // approve the user to transfer the staking claim\r\n            staking.pushClaim(_user, claimIndex);\r\n\r\n            // Map the index of the user's note to the claimIndex\r\n            noteForClaim[_user][index_] = claimIndex;\r\n        }\r\n    }\r\n\r\n    /* ========== REDEEM ========== */\r\n\r\n    /**\r\n     * @notice             redeem notes for user\r\n     * @dev                adapted from Olympus V2. Olympus V2 either sends payout as gOHM\r\n     *                     or calls an `unwrap` function on the staking contract\r\n     *                     to convert the payout from gOHM into sOHM and then send as sOHM.\r\n     *                     This current contract sends payout as sTHEO.\r\n     * @param _user        the user to redeem for\r\n     * @param _indexes     the note indexes to redeem\r\n     * @return payout_     sum of payout sent, in sTHEO\r\n     */\r\n    function redeem(address _user, uint256[] memory _indexes) public override returns (uint256 payout_) {\r\n        uint48 time = uint48(block.timestamp);\r\n        uint256 sTheoPayout = 0;\r\n        uint256 theoPayout = 0;\r\n\r\n        for (uint256 i = 0; i < _indexes.length; i++) {\r\n            (uint256 pay, , , , bool matured, ) = pendingFor(_user, _indexes[i]);\r\n\r\n            if (matured) {\r\n                notes[_user][_indexes[i]].redeemed = time; // mark as redeemed\r\n                payout_ += pay;\r\n                if (notes[_user][_indexes[i]].autoStake) {\r\n                    uint256 _claimIndex = noteForClaim[_user][_indexes[i]];\r\n                    staking.pushClaimForBond(_user, _claimIndex);\r\n                    sTheoPayout += pay;\r\n                } else {\r\n                    theoPayout += pay;\r\n                }\r\n            }\r\n        }\r\n        if (theoPayout > 0) theo.transfer(_user, theoPayout);\r\n        if (sTheoPayout > 0) sTHEO.transfer(_user, sTheoPayout);\r\n    }\r\n\r\n    /**\r\n     * @notice             redeem all redeemable markets for user\r\n     * @dev                if possible, query indexesFor() off-chain and input in redeem() to save gas\r\n     * @param _user        user to redeem all notes for\r\n     * @return             sum of payout sent, in sTHEO\r\n     */\r\n    function redeemAll(address _user) external override returns (uint256) {\r\n        return redeem(_user, indexesFor(_user));\r\n    }\r\n\r\n    /* ========== TRANSFER ========== */\r\n\r\n    /**\r\n     * @notice             approve an address to transfer a note\r\n     * @param _to          address to approve note transfer for\r\n     * @param _index       index of note to approve transfer for\r\n     */\r\n    function pushNote(address _to, uint256 _index) external override {\r\n        require(notes[msg.sender][_index].created != 0, \"Depository: note not found\");\r\n        noteTransfers[msg.sender][_index] = _to;\r\n\r\n        emit PushNote(msg.sender, _to, _index);\r\n    }\r\n\r\n    /**\r\n     * @notice             transfer a note that has been approved by an address\r\n     * @dev                if the note being pulled is autostaked then update noteForClaim as follows:\r\n     *                     get the relevant `claimIndex` associated with the note that is being pulled.\r\n     *                     Then add the claimIndex to the recipient's noteForClaim.\r\n     *                     After updating noteForClaim, the staking claim is pushed to the recipient, in order to\r\n     *                     update `claimTransfers` in the Staking contract and thereby change claim ownership (from the note's pusher to the note's recipient)\r\n     * @param _from        the address that approved the note transfer\r\n     * @param _index       the index of the note to transfer (in the sender's array)\r\n     */\r\n    function pullNote(address _from, uint256 _index) external override returns (uint256 newIndex_) {\r\n        require(noteTransfers[_from][_index] == msg.sender, \"Depository: transfer not found\");\r\n        require(notes[_from][_index].redeemed == 0, \"Depository: note redeemed\");\r\n\r\n        newIndex_ = notes[msg.sender].length;\r\n\r\n        if (notes[_from][_index].autoStake) {\r\n            uint256 claimIndex = noteForClaim[_from][_index];\r\n            noteForClaim[msg.sender][newIndex_] = claimIndex;\r\n            staking.pushClaim(msg.sender, claimIndex);\r\n        }\r\n        notes[msg.sender].push(notes[_from][_index]);\r\n\r\n        delete notes[_from][_index];\r\n        emit PullNote(_from, msg.sender, _index);\r\n    }\r\n\r\n    /* ========== VIEW ========== */\r\n\r\n    // Note info\r\n\r\n    /**\r\n     * @notice             all pending notes for user\r\n     * @param _user        the user to query notes for\r\n     * @return             the pending notes for the user\r\n     */\r\n    function indexesFor(address _user) public view override returns (uint256[] memory) {\r\n        Note[] memory info = notes[_user];\r\n\r\n        uint256 length;\r\n        for (uint256 i = 0; i < info.length; i++) {\r\n            if (info[i].redeemed == 0 && info[i].payout != 0) length++;\r\n        }\r\n\r\n        uint256[] memory indexes = new uint256[](length);\r\n        uint256 position;\r\n\r\n        for (uint256 i = 0; i < info.length; i++) {\r\n            if (info[i].redeemed == 0 && info[i].payout != 0) {\r\n                indexes[position] = i;\r\n                position++;\r\n            }\r\n        }\r\n\r\n        return indexes;\r\n    }\r\n\r\n    /**\r\n     * @notice                  calculate amount available for claim for a single note\r\n     * @param _user             the user that the note belongs to\r\n     * @param _index            the index of the note in the user's array\r\n     * @return payout_          the payout due, in sTHEO\r\n     * @return created_         the time the note was created\r\n     * @return expiry_          the time the note is redeemable\r\n     * @return timeRemaining_   the time remaining until the note is matured\r\n     * @return matured_         if the payout can be redeemed\r\n     */\r\n    function pendingFor(address _user, uint256 _index)\r\n        public\r\n        view\r\n        override\r\n        returns (\r\n            uint256 payout_,\r\n            uint48 created_,\r\n            uint48 expiry_,\r\n            uint48 timeRemaining_,\r\n            bool matured_,\r\n            uint48 discount_\r\n        )\r\n    {\r\n        Note memory note = notes[_user][_index];\r\n\r\n        payout_ = note.payout;\r\n        created_ = note.created;\r\n        expiry_ = note.matured;\r\n        timeRemaining_ = note.matured > block.timestamp ? uint48(note.matured - block.timestamp) : 0;\r\n        matured_ = note.redeemed == 0 && note.matured <= block.timestamp && note.payout != 0;\r\n        discount_ = note.discount;\r\n    }\r\n\r\n    function getNotesCount(address _user) external view returns (uint256) {\r\n        return notes[_user].length;\r\n    }\r\n}\r\n"
    },
    "src/Types/PriceConsumerV3.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\r\n\r\ncontract PriceConsumerV3 {\r\n    /**\r\n     * Returns the latest price\r\n     */\r\n    function getLatestPrice(address priceFeedAddress) public view returns (int256, uint8) {\r\n        (\r\n            uint80 roundID,\r\n            int256 price,\r\n            uint256 startedAt,\r\n            uint256 timeStamp,\r\n            uint80 answeredInRound\r\n        ) = AggregatorV3Interface(priceFeedAddress).latestRoundData();\r\n\r\n        uint8 decimals = AggregatorV3Interface(priceFeedAddress).decimals();\r\n\r\n        return (price, decimals);\r\n    }\r\n}\r\n"
    },
    "src/Types/Signed.sol": {
      "content": "// SPDX-License-Identifier: BSD-3\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\r\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\r\n\r\nimport \"./TheopetraAccessControlled.sol\";\r\n\r\nabstract contract Signed is TheopetraAccessControlled {\r\n    using Strings for uint256;\r\n    using ECDSA for bytes32;\r\n\r\n    string private _secret;\r\n\r\n    event SetSecret(string secret);\r\n\r\n    function setSecret(string calldata secret) external onlyGovernor {\r\n        _secret = secret;\r\n        emit SetSecret(secret);\r\n    }\r\n\r\n    function createHash(string memory data) internal view returns (bytes32) {\r\n        return keccak256(abi.encodePacked(address(this), msg.sender, data, _secret));\r\n    }\r\n\r\n    function getSigner(bytes32 hash, bytes memory signature) internal pure returns (address) {\r\n        return hash.toEthSignedMessageHash().recover(signature);\r\n    }\r\n\r\n    function isAuthorizedSigner(address extracted) internal view virtual returns (bool) {\r\n        return extracted == authority.whitelistSigner();\r\n    }\r\n\r\n    function verifySignature(string memory data, bytes calldata signature) internal view {\r\n        address extracted = getSigner(createHash(data), signature);\r\n        require(isAuthorizedSigner(extracted), \"Signature verification failed\");\r\n    }\r\n}\r\n"
    },
    "src/Types/TheopetraAccessControlled.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity >=0.7.5;\r\n\r\nimport \"../Interfaces/ITheopetraAuthority.sol\";\r\n\r\nabstract contract TheopetraAccessControlled {\r\n    /* ========== EVENTS ========== */\r\n\r\n    event AuthorityUpdated(ITheopetraAuthority indexed authority);\r\n\r\n    string constant UNAUTHORIZED = \"UNAUTHORIZED\"; // save gas\r\n\r\n    /* ========== STATE VARIABLES ========== */\r\n\r\n    ITheopetraAuthority public authority;\r\n\r\n    /* ========== Constructor ========== */\r\n\r\n    constructor(ITheopetraAuthority _authority) {\r\n        authority = _authority;\r\n        emit AuthorityUpdated(_authority);\r\n    }\r\n\r\n    /* ========== MODIFIERS ========== */\r\n\r\n    modifier onlyGovernor() {\r\n        require(msg.sender == authority.governor(), UNAUTHORIZED);\r\n        _;\r\n    }\r\n\r\n    modifier onlyGuardian() {\r\n        require(msg.sender == authority.guardian(), UNAUTHORIZED);\r\n        _;\r\n    }\r\n\r\n    modifier onlyPolicy() {\r\n        require(msg.sender == authority.policy(), UNAUTHORIZED);\r\n        _;\r\n    }\r\n\r\n    modifier onlyManager() {\r\n        require(msg.sender == authority.manager(), UNAUTHORIZED);\r\n        _;\r\n    }\r\n\r\n    modifier onlyVault() {\r\n        require(msg.sender == authority.vault(), UNAUTHORIZED);\r\n        _;\r\n    }\r\n\r\n    /* ========== GOV ONLY ========== */\r\n\r\n    function setAuthority(ITheopetraAuthority _newAuthority) external onlyGovernor {\r\n        authority = _newAuthority;\r\n        emit AuthorityUpdated(_newAuthority);\r\n    }\r\n}\r\n"
    }
  }
}