creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "lib/solmate/src/utils/FixedPointMathLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n    /*//////////////////////////////////////////////////////////////\n                    SIMPLIFIED FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n    }\n\n    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n    }\n\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    LOW LEVEL FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function mulDivDown(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // Divide x * y by the denominator.\n            z := div(mul(x, y), denominator)\n        }\n    }\n\n    function mulDivUp(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // If x * y modulo the denominator is strictly greater than 0,\n            // 1 is added to round up the division of x * y by the denominator.\n            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n        }\n    }\n\n    function rpow(\n        uint256 x,\n        uint256 n,\n        uint256 scalar\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            switch x\n            case 0 {\n                switch n\n                case 0 {\n                    // 0 ** 0 = 1\n                    z := scalar\n                }\n                default {\n                    // 0 ** n = 0\n                    z := 0\n                }\n            }\n            default {\n                switch mod(n, 2)\n                case 0 {\n                    // If n is even, store scalar in z for now.\n                    z := scalar\n                }\n                default {\n                    // If n is odd, store x in z for now.\n                    z := x\n                }\n\n                // Shifting right by 1 is like dividing by 2.\n                let half := shr(1, scalar)\n\n                for {\n                    // Shift n right by 1 before looping to halve it.\n                    n := shr(1, n)\n                } n {\n                    // Shift n right by 1 each iteration to halve it.\n                    n := shr(1, n)\n                } {\n                    // Revert immediately if x ** 2 would overflow.\n                    // Equivalent to iszero(eq(div(xx, x), x)) here.\n                    if shr(128, x) {\n                        revert(0, 0)\n                    }\n\n                    // Store x squared.\n                    let xx := mul(x, x)\n\n                    // Round to the nearest number.\n                    let xxRound := add(xx, half)\n\n                    // Revert if xx + half overflowed.\n                    if lt(xxRound, xx) {\n                        revert(0, 0)\n                    }\n\n                    // Set x to scaled xxRound.\n                    x := div(xxRound, scalar)\n\n                    // If n is even:\n                    if mod(n, 2) {\n                        // Compute z * x.\n                        let zx := mul(z, x)\n\n                        // If z * x overflowed:\n                        if iszero(eq(div(zx, x), z)) {\n                            // Revert if x is non-zero.\n                            if iszero(iszero(x)) {\n                                revert(0, 0)\n                            }\n                        }\n\n                        // Round to the nearest number.\n                        let zxRound := add(zx, half)\n\n                        // Revert if zx + half overflowed.\n                        if lt(zxRound, zx) {\n                            revert(0, 0)\n                        }\n\n                        // Return properly scaled zxRound.\n                        z := div(zxRound, scalar)\n                    }\n                }\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        GENERAL NUMBER UTILITIES\n    //////////////////////////////////////////////////////////////*/\n\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Mod x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            z := mod(x, y)\n        }\n    }\n\n    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Divide x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            r := div(x, y)\n        }\n    }\n\n    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Add 1 to x * y if x % y > 0. Note this will\n            // return 0 instead of reverting if y is zero.\n            z := add(gt(mod(x, y), 0), div(x, y))\n        }\n    }\n}\n"
      },
      "src/escrows/INVEscrow.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.13;\nimport \"../interfaces/IERC20.sol\";\nimport {FixedPointMathLib} from \"solmate/utils/FixedPointMathLib.sol\";\n\n// @dev Caution: We assume all failed transfers cause reverts and ignore the returned bool.\ninterface IXINV {\n    function rewardTreasury() external view returns(address);\n    function balanceOf(address) external view returns (uint);\n    function exchangeRateStored() external view returns (uint);\n    function exchangeRateCurrent() external returns (uint);\n    function mint(uint mintAmount) external returns (uint);\n    function redeemUnderlying(uint redeemAmount) external returns (uint);\n    function syncDelegate(address user) external;\n    function accrualBlockNumber() external view returns (uint);\n    function getCash() external view returns (uint);\n    function totalSupply() external view returns (uint);\n    function rewardPerBlock() external view returns (uint);\n}\n\ninterface IDbrDistributor {\n    function stake(uint amount) external;\n    function unstake(uint amount) external;\n    function claim(address to) external;\n    function claimable(address user) external view returns(uint);\n}\n\n/**\n * @title INV Escrow\n * @notice Collateral is stored in unique escrow contracts for every user and every market.\n * This escrow allows user to deposit INV collateral directly into the xINV contract, earning APY and allowing them to delegate votes on behalf of the xINV collateral\n * @dev Caution: This is a proxy implementation. Follow proxy pattern best practices\n */\ncontract INVEscrow {\n    using FixedPointMathLib for uint;\n\n    address public market;\n    IDelegateableERC20 public token;\n    address public beneficiary;\n    uint public stakedXINV;\n    IXINV public immutable xINV;\n    IDbrDistributor public immutable distributor;\n    mapping(address => bool) public claimers;\n\n    constructor(IXINV _xINV, IDbrDistributor _distributor) {\n        xINV = _xINV;\n        distributor = _distributor;\n    }\n\n    /**\n     * @notice Initialize escrow with a token\n     * @dev Must be called right after proxy is created.\n     * @param _token The IERC20 token representing the INV governance token\n     * @param _beneficiary The beneficiary who may delegate token voting power\n     */\n    function initialize(IDelegateableERC20 _token, address _beneficiary) public {\n        require(market == address(0), \"ALREADY INITIALIZED\");\n        market = msg.sender;\n        token = _token;\n        beneficiary = _beneficiary;\n        _token.delegate(_token.delegates(_beneficiary));\n        _token.approve(address(xINV), type(uint).max);\n        xINV.syncDelegate(address(this));\n    }\n    \n    /**\n     * @notice Transfers the associated ERC20 token to a recipient.\n     * @param recipient The address to receive payment from the escrow\n     * @param amount The amount of ERC20 token to be transferred.\n     */\n    function pay(address recipient, uint amount) public {\n        require(msg.sender == market, \"ONLY MARKET\");\n        uint invBalance = token.balanceOf(address(this));\n        if(invBalance < amount) {\n            uint invNeeded = amount - invBalance;\n            uint xInvToUnstake = invNeeded * 1 ether / viewExchangeRate();\n            stakedXINV -= xInvToUnstake;\n            distributor.unstake(xInvToUnstake);\n            xINV.redeemUnderlying(invNeeded); // we do not check return value because transfer call will fail if this fails anyway\n        }\n        token.transfer(recipient, amount);\n    }\n    \n    /**\n     * @notice Allows the beneficiary to claim DBR tokens\n     * @dev Requires the caller to be the beneficiary\n     */\n    function claimDBR() public {\n        require(msg.sender == beneficiary, \"ONLY BENEFICIARY\");\n        distributor.claim(msg.sender);\n    }\n\n    /**\n     * @notice Allows the beneficiary or allowed claimers to claim DBR tokens on behalf of another address\n     * @param to The address to which the claimed tokens will be sent\n     * @dev Requires the caller to be the beneficiary or an allowed claimer\n     */\n    function claimDBRTo(address to) public {\n        require(msg.sender == beneficiary || claimers[msg.sender], \"ONLY BENEFICIARY OR ALLOWED CLAIMERS\");\n        distributor.claim(to);\n    }\n\n    /**\n     * @notice Returns the amount of claimable DBR tokens for the contract\n     * @return The amount of claimable tokens\n     */\n    function claimable() public view returns (uint) {\n        return distributor.claimable(address(this));\n    }\n\n    /**\n     * @notice Sets or unsets an address as an allowed claimer\n     * @param claimer The address of the claimer to set or unset\n     * @param allowed A boolean value to determine if the claimer is allowed or not\n     * @dev Requires the caller to be the beneficiary\n     */\n    function setClaimer(address claimer, bool allowed) public {\n        require(msg.sender == beneficiary, \"ONLY BENEFICIARY\");\n        claimers[claimer] = allowed;\n    }\n\n    /**\n    * @notice Get the token balance of the escrow\n    * @return Uint representing the INV token balance of the escrow including the additional INV accrued from xINV\n    */\n    function balance() public view returns (uint) {\n        uint invBalance = token.balanceOf(address(this));\n        uint invBalanceInXInv = stakedXINV * viewExchangeRate() / 1 ether;\n        return invBalance + invBalanceInXInv;\n    }\n    \n    /**\n     * @notice Function called by market on deposit. Will deposit INV into xINV \n     * @dev This function should remain callable by anyone to handle direct inbound transfers.\n     */\n    function onDeposit() public {\n        uint invBalance = token.balanceOf(address(this));\n        if(invBalance > 0) {\n            uint xinvBal = xINV.balanceOf(address(this));\n            xINV.mint(invBalance); // we do not check return value because we don't want errors to block this call\n            stakedXINV += xINV.balanceOf(address(this)) - xinvBal;\n            distributor.stake(stakedXINV - xinvBal);\n        }\n    }\n\n    /**\n     * @notice Delegates voting power of the underlying xINV.\n     * @param delegatee The address to be delegated voting power\n     */\n    function delegate(address delegatee) public {\n        require(msg.sender == beneficiary, \"ONLY BENEFICIARY\");\n        token.delegate(delegatee);\n        xINV.syncDelegate(address(this));\n    }\n\n    /**\n     * @notice View function to calculate exact exchangerate for current block\n     */\n    function viewExchangeRate() internal view returns (uint) {\n        uint accrualBlockNumberPrior = xINV.accrualBlockNumber();\n        if (accrualBlockNumberPrior == block.number) return xINV.exchangeRateStored();\n        uint blockDelta = block.number - accrualBlockNumberPrior;\n        uint rewardsAccrued = xINV.rewardPerBlock() * blockDelta;\n        uint treasuryInvBalance = token.balanceOf(xINV.rewardTreasury());\n        uint treasuryxInvAllowance = token.allowance(xINV.rewardTreasury(), address(xINV));\n        if( treasuryInvBalance <= rewardsAccrued || treasuryxInvAllowance <= rewardsAccrued) return xINV.exchangeRateStored();\n        return (xINV.getCash() + rewardsAccrued).divWadDown(xINV.totalSupply());\n    }\n\n}\n"
      },
      "src/interfaces/IERC20.sol": {
        "content": "pragma solidity ^0.8.13;\n\ninterface IERC20 {\n    function approve(address,uint) external;\n    function transfer(address,uint) external returns (bool);\n    function transferFrom(address,address,uint) external returns (bool);\n    function balanceOf(address) external view returns (uint);\n    function allowance(address from, address to) external view returns (uint);\n}\n\ninterface IDelegateableERC20 is IERC20 {\n    function delegate(address delegatee) external;\n    function delegates(address delegator) external view returns (address delegatee);\n}\n\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/solmate/lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "solmate/=lib/solmate/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "bytecodeHash": "ipfs"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "london",
      "libraries": {}
    }
  }}