zellic-audit
Initial commit
f998fcd
raw
history blame
47.7 kB
{
"language": "Solidity",
"sources": {
"contracts/13_BlackDAOBondDepositoryV2.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-or-later\r\npragma solidity ^0.8.10;\r\n\r\nimport \"./types/NoteKeeper.sol\";\r\n\r\nimport \"./libraries/SafeERC20.sol\";\r\n\r\nimport \"./interfaces/IERC20Metadata.sol\";\r\nimport \"./interfaces/IBondDepository.sol\";\r\n\r\n/// @title BlackDAO Bond Depository V2\r\n/// @author Sheikh\r\n/// Review by: Kashmiri\r\n\r\ncontract BlackDAOBondDepositoryV2 is IBondDepository, NoteKeeper {\r\n /* ======== DEPENDENCIES ======== */\r\n\r\n using SafeERC20 for IERC20;\r\n\r\n /* ======== EVENTS ======== */\r\n\r\n event CreateMarket(uint256 indexed id, address indexed baseToken, address indexed quoteToken, uint256 initialPrice);\r\n event CloseMarket(uint256 indexed id);\r\n event Bond(uint256 indexed id, uint256 amount, uint256 price);\r\n event Tuned(uint256 indexed id, uint64 oldControlVariable, uint64 newControlVariable);\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 mapping(uint256 => Adjustment) public adjustments; // control variable changes\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 IBlackDAOAuthority _authority,\r\n IERC20 _blkd,\r\n IgBLKD _gblkd,\r\n IStaking _staking,\r\n ITreasury _treasury\r\n ) NoteKeeper(_authority, _blkd, _gblkd, _staking, _treasury) {\r\n // save gas for users by bulk approving stake() transactions\r\n _blkd.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 payout_ the amount of gBLKD due\r\n * @return expiry_ the timestamp at which payout is redeemable\r\n * @return index_ the user index of the Note (used to redeem or query information)\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 )\r\n external\r\n override\r\n returns (\r\n uint256 payout_,\r\n uint256 expiry_,\r\n uint256 index_\r\n )\r\n {\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 // Debt and the control variable decay over time\r\n _decay(_id, currentTime);\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 uint256 price = _marketPrice(_id);\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 = BLKD out\r\n * amount = quote tokens in\r\n * price = quote tokens : blkd (i.e. 42069 DAI : BLKD)\r\n *\r\n * 1e18 = BLKD decimals (9) + price decimals (9)\r\n */\r\n payout_ = ((_amount * 1e18) / price) / (10**metadata[_id].quoteDecimals);\r\n\r\n // markets have a max payout amount, capping size because deposits\r\n // do not experience slippage. max payout is recalculated upon tuning\r\n require(payout_ <= market.maxPayout, \"Depository: max size exceeded\");\r\n\r\n /*\r\n * each market is initialized with a capacity\r\n *\r\n * this is either the number of BLKD 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 market.capacity -= market.capacityInQuote ? _amount : payout_;\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 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 BLKD has been sold\r\n market.purchased += _amount;\r\n market.sold += uint64(payout_);\r\n\r\n // incrementing total debt raises the price of the next bond\r\n market.totalDebt += uint64(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 index_ = addNote(_user, payout_, uint48(expiry_), uint48(_id), _referral);\r\n\r\n // transfer payment to treasury\r\n market.quoteToken.safeTransferFrom(msg.sender, address(treasury), _amount);\r\n\r\n // if max debt is breached, the market is closed\r\n // this a circuit breaker\r\n if (term.maxDebt < market.totalDebt) {\r\n market.capacity = 0;\r\n emit CloseMarket(_id);\r\n } else {\r\n // if market will continue, the control variable is tuned to hit targets on time\r\n _tune(_id, currentTime);\r\n }\r\n }\r\n\r\n /**\r\n * @notice decay debt, and adjust control variable if there is an active change\r\n * @param _id ID of market\r\n * @param _time uint48 timestamp (saves gas when passed in)\r\n */\r\n function _decay(uint256 _id, uint48 _time) internal {\r\n // Debt decay\r\n\r\n /*\r\n * Debt is a time-decayed sum of tokens spent in a market\r\n * Debt is added when deposits occur and removed over time\r\n * |\r\n * | debt falls with\r\n * | / \\ inactivity / \\\r\n * | / \\ /\\/ \\\r\n * | \\ / \\\r\n * | \\ /\\/ \\\r\n * | \\ / and rises \\\r\n * | with deposits\r\n * |\r\n * |------------------------------------| t\r\n */\r\n markets[_id].totalDebt -= debtDecay(_id);\r\n metadata[_id].lastDecay = _time;\r\n\r\n // Control variable decay\r\n\r\n // The bond control variable is continually tuned. When it is lowered (which\r\n // lowers the market price), the change is carried out smoothly over time.\r\n if (adjustments[_id].active) {\r\n Adjustment storage adjustment = adjustments[_id];\r\n\r\n (uint64 adjustBy, uint48 secondsSince, bool stillActive) = _controlDecay(_id);\r\n terms[_id].controlVariable -= adjustBy;\r\n\r\n if (stillActive) {\r\n adjustment.change -= adjustBy;\r\n adjustment.timeToAdjusted -= secondsSince;\r\n adjustment.lastAdjustment = _time;\r\n } else {\r\n adjustment.active = false;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @notice auto-adjust control variable to hit capacity/spend target\r\n * @param _id ID of market\r\n * @param _time uint48 timestamp (saves gas when passed in)\r\n */\r\n function _tune(uint256 _id, uint48 _time) internal {\r\n Metadata memory meta = metadata[_id];\r\n\r\n if (_time >= meta.lastTune + meta.tuneInterval) {\r\n Market memory market = markets[_id];\r\n\r\n // compute seconds remaining until market will conclude\r\n uint256 timeRemaining = terms[_id].conclusion - _time;\r\n uint256 price = _marketPrice(_id);\r\n\r\n // standardize capacity into an base token amount\r\n // blkd decimals (9) + price decimals (9)\r\n uint256 capacity = market.capacityInQuote\r\n ? ((market.capacity * 1e18) / price) / (10**meta.quoteDecimals)\r\n : market.capacity;\r\n\r\n /**\r\n * calculate the correct payout to complete on time assuming each bond\r\n * will be max size in the desired deposit interval for the remaining time\r\n *\r\n * i.e. market has 10 days remaining. deposit interval is 1 day. capacity\r\n * is 10,000 BLKD. max payout would be 1,000 BLKD (10,000 * 1 / 10).\r\n */\r\n markets[_id].maxPayout = uint64((capacity * meta.depositInterval) / timeRemaining);\r\n\r\n // calculate the ideal total debt to satisfy capacity in the remaining time\r\n uint256 targetDebt = (capacity * meta.length) / timeRemaining;\r\n\r\n // derive a new control variable from the target debt and current supply\r\n uint64 newControlVariable = uint64((price * treasury.baseSupply()) / targetDebt);\r\n\r\n emit Tuned(_id, terms[_id].controlVariable, newControlVariable);\r\n\r\n if (newControlVariable >= terms[_id].controlVariable) {\r\n terms[_id].controlVariable = newControlVariable;\r\n } else {\r\n // if decrease, control variable change will be carried out over the tune interval\r\n // this is because price will be lowered\r\n uint64 change = terms[_id].controlVariable - newControlVariable;\r\n adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true);\r\n }\r\n metadata[_id].lastTune = _time;\r\n }\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 BLKD or quote), initial price / BLKD (9 decimals), debt buffer (3 decimals)]\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 _intervals [deposit interval (seconds), tune interval (seconds)]\r\n * @return id_ ID of new bond market\r\n */\r\n function create(\r\n IERC20 _quoteToken,\r\n uint256[3] memory _market,\r\n bool[2] memory _booleans,\r\n uint256[2] memory _terms,\r\n uint32[2] memory _intervals\r\n ) external override onlyPolicy returns (uint256 id_) {\r\n // the length of the program, in seconds\r\n uint256 secondsToConclusion = _terms[1] - block.timestamp;\r\n\r\n // the decimal count of the quote token\r\n uint256 decimals = IERC20Metadata(address(_quoteToken)).decimals();\r\n\r\n /*\r\n * initial target debt is equal to capacity (this is the amount of debt\r\n * that will decay over in the length of the program if price remains the same).\r\n * it is converted into base token terms if passed in in quote token terms.\r\n *\r\n * 1e18 = blkd decimals (9) + initial price decimals (9)\r\n */\r\n uint64 targetDebt = uint64(_booleans[0] ? ((_market[0] * 1e18) / _market[1]) / 10**decimals : _market[0]);\r\n\r\n /*\r\n * max payout is the amount of capacity that should be utilized in a deposit\r\n * interval. for example, if capacity is 1,000 BLKD, there are 10 days to conclusion,\r\n * and the preferred deposit interval is 1 day, max payout would be 100 BLKD.\r\n */\r\n uint64 maxPayout = uint64((targetDebt * _intervals[0]) / secondsToConclusion);\r\n\r\n /*\r\n * max debt serves as a circuit breaker for the market. let's say the quote\r\n * token is a stablecoin, and that stablecoin depegs. without max debt, the\r\n * market would continue to buy until it runs out of capacity. this is\r\n * configurable with a 3 decimal buffer (1000 = 1% above initial price).\r\n * note that its likely advisable to keep this buffer wide.\r\n * note that the buffer is above 100%. i.e. 10% buffer = initial debt * 1.1\r\n */\r\n uint256 maxDebt = targetDebt + ((targetDebt * _market[2]) / 1e5); // 1e5 = 100,000. 10,000 / 100,000 = 10%.\r\n\r\n /*\r\n * the control variable is set so that initial price equals the desired\r\n * initial price. the control variable is the ultimate determinant of price,\r\n * so we compute this last.\r\n *\r\n * price = control variable * debt ratio\r\n * debt ratio = total debt / supply\r\n * therefore, control variable = price / debt ratio\r\n */\r\n uint256 controlVariable = (_market[1] * treasury.baseSupply()) / targetDebt;\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 capacityInQuote: _booleans[0],\r\n capacity: _market[0],\r\n totalDebt: targetDebt,\r\n maxPayout: maxPayout,\r\n purchased: 0,\r\n sold: 0\r\n })\r\n );\r\n\r\n terms.push(\r\n Terms({\r\n fixedTerm: _booleans[1],\r\n controlVariable: uint64(controlVariable),\r\n vesting: uint48(_terms[0]),\r\n conclusion: uint48(_terms[1]),\r\n maxDebt: uint64(maxDebt)\r\n })\r\n );\r\n\r\n metadata.push(\r\n Metadata({\r\n lastTune: uint48(block.timestamp),\r\n lastDecay: uint48(block.timestamp),\r\n length: uint48(secondsToConclusion),\r\n depositInterval: _intervals[0],\r\n tuneInterval: _intervals[1],\r\n quoteDecimals: uint8(decimals)\r\n })\r\n );\r\n\r\n marketsForQuote[address(_quoteToken)].push(id_);\r\n\r\n emit CreateMarket(id_, address(blkd), 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 calculate current market price of quote token in base token\r\n * @dev accounts for debt and control variable decay since last deposit (vs _marketPrice())\r\n * @param _id ID of market\r\n * @return price for market in BLKD decimals\r\n *\r\n * price is derived from the equation\r\n *\r\n * p = cv * dr\r\n *\r\n * where\r\n * p = price\r\n * cv = control variable\r\n * dr = debt ratio\r\n *\r\n * dr = d / s\r\n *\r\n * where\r\n * d = debt\r\n * s = supply of token at market creation\r\n *\r\n * d -= ( d * (dt / l) )\r\n *\r\n * where\r\n * dt = change in time\r\n * l = length of program\r\n */\r\n function marketPrice(uint256 _id) public view override returns (uint256) {\r\n return (currentControlVariable(_id) * debtRatio(_id)) / (10**metadata[_id].quoteDecimals);\r\n }\r\n\r\n /**\r\n * @notice payout due for amount of quote tokens\r\n * @dev accounts for debt and control variable decay so it is up to date\r\n * @param _amount amount of quote tokens to spend\r\n * @param _id ID of market\r\n * @return amount of BLKD to be paid in BLKD decimals\r\n *\r\n * @dev 1e18 = blkd decimals (9) + market 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) / marketPrice(_id) / 10**meta.quoteDecimals;\r\n }\r\n\r\n /**\r\n * @notice calculate current ratio of debt to supply\r\n * @dev uses current debt, which accounts for debt decay since last deposit (vs _debtRatio())\r\n * @param _id ID of market\r\n * @return debt ratio for market in quote decimals\r\n */\r\n function debtRatio(uint256 _id) public view override returns (uint256) {\r\n return (currentDebt(_id) * (10**metadata[_id].quoteDecimals)) / treasury.baseSupply();\r\n }\r\n\r\n /**\r\n * @notice calculate debt factoring in decay\r\n * @dev accounts for debt decay since last deposit\r\n * @param _id ID of market\r\n * @return current debt for market in BLKD decimals\r\n */\r\n function currentDebt(uint256 _id) public view override returns (uint256) {\r\n return markets[_id].totalDebt - debtDecay(_id);\r\n }\r\n\r\n /**\r\n * @notice amount of debt to decay from total debt for market ID\r\n * @param _id ID of market\r\n * @return amount of debt to decay\r\n */\r\n function debtDecay(uint256 _id) public view override returns (uint64) {\r\n Metadata memory meta = metadata[_id];\r\n\r\n uint256 secondsSince = block.timestamp - meta.lastDecay;\r\n\r\n return uint64((markets[_id].totalDebt * secondsSince) / meta.length);\r\n }\r\n\r\n /**\r\n * @notice up to date control variable\r\n * @dev accounts for control variable adjustment\r\n * @param _id ID of market\r\n * @return control variable for market in BLKD decimals\r\n */\r\n function currentControlVariable(uint256 _id) public view returns (uint256) {\r\n (uint64 decay, , ) = _controlDecay(_id);\r\n return terms[_id].controlVariable - decay;\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 /* ======== INTERNAL VIEW ======== */\r\n\r\n /**\r\n * @notice calculate current market price of quote token in base token\r\n * @dev see marketPrice() for explanation of price computation\r\n * @dev uses info from storage because data has been updated before call (vs marketPrice())\r\n * @param _id market ID\r\n * @return price for market in BLKD decimals\r\n */\r\n function _marketPrice(uint256 _id) internal view returns (uint256) {\r\n return (terms[_id].controlVariable * _debtRatio(_id)) / (10**metadata[_id].quoteDecimals);\r\n }\r\n\r\n /**\r\n * @notice calculate debt factoring in decay\r\n * @dev uses info from storage because data has been updated before call (vs debtRatio())\r\n * @param _id market ID\r\n * @return current debt for market in quote decimals\r\n */\r\n function _debtRatio(uint256 _id) internal view returns (uint256) {\r\n return (markets[_id].totalDebt * (10**metadata[_id].quoteDecimals)) / treasury.baseSupply();\r\n }\r\n\r\n /**\r\n * @notice amount to decay control variable by\r\n * @param _id ID of market\r\n * @return decay_ change in control variable\r\n * @return secondsSince_ seconds since last change in control variable\r\n * @return active_ whether or not change remains active\r\n */\r\n function _controlDecay(uint256 _id)\r\n internal\r\n view\r\n returns (\r\n uint64 decay_,\r\n uint48 secondsSince_,\r\n bool active_\r\n )\r\n {\r\n Adjustment memory info = adjustments[_id];\r\n if (!info.active) return (0, 0, false);\r\n\r\n secondsSince_ = uint48(block.timestamp) - info.lastAdjustment;\r\n\r\n active_ = secondsSince_ < info.timeToAdjusted;\r\n decay_ = active_ ? (info.change * secondsSince_) / info.timeToAdjusted : info.change;\r\n }\r\n}"
},
"contracts/interfaces/IBondDepository.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IERC20.sol\";\r\n\r\ninterface IBondDepository {\r\n // Info about each type of market\r\n struct Market {\r\n uint256 capacity; // capacity remaining\r\n IERC20 quoteToken; // token to accept as payment\r\n bool capacityInQuote; // capacity limit is in payment token (true) or in BLKD (false, default)\r\n uint64 totalDebt; // total debt from market\r\n uint64 maxPayout; // max tokens in/out (determined by capacityInQuote false/true, respectively)\r\n uint64 sold; // base tokens out\r\n uint256 purchased; // quote tokens in\r\n }\r\n\r\n // Info for creating new markets\r\n struct Terms {\r\n bool fixedTerm; // fixed term or fixed expiration\r\n uint64 controlVariable; // scaling variable for price\r\n uint48 vesting; // length of time from deposit to maturity if fixed-term\r\n uint48 conclusion; // timestamp when market no longer offered (doubles as time when market matures if fixed-expiry)\r\n uint64 maxDebt; // 9 decimal debt maximum in BLKD\r\n }\r\n\r\n // Additional info about market.\r\n struct Metadata {\r\n uint48 lastTune; // last timestamp when control variable was tuned\r\n uint48 lastDecay; // last timestamp when market was created and debt was decayed\r\n uint48 length; // time from creation to conclusion. used as speed to decay debt.\r\n uint48 depositInterval; // target frequency of deposits\r\n uint48 tuneInterval; // frequency of tuning\r\n uint8 quoteDecimals; // decimals of quote token\r\n }\r\n\r\n // Control variable adjustment data\r\n struct Adjustment {\r\n uint64 change;\r\n uint48 lastAdjustment;\r\n uint48 timeToAdjusted;\r\n bool active;\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 * @return payout_ uint256\r\n * @return expiry_ uint256\r\n * @return index_ uint256\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 )\r\n external\r\n returns (\r\n uint256 payout_,\r\n uint256 expiry_,\r\n uint256 index_\r\n );\r\n\r\n function create(\r\n IERC20 _quoteToken, // token used to deposit\r\n uint256[3] memory _market, // [capacity, initial price]\r\n bool[2] memory _booleans, // [capacity in quote, fixed term]\r\n uint256[2] memory _terms, // [vesting, conclusion]\r\n uint32[2] memory _intervals // [deposit interval, tune interval]\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 payoutFor(uint256 _amount, uint256 _bid) external view returns (uint256);\r\n\r\n function marketPrice(uint256 _bid) external view returns (uint256);\r\n\r\n function currentDebt(uint256 _bid) external view returns (uint256);\r\n\r\n function debtRatio(uint256 _bid) external view returns (uint256);\r\n\r\n function debtDecay(uint256 _bid) external view returns (uint64);\r\n}"
},
"contracts/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}"
},
"contracts/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}"
},
"contracts/types/NoteKeeper.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity ^0.8.10;\r\n\r\nimport \"../types/FrontEndRewarder.sol\";\r\n\r\nimport \"../interfaces/IgBLKD.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\r\n IgBLKD internal immutable gBLKD;\r\n IStaking internal immutable staking;\r\n ITreasury internal treasury;\r\n\r\n constructor(\r\n IBlackDAOAuthority _authority,\r\n IERC20 _blkd,\r\n IgBLKD _gblkd,\r\n IStaking _staking,\r\n ITreasury _treasury\r\n ) FrontEndRewarder(_authority, _blkd) {\r\n gBLKD = _gblkd;\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 treasury = ITreasury(authority.vault());\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 BLKD 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 * @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 ) 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: gBLKD.balanceTo(_payout),\r\n created: uint48(block.timestamp),\r\n matured: _expiry,\r\n redeemed: 0,\r\n marketID: _marketID\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 // note that only the payout gets staked (front end rewards are in BLKD)\r\n staking.stake(address(this), _payout, false, true);\r\n }\r\n\r\n /* ========== REDEEM ========== */\r\n\r\n /**\r\n * @notice redeem notes for user\r\n * @param _user the user to redeem for\r\n * @param _indexes the note indexes to redeem\r\n * @param _sendgBLKD send payout as gBLKD or sBLKD\r\n * @return payout_ sum of payout sent, in gBLKD\r\n */\r\n function redeem(\r\n address _user,\r\n uint256[] memory _indexes,\r\n bool _sendgBLKD\r\n ) public override returns (uint256 payout_) {\r\n uint48 time = uint48(block.timestamp);\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 }\r\n }\r\n\r\n if (_sendgBLKD) {\r\n gBLKD.transfer(_user, payout_); // send payout as gBLKD\r\n } else {\r\n staking.unwrap(_user, payout_); // unwrap and send payout as sBLKD\r\n }\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 * @param _sendgBLKD send payout as gBLKD or sBLKD\r\n * @return sum of payout sent, in gBLKD\r\n */\r\n function redeemAll(address _user, bool _sendgBLKD) external override returns (uint256) {\r\n return redeem(_user, indexesFor(_user), _sendgBLKD);\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\r\n /**\r\n * @notice transfer a note that has been approved by an address\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 notes[msg.sender].push(notes[_from][_index]);\r\n\r\n delete notes[_from][_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 gBLKD\r\n * @return matured_ if the payout can be redeemed\r\n */\r\n function pendingFor(address _user, uint256 _index) public view override returns (uint256 payout_, bool matured_) {\r\n Note memory note = notes[_user][_index];\r\n\r\n payout_ = note.payout;\r\n matured_ = note.redeemed == 0 && note.matured <= block.timestamp && note.payout != 0;\r\n }\r\n}"
},
"contracts/interfaces/INoteKeeper.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity >=0.7.5;\r\n\r\ninterface INoteKeeper {\r\n // Info for market note\r\n struct Note {\r\n uint256 payout; // gBLKD remaining to be paid\r\n uint48 created; // time market was created\r\n uint48 matured; // timestamp when market is matured\r\n uint48 redeemed; // time market was redeemed\r\n uint48 marketID; // market ID of deposit. uint48 to avoid adding a slot.\r\n }\r\n\r\n function redeem(\r\n address _user,\r\n uint256[] memory _indexes,\r\n bool _sendgBLKD\r\n ) external returns (uint256);\r\n\r\n function redeemAll(address _user, bool _sendgBLKD) 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) external view returns (uint256 payout_, bool matured_);\r\n}"
},
"contracts/interfaces/ITreasury.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\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 excessReserves() external view returns (uint256);\r\n\r\n function baseSupply() external view returns (uint256);\r\n}"
},
"contracts/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 _rebasing,\r\n bool _claim\r\n ) external returns (uint256);\r\n\r\n function claim(address _recipient, bool _rebasing) external returns (uint256);\r\n\r\n function forfeit() external returns (uint256);\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}"
},
"contracts/interfaces/IgBLKD.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\nimport \"./IERC20.sol\";\r\n\r\ninterface IgBLKD is IERC20 {\r\n function mint(address _to, uint256 _amount) external;\r\n\r\n function burn(address _from, uint256 _amount) external;\r\n\r\n function index() external view returns (uint256);\r\n\r\n function balanceFrom(uint256 _amount) external view returns (uint256);\r\n\r\n function balanceTo(uint256 _amount) external view returns (uint256);\r\n\r\n function migrate(address _staking, address _sBLKD) external;\r\n}"
},
"contracts/types/FrontEndRewarder.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity ^0.8.10;\r\n\r\nimport \"../types/BlackDAOAccessControlled.sol\";\r\nimport \"../interfaces/IERC20.sol\";\r\n\r\nabstract contract FrontEndRewarder is BlackDAOAccessControlled {\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 blkd; // reward token\r\n\r\n constructor(IBlackDAOAuthority _authority, IERC20 _blkd) BlackDAOAccessControlled(_authority) {\r\n blkd = _blkd;\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 blkd.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\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}"
},
"contracts/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}"
},
"contracts/types/BlackDAOAccessControlled.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity >=0.7.5;\r\n\r\nimport \"../interfaces/IBlackDAOAuthority.sol\";\r\n\r\nabstract contract BlackDAOAccessControlled {\r\n /* ========== EVENTS ========== */\r\n\r\n event AuthorityUpdated(IBlackDAOAuthority indexed authority);\r\n\r\n string UNAUTHORIZED = \"UNAUTHORIZED\"; // save gas\r\n\r\n /* ========== STATE VARIABLES ========== */\r\n\r\n IBlackDAOAuthority public authority;\r\n\r\n /* ========== Constructor ========== */\r\n\r\n constructor(IBlackDAOAuthority _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 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(IBlackDAOAuthority _newAuthority) external onlyGovernor {\r\n authority = _newAuthority;\r\n emit AuthorityUpdated(_newAuthority);\r\n }\r\n}"
},
"contracts/interfaces/IBlackDAOAuthority.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\r\npragma solidity >=0.7.5;\r\n\r\ninterface IBlackDAOAuthority {\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 VaultPushed(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 VaultPulled(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 vault() external view returns (address);\r\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
}
}