creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "lib/solmate/src/tokens/ERC20.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n    /*///////////////////////////////////////////////////////////////\n                                  EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /*///////////////////////////////////////////////////////////////\n                             METADATA STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    string public name;\n\n    string public symbol;\n\n    uint8 public immutable decimals;\n\n    /*///////////////////////////////////////////////////////////////\n                              ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 public totalSupply;\n\n    mapping(address => uint256) public balanceOf;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*///////////////////////////////////////////////////////////////\n                             EIP-2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    bytes32 public constant PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n\n    uint256 internal immutable INITIAL_CHAIN_ID;\n\n    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n    mapping(address => uint256) public nonces;\n\n    /*///////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    ) {\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n\n        INITIAL_CHAIN_ID = block.chainid;\n        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                              ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        allowance[msg.sender][spender] = amount;\n\n        emit Approval(msg.sender, spender, amount);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        balanceOf[msg.sender] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(msg.sender, to, amount);\n\n        return true;\n    }\n\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n        balanceOf[from] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        return true;\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                              EIP-2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            bytes32 digest = keccak256(\n                abi.encodePacked(\n                    \"\\x19\\x01\",\n                    DOMAIN_SEPARATOR(),\n                    keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n                )\n            );\n\n            address recoveredAddress = ecrecover(digest, v, r, s);\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n    }\n\n    function computeDomainSeparator() internal view virtual returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(bytes(name)),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                       INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function _mint(address to, uint256 amount) internal virtual {\n        totalSupply += amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(address(0), to, amount);\n    }\n\n    function _burn(address from, uint256 amount) internal virtual {\n        balanceOf[from] -= amount;\n\n        // Cannot underflow because a user's balance\n        // will never be larger than the total supply.\n        unchecked {\n            totalSupply -= amount;\n        }\n\n        emit Transfer(from, address(0), amount);\n    }\n}\n"
      },
      "lib/solmate/src/utils/SafeTransferLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\nlibrary SafeTransferLib {\n    /*///////////////////////////////////////////////////////////////\n                            ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool callStatus;\n\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            callStatus := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(callStatus, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                           ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 100 because the calldata length is 4 + 32 * 3.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 68 because the calldata length is 4 + 32 * 2.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 68 because the calldata length is 4 + 32 * 2.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"APPROVE_FAILED\");\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                         INTERNAL HELPER LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {\n        assembly {\n            // Get how many bytes the call returned.\n            let returnDataSize := returndatasize()\n\n            // If the call reverted:\n            if iszero(callStatus) {\n                // Copy the revert message into memory.\n                returndatacopy(0, 0, returnDataSize)\n\n                // Revert with the same message.\n                revert(0, returnDataSize)\n            }\n\n            switch returnDataSize\n            case 32 {\n                // Copy the return data into memory.\n                returndatacopy(0, 0, returnDataSize)\n\n                // Set success to whether it returned true.\n                success := iszero(iszero(mload(0)))\n            }\n            case 0 {\n                // There was no return data.\n                success := 1\n            }\n            default {\n                // It returned some malformed input.\n                success := 0\n            }\n        }\n    }\n}\n"
      },
      "src/Entity.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity >=0.8.0;\nimport \"solmate/tokens/ERC20.sol\";\nimport \"solmate/utils/SafeTransferLib.sol\";\nimport \"./lib/ReentrancyGuard.sol\";\n\nimport { Registry } from  \"./Registry.sol\";\nimport { ISwapWrapper } from \"./interfaces/ISwapWrapper.sol\";\nimport { EndaomentAuth } from \"./lib/auth/EndaomentAuth.sol\";\nimport { Portfolio } from \"./Portfolio.sol\";\nimport { Math } from \"./lib/Math.sol\";\n\nerror EntityInactive();\nerror PortfolioInactive();\nerror InsufficientFunds();\nerror InvalidAction();\nerror BalanceMismatch();\nerror CallFailed(bytes response);\n\n/**\n * @notice Entity contract inherited by Org and Fund contracts (and all future kinds of Entities).\n */\nabstract contract Entity is EndaomentAuth, ReentrancyGuard {\n    using Math for uint256;\n    using SafeTransferLib for ERC20;\n\n    /// @notice The base registry to which the entity is connected.\n    Registry public registry;\n\n    /// @notice The entity's manager.\n    address public manager;\n\n    // @notice The base token used for tracking the entity's fund balance.\n    ERC20 public baseToken;\n\n    /// @notice The current balance for the entity, denominated in the base token's units.\n    uint256 public balance;\n\n    /// @notice Placeholder address used in swapping method to denote usage of ETH instead of a token.\n    address public constant ETH_PLACEHOLDER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n    /// @notice Emitted when manager is set.\n    event EntityManagerSet(address indexed oldManager, address indexed newManager);\n\n    /// @notice Emitted when a donation is made.\n    event EntityDonationReceived(\n        address indexed from,\n        address indexed to,\n        address indexed tokenIn,\n        uint256 amountIn,\n        uint256 amountReceived,\n        uint256 amountFee\n    );\n\n    /// @notice Emitted when a payout is made from an entity.\n    event EntityValuePaidOut(address indexed from, address indexed to, uint256 amountSent, uint256 amountFee);\n\n    /// @notice Emitted when a transfer is made between entities.\n    event EntityValueTransferred(address indexed from, address indexed to, uint256 amountReceived, uint256 amountFee);\n\n    /// @notice Emitted when a base token reconciliation completes\n    event EntityBalanceReconciled(address indexed entity, uint256 amountReceived, uint256 amountFee);\n\n    /// @notice Emitted when a base token balance is used to correct the internal contract balance.\n    event EntityBalanceCorrected(address indexed entity, uint256 newBalance);\n\n    /// @notice Emitted when a portfolio deposit is made.\n    event EntityDeposit(address indexed portfolio, uint256 baseTokenDeposited, uint256 sharesReceived);\n\n    /// @notice Emitted when a portfolio share redemption is made.\n    event EntityRedeem(address indexed portfolio, uint256 sharesRedeemed, uint256 baseTokenReceived);\n\n    /// @notice Emitted when ether is received.\n    event EntityEthReceived(address indexed sender, uint256 amount);\n\n    /**\n     * @notice Modifier for methods that require auth and that the manager can access.\n     * @dev Uses the same condition as `requiresAuth` but with added manager access.\n     */\n    modifier requiresManager {\n        if(msg.sender != manager && !isAuthorized(msg.sender, msg.sig)) revert Unauthorized();\n        _;\n    }\n\n    /// @notice Each entity will implement this function to allow a caller to interrogate what kind of entity it is.\n    function entityType() public pure virtual returns (uint8);\n\n    /**\n     * @notice One time method to be called at deployment to configure the contract. Required so Entity\n     * contracts can be deployed as minimal proxies (clones).\n     * @param _registry The registry to host the Entity.\n     * @param _manager The address of the Entity's manager.\n     */\n    function __initEntity(Registry _registry, address _manager) internal {\n        // Call to EndaomentAuth's initialize function ensures that this can't be called again\n        __initEndaomentAuth(_registry, bytes20(bytes.concat(\"entity\", bytes1(entityType()))));\n        __initReentrancyGuard();\n        registry = _registry;\n        manager = _manager;\n        baseToken = _registry.baseToken();\n    }\n\n    /**\n     * @notice Set a new manager for this entity.\n     * @param _manager Address of new manager.\n     * @dev Callable by current manager or permissioned role.\n     */\n    function setManager(address _manager) external virtual requiresManager {\n        emit EntityManagerSet(manager, _manager);\n        manager = _manager;\n    }\n\n    /**\n     * @notice Receives a donated amount of base tokens to be added to the entity's balance. Transfers default fee to treasury.\n     * @param _amount Amount donated in base token.\n     * @dev Reverts if the donation fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function donate(uint256 _amount) external virtual {\n        uint32 _feeMultiplier = registry.getDonationFee(this);\n        _donateWithFeeMultiplier(_amount, _feeMultiplier);\n    }\n\n    /**\n     * @notice Receives a donated amount of base tokens to be added to the entity's balance. Transfers default or overridden fee to treasury.\n     * @param _amount Amount donated in base token.\n     * @dev Reverts if the donation fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function donateWithOverrides(uint256 _amount) external virtual {\n        uint32 _feeMultiplier = registry.getDonationFeeWithOverrides(this);\n        _donateWithFeeMultiplier(_amount, _feeMultiplier);\n    }\n\n    /**\n     * @notice Receives a donated amount of base tokens to be added to the entity's balance.\n     * This method can be called by permissioned actors to make a donation with a manually specified fee.\n     * @param _amount Amount donated in base token.\n     * @param _feeOverride Fee percentage as zoc.\n     * @dev Reverts if the transfer fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not a privileged role.\n     */\n    function donateWithAdminOverrides(uint256 _amount, uint32 _feeOverride) requiresAuth external virtual {\n        _donateWithFeeMultiplier(_amount, _feeOverride);\n    }\n\n    /**\n     * @notice Receives a donated amount of base tokens to be added to the entity's balance. Transfers fee calculated by fee multiplier to treasury.\n     * @param _amount Amount donated in base token.\n     * @param _feeMultiplier Value indicating the percentage of the Endaoment donation fee to go to the Endaoment treasury.\n     * @dev Reverts if the donation fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function _donateWithFeeMultiplier(uint256 _amount, uint32 _feeMultiplier) internal virtual {\n\n        (uint256 _netAmount, uint256 _fee) = _calculateFee(_amount, _feeMultiplier);\n        baseToken.safeTransferFrom(msg.sender, registry.treasury(), _fee);\n        baseToken.safeTransferFrom(msg.sender, address(this), _netAmount);\n\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            balance += _netAmount;\n        }\n        emit EntityDonationReceived(msg.sender, address(this), address(baseToken), _amount, _amount, _fee);\n    }\n\n    /**\n     * @notice Receive a donated amount of ETH or ERC20 tokens, swaps them to base tokens, and adds the output to the\n     * entity's balance. Fee calculated using default rate and sent to treasury.\n     * @param _swapWrapper The swap wrapper to use for the donation. Must be whitelisted on the Registry.\n     * @param _tokenIn The address of the ERC20 token to swap and donate, or ETH_PLACEHOLDER if donating ETH.\n     * @param _amountIn The amount of tokens or ETH being swapped and donated.\n     * @param _data Additional call data required by the ISwapWrapper being used.\n     */\n    function swapAndDonate(\n        ISwapWrapper _swapWrapper,\n        address _tokenIn,\n        uint256 _amountIn,\n        bytes calldata _data\n    ) external virtual payable {\n        uint32 _feeMultiplier = registry.getDonationFee(this);\n        _swapAndDonateWithFeeMultiplier(_swapWrapper, _tokenIn, _amountIn, _data, _feeMultiplier);\n    }\n\n    /**\n     * @notice Receive a donated amount of ETH or ERC20 tokens, swaps them to base tokens, and adds the output to the\n     * entity's balance. Fee calculated using override rate and sent to treasury.\n     * @param _swapWrapper The swap wrapper to use for the donation. Must be whitelisted on the Registry.\n     * @param _tokenIn The address of the ERC20 token to swap and donate, or ETH_PLACEHOLDER if donating ETH.\n     * @param _amountIn The amount of tokens or ETH being swapped and donated.\n     * @param _data Additional call data required by the ISwapWrapper being used.\n     */\n    function swapAndDonateWithOverrides(\n        ISwapWrapper _swapWrapper,\n        address _tokenIn,\n        uint256 _amountIn,\n        bytes calldata _data\n    ) external virtual payable {\n        uint32 _feeMultiplier = registry.getDonationFeeWithOverrides(this);\n        _swapAndDonateWithFeeMultiplier(_swapWrapper, _tokenIn, _amountIn, _data, _feeMultiplier);\n    }\n\n    /// @dev Internal helper implementing swap and donate functionality for any fee multiplier provided.\n    function _swapAndDonateWithFeeMultiplier(\n        ISwapWrapper _swapWrapper,\n        address _tokenIn,\n        uint256 _amountIn,\n        bytes calldata _data,\n        uint32 _feeMultiplier\n    ) nonReentrant internal virtual {\n        if (!registry.isSwapperSupported(_swapWrapper)) revert InvalidAction();\n\n        // THINK: do we need a re-entrancy guard on this method?\n        if (_tokenIn != ETH_PLACEHOLDER) {\n            ERC20(_tokenIn).safeTransferFrom(msg.sender, address(this), _amountIn);\n            ERC20(_tokenIn).safeApprove(address(_swapWrapper), 0);\n            ERC20(_tokenIn).safeApprove(address(_swapWrapper), _amountIn);\n        }\n\n        uint256 _amountOut = _swapWrapper.swap{value: msg.value}(\n            _tokenIn,\n            address(baseToken),\n            address(this),\n            _amountIn,\n            _data\n        );\n\n        (uint256 _netAmount, uint256 _fee) = _calculateFee(_amountOut, _feeMultiplier);\n\n        baseToken.safeTransfer(registry.treasury(), _fee);\n\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            balance += _netAmount;\n        }\n\n        if(balance > baseToken.balanceOf(address(this))) revert BalanceMismatch();\n\n        emit EntityDonationReceived(msg.sender, address(this), _tokenIn, _amountIn, _amountOut, _fee);\n    }\n\n    /**\n     * @notice Transfers an amount of base tokens from one entity to another. Transfers default fee to treasury.\n     * @param _to The entity to receive the tokens.\n     * @param _amount Contains the amount being donated (denominated in the base token's units).\n     * @dev Reverts if the entity is inactive or if the token transfer fails.\n     * @dev Reverts if the transfer fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not the entity manager or a privileged role.\n     * @dev Renamed from `transfer` to distinguish from ERC20 transfer in 3rd party tools.\n     */\n    function transferToEntity(Entity _to, uint256 _amount) requiresManager external virtual {\n        uint32 _feeMultiplier = registry.getTransferFee(this, _to);\n        _transferWithFeeMultiplier(_to, _amount, _feeMultiplier);\n    }\n\n    /**\n     * @notice Transfers an amount of base tokens from one entity to another. Transfers default or overridden fee to treasury.\n     * @param _to The entity to receive the tokens.\n     * @param _amount Contains the amount being donated (denominated in the base token's units).\n     * @dev Reverts if the entity is inactive or if the token transfer fails.\n     * @dev Reverts if the transfer fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not the entity manager or a privileged role.\n     */\n    function transferToEntityWithOverrides(Entity _to, uint256 _amount) requiresManager external virtual {\n        uint32 _feeMultiplier = registry.getTransferFeeWithOverrides(this, _to);\n        _transferWithFeeMultiplier(_to, _amount, _feeMultiplier);\n    }\n\n    /**\n     * @notice Transfers an amount of base tokens from one entity to another. Transfers fee specified by a privileged role.\n     * @param _to The entity to receive the tokens.\n     * @param _amount Contains the amount being donated (denominated in the base token's units).\n     * @param _feeOverride Admin override configured by an Admin\n     * @dev Reverts if the entity is inactive or if the token transfer fails.\n     * @dev Reverts if the transfer fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not a privileged role.\n     */\n    function transferToEntityWithAdminOverrides(Entity _to, uint256 _amount, uint32 _feeOverride) requiresAuth external virtual {\n        _transferWithFeeMultiplier(_to, _amount, _feeOverride);\n    }\n\n    /**\n     * @notice Transfers an amount of base tokens from one entity to another. Transfers fee calculated by fee multiplier to treasury.\n     * @param _to The entity to receive the tokens.\n     * @param _amount Contains the amount being donated (denominated in the base token's units).\n     * @param _feeMultiplier Value indicating the percentage of the Endaoment donation fee to go to the Endaoment treasury.\n     * @dev Reverts with 'Inactive' if the entity sending the transfer or the entity receiving the transfer is inactive.\n     * @dev Reverts if the transfer fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not the entity manager or a privileged role.\n     * @dev Reverts if the token transfer fails.\n     */\n    function _transferWithFeeMultiplier(Entity _to, uint256 _amount, uint32 _feeMultiplier) internal virtual {\n        if (!registry.isActiveEntity(this) || !registry.isActiveEntity(_to)) revert EntityInactive();\n        if (balance < _amount) revert InsufficientFunds();\n\n        (uint256 _netAmount, uint256 _fee) = _calculateFee(_amount, _feeMultiplier);\n        baseToken.safeTransfer(registry.treasury(), _fee);\n        baseToken.safeTransfer(address(_to), _netAmount);\n\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            balance -= _amount;\n            _to.receiveTransfer(_netAmount);\n        }\n        emit EntityValueTransferred(address(this), address(_to), _amount, _fee);\n    }\n\n    /**\n     * @notice Updates the receiving entity balance on a transfer.\n     * @param _transferAmount The amount being received on the transfer.\n     * @dev This function is external, but is restricted such that it can only be called by other entities.\n     */\n     function receiveTransfer(uint256 _transferAmount) external virtual {\n         if (!registry.isActiveEntity(Entity(payable(msg.sender)))) revert EntityInactive();\n         unchecked {\n             // Cannot overflow with realistic balances.\n             balance += _transferAmount;\n         }\n     }\n\n     /**\n     * @notice Deposits an amount of Entity's `baseToken` into an Endaoment-approved Portfolio.\n     * @param _portfolio An Endaoment-approved portfolio.\n     * @param _amount Amount of `baseToken` to deposit into the portfolio.\n     * @param _data Data required by a portfolio to deposit.\n     * @return _shares Amount of portfolio share tokens Entity received as a result of this deposit.\n     */\n    function portfolioDeposit(Portfolio _portfolio, uint256 _amount, bytes calldata _data) external virtual requiresManager returns (uint256) {\n        if(!registry.isActivePortfolio(_portfolio)) revert PortfolioInactive();\n        balance -= _amount;\n        baseToken.safeApprove(address(_portfolio), _amount);\n        uint256 _shares = _portfolio.deposit(_amount, _data);\n        emit EntityDeposit(address(_portfolio), _amount, _shares);\n        return _shares;\n    }\n\n    /**\n     * @notice Redeems an amount of Entity's portfolio shares for an amount of `baseToken`.\n     * @param _portfolio An Endaoment-approved portfolio.\n     * @param _shares Amount of share tokens to redeem.\n     * @param _data Data required by a portfolio to redeem.\n     * @return _received Amount of `baseToken` Entity received as a result of this redemption.\n     */\n    function portfolioRedeem(Portfolio _portfolio, uint256 _shares, bytes calldata _data) external virtual requiresManager returns (uint256) {\n        if(!registry.isActivePortfolio(_portfolio)) revert PortfolioInactive();\n        uint256 _received = _portfolio.redeem(_shares, _data);\n        // unchecked: a realistic balance can never overflow a uint256\n        unchecked {\n            balance += _received;\n        }\n        emit EntityRedeem(address(_portfolio), _shares, _received);\n        return _received;\n    }\n\n    /**\n     * @notice This method should be called to reconcile the Entity's internal baseToken accounting with the baseToken contract's accounting.\n     * There are a 2 situations where calling this method is appropriate:\n     * 1. To process amounts of baseToken that arrived at this Entity through methods besides Entity:donate or Entity:transfer. For example,\n     * if this Entity receives a normal ERC20 transfer of baseToken, the amount received will be unavailable for Entity use until this method\n     * is called to adjust the balance and process fees. OrgFundFactory.sol:_donate makes use of this method to do this as well.\n     * 2. Unusually, the Entity's perspective of balance could be lower than `baseToken.balanceOf(this)`. This could happen if\n     * Entity:callAsEntity is used to transfer baseToken. In this case, this method provides a way of correcting the Entity's internal balance.\n     */\n    function reconcileBalance() external virtual {\n        uint256 _tokenBalance = baseToken.balanceOf(address(this));\n\n        if (_tokenBalance >= balance) {\n            uint256 _sweepAmount = _tokenBalance - balance;\n            uint32 _feeMultiplier = registry.getDonationFeeWithOverrides(this);\n            (uint256 _netAmount, uint256 _fee) = _calculateFee(_sweepAmount, _feeMultiplier);\n\n            baseToken.safeTransfer(registry.treasury(), _fee);\n            unchecked {\n                balance += _netAmount;\n            }\n            emit EntityBalanceReconciled(address(this), _sweepAmount, _fee);\n        } else {\n            // Handle abnormal scenario where _tokenBalance < balance (see method docs)\n            balance = _tokenBalance;\n            emit EntityBalanceCorrected(address(this), _tokenBalance);\n        }\n     }\n\n    /**\n     * @notice Takes stray tokens or ETH sent directly to this Entity, swaps them for base token, then adds them to the\n     * Entity's balance after paying the appropriate fee to the treasury.\n     * @param _swapWrapper The swap wrapper to use to convert the assets. Must be whitelisted on the Registry.\n     * @param _tokenIn The address of the ERC20 token to swap, or ETH_PLACEHOLDER if ETH.\n     * @param _amountIn The amount of tokens or ETH being swapped and added to the balance.\n     * @param _data Additional call data required by the ISwapWrapper being used.\n     */\n    function swapAndReconcileBalance(\n        ISwapWrapper _swapWrapper,\n        address _tokenIn,\n        uint256 _amountIn,\n        bytes calldata _data\n    ) nonReentrant external virtual requiresManager {\n        if (!registry.isSwapperSupported(_swapWrapper)) revert InvalidAction();\n\n        uint32 _feeMultiplier = registry.getDonationFeeWithOverrides(this);\n\n        if (_tokenIn != ETH_PLACEHOLDER) {\n            ERC20(_tokenIn).safeApprove(address(_swapWrapper), 0);\n            ERC20(_tokenIn).safeApprove(address(_swapWrapper), _amountIn);\n        }\n\n        // Send value only if token in is ETH\n        uint256 _value = _tokenIn == ETH_PLACEHOLDER ? _amountIn : 0;\n\n        uint256 _amountOut = _swapWrapper.swap{value: _value}(\n            _tokenIn,\n            address(baseToken),\n            address(this),\n            _amountIn,\n            _data\n        );\n\n        (uint256 _netAmount, uint256 _fee) = _calculateFee(_amountOut, _feeMultiplier);\n        baseToken.safeTransfer(registry.treasury(), _fee);\n\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            balance += _netAmount;\n        }\n\n        if(balance > baseToken.balanceOf(address(this))) revert BalanceMismatch();\n\n        emit EntityBalanceReconciled(address(this), _amountOut, _fee);\n    }\n\n    /**\n     * @notice Permissioned method that allows Endaoment admin to make arbitrary calls acting as this Entity.\n     * @param _target The address to which the call will be made.\n     * @param _value The ETH value that should be forwarded with the call.\n     * @param _data The calldata that will be sent with the call.\n     * @return _return The data returned by the call.\n     */\n    function callAsEntity(\n        address _target,\n        uint256 _value,\n        bytes memory _data\n    ) external virtual payable requiresAuth returns (bytes memory) {\n        (bool _success, bytes memory _response) = payable(_target).call{value: _value}(_data);\n        if (!_success) revert CallFailed(_response);\n        return _response;\n    }\n\n    /**\n     * @notice Pays out an amount of base tokens from the entity to an address. Transfers the fee calculated by the\n     * default fee multiplier to the treasury.\n     * @param _to The address to receive the tokens.\n     * @param _amount Amount donated in base token.\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not a privileged role.\n     * @dev Reverts if the fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function payout(address _to, uint256 _amount) external virtual requiresAuth {\n        uint32 _feeMultiplier = registry.getPayoutFee(this);\n        _payoutWithFeeMultiplier(_to, _amount, _feeMultiplier);\n    }\n\n    /**\n     * @notice Pays out an amount of base tokens from the entity to an address. Transfers the fee calculated by the\n     * default fee multiplier to the treasury.\n     * @param _amount Amount donated in base token.\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not a privileged role.\n     * @dev Reverts if the fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function payoutWithOverrides(address _to, uint256 _amount) external virtual requiresAuth {\n        uint32 _feeMultiplier = registry.getPayoutFeeWithOverrides(this);\n        _payoutWithFeeMultiplier(_to, _amount, _feeMultiplier);\n    }\n\n     /**\n     * @notice Pays out an amount of base tokens from the entity to an address. Transfers fee specified by a privileged role.\n     * @param _amount Amount donated in base token.\n     * @param _feeOverride Payout override configured by an Admin\n     * @dev Reverts with `Unauthorized` if the `msg.sender` is not a privileged role.\n     * @dev Reverts if the fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     * @dev Reverts if the token transfer fails.\n     */\n    function payoutWithAdminOverrides(address _to, uint256 _amount, uint32 _feeOverride) external virtual requiresAuth {\n        _payoutWithFeeMultiplier(_to, _amount, _feeOverride);\n    }\n\n    /**\n     * @notice Pays out an amount of base tokens from the entity to an address. Transfers the fee calculated by fee multiplier to the treasury.\n     * @param _to The address to receive the tokens.\n     * @param _amount Contains the amount being paid out (denominated in the base token's units).\n     * @param _feeMultiplier Value indicating the percentage of the Endaoment fee to go to the Endaoment treasury.\n     * @dev Reverts if the token transfer fails.\n     * @dev Reverts if the fee percentage is larger than 100% (equal to 1e4 when represented as a zoc).\n     */\n    function _payoutWithFeeMultiplier(address _to, uint256 _amount, uint32 _feeMultiplier) internal virtual {\n        if (balance < _amount) revert InsufficientFunds();\n\n        (uint256 _netAmount, uint256 _fee) = _calculateFee(_amount, _feeMultiplier);\n        baseToken.safeTransfer(registry.treasury(), _fee);\n        baseToken.safeTransfer(address(_to), _netAmount);\n\n        unchecked {\n            // unchecked because we've already validated that amount is less than or equal to the balance\n            balance -= _amount;\n        }\n        emit EntityValuePaidOut(address(this), _to, _amount, _fee);\n    }\n\n    /// @dev Internal helper method to calculate the fee on a base token amount for a given fee multiplier.\n    function _calculateFee(\n        uint256 _amount,\n        uint256 _feeMultiplier\n    ) internal virtual pure returns (uint256 _netAmount, uint256 _fee) {\n        if (_feeMultiplier > Math.ZOC) revert InvalidAction();\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            _fee = _amount.zocmul(_feeMultiplier);\n            // unchecked as the _feeMultiplier check with revert above protects against overflow\n            _netAmount = _amount - _fee;\n        }\n    }\n\n    receive() external virtual payable {\n        emit EntityEthReceived(msg.sender, msg.value);\n    }\n}\n"
      },
      "src/Org.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity 0.8.13;\n\nimport { Registry } from \"./Registry.sol\";\nimport { Entity } from \"./Entity.sol\";\n\n/**\n * @notice This contract controls the Org entity.\n */\ncontract Org is Entity {\n\n    /// @notice Tax ID of org\n    bytes32 public orgId;\n\n    /**\n     * @notice One time method to be called at deployment to configure the contract. Required so Org\n     * contracts can be deployed as minimal proxies (clones).\n     * @param _registry The registry to host the Org Entity.\n     * @param _orgId The Org's ID for tax purposes.\n     * @dev The `manager` of the Org is initially set to the zero address and will be updated by role pending an off-chain claim.\n     */\n    function initialize(Registry _registry, bytes32 _orgId) public {\n        // Call to Entity's initializer ensures this can only be called once.\n        __initEntity(_registry, address(0));\n        orgId = _orgId;\n    }\n\n    function setOrgId(bytes32 _orgId) requiresAuth external {\n        orgId = _orgId;\n    }\n\n    /**\n     * @inheritdoc Entity\n     */\n    function entityType() public pure override returns (uint8) {\n        return 1;\n    }\n}\n"
      },
      "src/Portfolio.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity >=0.8.0;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { Registry } from \"./Registry.sol\";\nimport { Entity } from \"./Entity.sol\";\nimport { EndaomentAuth } from \"./lib/auth/EndaomentAuth.sol\";\nimport { RolesAuthority } from \"./lib/auth/authorities/RolesAuthority.sol\";\nimport { Math } from \"./lib/Math.sol\";\n\nabstract contract Portfolio is ERC20, EndaomentAuth {\n    using Math for uint256;\n    Registry public immutable registry;\n    uint256 public cap;\n    uint256 public depositFee;\n    uint256 public redemptionFee;\n    address public immutable asset;\n    bool public didShutdown;\n\n    error InvalidSwapper();\n    error TransferDisallowed();\n    error DepositAfterShutdown();\n    error DidShutdown();\n    error NotEntity();\n    error ExceedsCap();\n    error PercentageOver100();\n    error RoundsToZero();\n    error CallFailed(bytes response);\n\n    /// @notice `sender` has exchanged `assets` (after fees) for `shares`, and transferred those `shares` to `receiver`.\n    /// The sender paid a total of `depositAmount` and was charged `fee` for the transaction.\n    event Deposit(\n        address indexed sender,\n        address indexed receiver,\n        uint256 assets,\n        uint256 shares,\n        uint256 depositAmount,\n        uint256 fee\n    );\n\n    /// @notice `sender` has exchanged `shares` for `assets`, and transferred those `assets` to `receiver`.\n    /// The sender received a net of `redeemedAmount` after the conversion of `assets` into base tokens\n    /// and was charged `fee` for the transaction.\n    event Redeem(\n        address indexed sender,\n        address indexed receiver,\n        uint256 assets,\n        uint256 shares,\n        uint256 redeemedAmount,\n        uint256 fee\n    );\n\n    /// @notice Event emitted when `cap` is set.\n    event CapSet(uint256 cap);\n\n    /// @notice Event emitted when `depositFee` is set.\n    event DepositFeeSet(uint256 fee);\n\n    /// @notice Event emitted when `redemptionFee` is set.\n    event RedemptionFeeSet(uint256 fee);\n\n    /// @notice Event emitted when management takes fees.\n    event FeesTaken(uint256 amount);\n\n    /// @notice Event emitted when admin forcefully swaps portfolio asset balance for baseToken.\n    event Shutdown(uint256 assetAmount, uint256 baseTokenOut);\n\n    /**\n     * @param _registry Endaoment registry.\n     * @param _name Name of the ERC20 Portfolio share tokens.\n     * @param _symbol Symbol of the ERC20 Portfolio share tokens.\n     * @param _cap Amount in baseToken that value of totalAssets should not exceed.\n     * @param _depositFee Percentage fee as ZOC that will go to treasury on asset deposit.\n     * @param _redemptionFee Percentage fee as ZOC that will go to treasury on share redemption.\n     */\n    constructor(Registry _registry, address _asset, string memory _name, string memory _symbol, uint256 _cap, uint256 _depositFee, uint256 _redemptionFee) ERC20(_name, _symbol, ERC20(_asset).decimals()) {\n        registry = _registry;\n        if(_redemptionFee > Math.ZOC) revert PercentageOver100();\n        depositFee = _depositFee;\n        redemptionFee = _redemptionFee;\n        cap = _cap;\n        asset = _asset;\n        __initEndaomentAuth(_registry, \"portfolio\");\n    }\n\n    /**\n     * @notice Function used to determine whether an Entity is active on the registry.\n     * @param _entity The Entity.\n     */\n    function _isEntity(Entity _entity) internal view returns (bool) {\n        return registry.isActiveEntity(_entity);\n    }\n\n    /**\n     * @notice Set the Portfolio cap.\n     * @param _amount Amount, denominated in baseToken.\n     */\n    function setCap(uint256 _amount) external virtual requiresAuth {\n        cap = _amount;\n        emit CapSet(_amount);\n    }\n\n    /**\n     * @notice Set deposit fee.\n     * @param _pct Percentage as ZOC (e.g. 1000 = 10%).\n     */\n    function setDepositFee(uint256 _pct) external virtual requiresAuth {\n        if(_pct > Math.ZOC) revert PercentageOver100();\n        depositFee = _pct;\n        emit DepositFeeSet(_pct);\n    }\n\n    /**\n     * @notice Set redemption fee.\n     * @param _pct Percentage as ZOC (e.g. 1000 = 10%).\n     */\n    function setRedemptionFee(uint256 _pct) external virtual requiresAuth {\n        if(_pct > Math.ZOC) revert PercentageOver100();\n        redemptionFee = _pct;\n        emit RedemptionFeeSet(_pct);\n    }\n\n    /**\n     * @notice Total amount of the underlying asset that is managed by the Portfolio.\n     */\n    function totalAssets() external view virtual returns (uint256);\n\n    /**\n     * @notice Takes some amount of assets from this portfolio as assets under management fee.\n     * @param _amountAssets Amount of assets to take.\n     */\n    function takeFees(uint256 _amountAssets) external virtual;\n\n    /**\n     * @notice Exchange `_amountBaseToken` for some amount of Portfolio shares.\n     * @param _amountBaseToken The amount of the Entity's baseToken to deposit.\n     * @param _data Data that the portfolio needs to make the deposit. In some cases, this will be swap parameters.\n     * @return shares The amount of shares that this deposit yields to the Entity.\n     */\n    function deposit(uint256 _amountBaseToken, bytes calldata _data) virtual external returns (uint256 shares);\n\n    /**\n     * @notice Exchange `_amountShares` for some amount of baseToken.\n     * @param _amountShares The amount of the Entity's portfolio shares to exchange.\n     * @param _data Data that the portfolio needs to make the redemption. In some cases, this will be swap parameters.\n     * @return baseTokenOut The amount of baseToken that this redemption yields to the Entity.\n     */\n    function redeem(uint256 _amountShares, bytes calldata _data) virtual external returns (uint256 baseTokenOut);\n\n    /**\n     * @notice Calculates the amount of shares that the Portfolio should exchange for the amount of assets provided.\n     * @param _amountAssets Amount of assets.\n     */\n    function convertToShares(uint256 _amountAssets) virtual public view returns (uint256);\n\n    /**\n     * @notice Calculates the amount of assets that the Portfolio should exchange for the amount of shares provided.\n     * @param _amountShares Amount of shares.\n     */\n    function convertToAssets(uint256 _amountShares) virtual public view returns (uint256);\n\n    /**\n     * @notice Exit out all assets of portfolio for baseToken. Must persist a mechanism for entities to redeem their shares for baseToken.\n     * @param _data Data that the portfolio needs to exit from asset. In some cases, this will be swap parameters.\n     * @return baseTokenOut The amount of baseToken that this exit yielded.\n     */\n    function shutdown(bytes calldata _data) virtual external returns (uint256 baseTokenOut);\n\n    /// @notice `transfer` disabled on Portfolio tokens.\n    function transfer(address /** to */, uint256 /** amount */) public pure override returns (bool) {\n        revert TransferDisallowed();\n    }\n\n    /// @notice `transferFrom` disabled on Portfolio tokens.\n    function transferFrom(address /** from */, address /** to */, uint256 /** amount */) public pure override returns (bool) {\n        revert TransferDisallowed();\n    }\n\n    /// @notice `approve` disabled on Portfolio tokens.\n    function approve(address /** to */, uint256 /** amount */) public pure override returns (bool) {\n        revert TransferDisallowed();\n    }\n\n    /// @notice `permit` disabled on Portfolio tokens.\n    function permit(\n        address /* owner */,\n        address /* spender */,\n        uint256 /* value */,\n        uint256 /* deadline */,\n        uint8 /* v */,\n        bytes32 /* r */,\n        bytes32 /* s */\n    ) public pure override {\n        revert TransferDisallowed();\n    }\n\n    /**\n     * @notice Permissioned method that allows Endaoment admin to make arbitrary calls acting as this Portfolio.\n     * @param _target The address to which the call will be made.\n     * @param _value The ETH value that should be forwarded with the call.\n     * @param _data The calldata that will be sent with the call.\n     * @return _return The data returned by the call.\n     */\n    function callAsPortfolio(\n        address _target,\n        uint256 _value,\n        bytes memory _data\n    ) external payable requiresAuth returns (bytes memory) {\n        (bool _success, bytes memory _response) = payable(_target).call{value: _value}(_data);\n        if (!_success) revert CallFailed(_response);\n        return _response;\n    }\n\n    /// @dev Internal helper method to calculate the fee on a base token amount for a given fee multiplier.\n    function _calculateFee(\n        uint256 _amount,\n        uint256 _feeMultiplier\n    ) internal pure returns (uint256 _netAmount, uint256 _fee) {\n        if (_feeMultiplier > Math.ZOC) revert PercentageOver100();\n        unchecked {\n            // unchecked as no possibility of overflow with baseToken precision\n            _fee = _amount.zocmul(_feeMultiplier);\n            // unchecked as the _feeMultiplier check with revert above protects against overflow\n            _netAmount = _amount - _fee;\n        }\n    }\n}\n"
      },
      "src/Registry.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity 0.8.13;\n\nimport { Math } from \"./lib/Math.sol\";\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { Auth, Authority } from \"./lib/auth/Auth.sol\"; \nimport { SafeTransferLib } from \"solmate/utils/SafeTransferLib.sol\";\n\nimport { RegistryAuth } from \"./RegistryAuth.sol\";\nimport { Entity } from \"./Entity.sol\";\nimport { ISwapWrapper } from \"./interfaces/ISwapWrapper.sol\";\nimport { Portfolio } from \"./Portfolio.sol\";\n\n// --- Errors ---\nerror Unauthorized();\nerror UnsupportedSwapper();\n\n/**\n * @notice Registry entity - manages Factory and Entity state info.\n */\ncontract Registry is RegistryAuth {\n\n    // --- Storage ---\n\n    /// @notice Treasury address can receives fees.\n    address public treasury;\n\n    /// @notice Base Token address is the stable coin contract used throughout the system.\n    ERC20 public immutable baseToken;\n\n    /// @notice Mapping of approved factory contracts that are allowed to register new Entities.\n    mapping (address => bool) public isApprovedFactory;\n    /// @notice Mapping of active status of entities.\n    mapping (Entity => bool) public isActiveEntity;\n\n    /// @notice Maps entity type to donation fee percentage stored as a zoc, where type(uint32).max represents 0.\n    mapping (uint8 => uint32) defaultDonationFee;\n    /// @notice Maps specific entity receiver to donation fee percentage stored as a zoc.\n    mapping (Entity => uint32) donationFeeReceiverOverride;\n\n    /// @notice Maps entity type to payout fee percentage stored as a zoc, where type(uint32).max represents 0.\n    mapping (uint8 => uint32) defaultPayoutFee;\n    /// @notice Maps specific entity sender to payout fee percentage stored as a zoc.\n    mapping (Entity => uint32) payoutFeeOverride;\n\n    /// @notice Maps sender entity type to receiver entity type to fee percentage as a zoc.\n    mapping (uint8 => mapping(uint8 => uint32)) defaultTransferFee;\n    /// @notice Maps specific entity sender to receiver entity type to fee percentage as a zoc.\n    mapping (Entity => mapping(uint8 => uint32)) transferFeeSenderOverride;\n    /// @notice Maps sender entity type to specific entity receiver to fee percentage as a zoc.\n    mapping (uint8 => mapping(Entity => uint32)) transferFeeReceiverOverride;\n    /// @notice Maps swap wrappers to their enabled/disabled status.\n\n    mapping (ISwapWrapper => bool) public isSwapperSupported;\n    /// @notice Maps portfolios to their enabled/disabled status.\n    mapping (Portfolio => bool) public isActivePortfolio;\n\n    // --- Events ---\n\n    /// @notice The event emitted when a factory is approved (whitelisted) or has it's approval removed.\n    event FactoryApprovalSet(address indexed factory, bool isApproved);\n\n    /// @notice The event emitted when an entity is set active or inactive.\n    event EntityStatusSet(address indexed entity, bool isActive);\n\n    /// @notice The event emitted when a swap wrapper is set active or inactive.\n    event SwapWrapperStatusSet(address indexed swapWrapper, bool isSupported);\n\n    /// @notice The event emitted when a portfolio is set active or inactive.\n    event PortfolioStatusSet(address indexed portfolio, bool isActive);\n\n    /// @notice Emitted when a default donation fee is set for an entity type.\n    event DefaultDonationFeeSet(uint8 indexed entityType, uint32 fee);\n\n    /// @notice Emitted when a donation fee override is set for a specific receiving entity.\n    event DonationFeeReceiverOverrideSet(address indexed entity, uint32 fee);\n\n    /// @notice Emitted when a default payout fee is set for an entity type.\n    event DefaultPayoutFeeSet(uint8 indexed entityType, uint32 fee);\n\n    /// @notice Emitted when a payout fee override is set for a specific sender entity.\n    event PayoutFeeOverrideSet(address indexed entity, uint32 fee);\n\n    /// @notice Emitted when a default transfer fee is set for transfers between entity types.\n    event DefaultTransferFeeSet(uint8 indexed fromEntityType, uint8 indexed toEntityType, uint32 fee);\n\n    /// @notice Emitted when a transfer fee override is set for transfers from an entity to a specific entityType.\n    event TransferFeeSenderOverrideSet(address indexed fromEntity, uint8 indexed toEntityType, uint32 fee);\n\n    /// @notice Emitted when a transfer fee override is set for transfers from an entityType to an entity.\n    event TransferFeeReceiverOverrideSet(uint8 indexed fromEntityType, address indexed toEntity, uint32 fee);\n\n    /// @notice Emitted when the registry treasury contract is changed\n    event TreasuryChanged(address oldTreasury, address indexed newTreasury);\n\n    /**\n     * @notice Modifier for methods that require auth and that the manager cannot access.\n     * @dev Overridden from Auth.sol. Reason: use custom error.\n     */\n    modifier requiresAuth override {\n        if(!isAuthorized(msg.sender, msg.sig)) revert Unauthorized();\n\n        _;\n    }\n\n    // --- Constructor ---\n    constructor(address _admin, address _treasury, ERC20 _baseToken) RegistryAuth(_admin, Authority(address(this))) {\n        treasury = _treasury;\n        emit TreasuryChanged(address(0), _treasury);\n        baseToken = _baseToken;\n    }\n\n    // --- Internal fns ---\n\n    /**\n     * @notice Fee parsing to convert the special \"type(uint32).max\" value to zero, and zero to the \"max\".\n     * @dev After converting, \"type(uint32).max\" will cause overflow/revert when used as a fee percentage multiplier and zero will mean no fee.\n     * @param _value The value to be converted.\n     * @return The parsed fee to use.\n     */\n    function _parseFeeWithFlip(uint32 _value) private pure returns (uint32) {\n        if (_value == 0) {\n            return type(uint32).max;\n        } else if (_value == type(uint32).max) {\n            return 0;\n        } else {\n            return _value;\n        }\n    }\n\n    // --- External fns ---\n\n    /**\n     * @notice Sets a new Endaoment treasury address.\n     * @param _newTreasury The new treasury.\n     */\n     function setTreasury(address _newTreasury) external requiresAuth {\n         emit TreasuryChanged(treasury, _newTreasury);\n         treasury = _newTreasury;\n     }\n\n    /**\n     * @notice Sets the approval state of a factory. Grants the factory permissions to set entity status.\n     * @param _factory The factory whose approval state is to be updated.\n     * @param _isApproved True if the factory should be approved, false otherwise.\n     */\n    function setFactoryApproval(address _factory, bool _isApproved) external requiresAuth {\n        isApprovedFactory[_factory] = _isApproved;\n        emit FactoryApprovalSet(address(_factory), _isApproved);\n    }\n\n    /**\n     * @notice Sets the enable/disable state of an Entity.\n     * @param _entity The entity whose active state is to be updated.\n     * @param _isActive True if the entity should be active, false otherwise.\n     */\n    function setEntityStatus(Entity _entity, bool _isActive) external requiresAuth {\n        isActiveEntity[_entity] = _isActive;\n        emit EntityStatusSet(address(_entity), _isActive);\n    }\n\n    /**\n     * @notice Sets Entity as active. This is a special method to be called only by approved factories.\n     * Other callers should use `setEntityStatus` instead.\n     * @param _entity The entity.\n     */\n    function setEntityActive(Entity _entity) external {\n        if(!isApprovedFactory[msg.sender]) revert Unauthorized();\n        isActiveEntity[_entity] = true;\n        emit EntityStatusSet(address(_entity), true);\n    }\n\n    /**\n     * @notice Sets the enable/disable state of a Portfolio.\n     * @param _portfolio Portfolio.\n     * @param _isActive True if setting portfolio to active, false otherwise.\n     */\n    function setPortfolioStatus(Portfolio _portfolio, bool _isActive) external requiresAuth {\n        isActivePortfolio[_portfolio] = _isActive;\n        emit PortfolioStatusSet(address(_portfolio), _isActive);\n    }\n\n    /**\n     * @notice Gets default donation fee pct (as a zoc) for an Entity.\n     * @param _entity The receiving entity of the donation for which the fee is being fetched.\n     * @return uint32 The default donation fee for the entity's type.\n     * @dev Makes use of _parseFeeWithFlip, so if no default exists, \"max\" will be returned.\n     */\n    function getDonationFee(Entity _entity) external view returns (uint32) {\n       return _parseFeeWithFlip(defaultDonationFee[_entity.entityType()]);\n    }\n\n    /**\n     * @notice Gets lowest possible donation fee pct (as a zoc) for an Entity, among default and override.\n     * @param _entity The receiving entity of the donation for which the fee is being fetched.\n     * @return uint32 The minimum of the default donation fee and the receiver's fee override.\n     * @dev Makes use of _parseFeeWithFlip, so if no default or override exists, \"max\" will be returned.\n     */\n    function getDonationFeeWithOverrides(Entity _entity) external view returns (uint32) {\n        uint32 _default = _parseFeeWithFlip(defaultDonationFee[_entity.entityType()]);\n        uint32 _receiverOverride = _parseFeeWithFlip(donationFeeReceiverOverride[_entity]);\n        return _receiverOverride < _default ? _receiverOverride : _default;\n    }\n\n    /**\n     * @notice Gets default payout fee pct (as a zoc) for an Entity.\n     * @param _entity The sender entity of the payout for which the fee is being fetched.\n     * @return uint32 The default payout fee for the entity's type.\n     * @dev Makes use of _parseFeeWithFlip, so if no default exists, \"max\" will be returned.\n     */\n    function getPayoutFee(Entity _entity) external view returns (uint32) {\n       return _parseFeeWithFlip(defaultPayoutFee[_entity.entityType()]);\n    }\n\n    /**\n     * @notice Gets lowest possible payout fee pct (as a zoc) for an Entity, among default and override.\n     * @param _entity The sender entity of the payout for which the fee is being fetched.\n     * @return uint32 The minimum of the default payout fee and the sender's fee override.\n     * @dev Makes use of _parseFeeWithFlip, so if no default or override exists, \"max\" will be returned.\n     */\n    function getPayoutFeeWithOverrides(Entity _entity) external view returns (uint32) {\n        uint32 _default = _parseFeeWithFlip(defaultPayoutFee[_entity.entityType()]);\n        uint32 _senderOverride = _parseFeeWithFlip(payoutFeeOverride[_entity]);\n        return _senderOverride < _default ? _senderOverride : _default;\n    }\n\n    /**\n     * @notice Gets default transfer fee pct (as a zoc) between sender & receiver Entities.\n     * @param _sender The sending entity of the transfer for which the fee is being fetched.\n     * @param _receiver The receiving entity of the transfer for which the fee is being fetched.\n     * @return uint32 The default transfer fee.\n     * @dev Makes use of _parseFeeWithFlip, so if no default exists, \"type(uint32).max\" will be returned.\n     */\n    function getTransferFee(Entity _sender, Entity _receiver) external view returns (uint32) {\n        return _parseFeeWithFlip(defaultTransferFee[_sender.entityType()][_receiver.entityType()]);\n    }\n\n    /**\n     * @notice Gets lowest possible transfer fee pct (as a zoc) between sender & receiver Entities, among default and overrides.\n     * @param _sender The sending entity of the transfer for which the fee is being fetched.\n     * @param _receiver The receiving entity of the transfer for which the fee is being fetched.\n     * @return uint32 The minimum of the default transfer fee, and sender and receiver overrides.\n     * @dev Makes use of _parseFeeWithFlip, so if no default or overrides exist, \"type(uint32).max\" will be returned.\n     */\n    function getTransferFeeWithOverrides(Entity _sender, Entity _receiver) external view returns (uint32) {\n        uint32 _default = _parseFeeWithFlip(defaultTransferFee[_sender.entityType()][_receiver.entityType()]);\n        uint32 _senderOverride = _parseFeeWithFlip(transferFeeSenderOverride[_sender][_receiver.entityType()]);\n        uint32 _receiverOverride = _parseFeeWithFlip(transferFeeReceiverOverride[_sender.entityType()][_receiver]);\n\n        uint32 _lowestFee = _default;\n        _lowestFee = _senderOverride < _lowestFee ? _senderOverride : _lowestFee;\n        _lowestFee = _receiverOverride < _lowestFee ? _receiverOverride : _lowestFee;\n        return _lowestFee;\n    }\n\n    /**\n     * @notice Sets the default donation fee for an entity type.\n     * @param _entityType Entity type.\n     * @param _fee The fee percentage to be set (a zoc).\n     */\n    function setDefaultDonationFee(uint8 _entityType, uint32 _fee) external requiresAuth {\n        defaultDonationFee[_entityType] = _parseFeeWithFlip(_fee);\n        emit DefaultDonationFeeSet(_entityType, _fee);\n    }\n\n    /**\n     * @notice Sets the donation fee receiver override for a specific entity.\n     * @param _entity Entity.\n     * @param _fee The overriding fee (a zoc).\n     */\n    function setDonationFeeReceiverOverride(Entity _entity, uint32 _fee) external requiresAuth {\n        donationFeeReceiverOverride[_entity] = _parseFeeWithFlip(_fee);\n        emit DonationFeeReceiverOverrideSet(address(_entity), _fee);\n    }\n\n    /**\n     * @notice Sets the default payout fee for an entity type.\n     * @param _entityType Entity type.\n     * @param _fee The fee percentage to be set (a zoc).\n     */\n    function setDefaultPayoutFee(uint8 _entityType, uint32 _fee) external requiresAuth {\n        defaultPayoutFee[_entityType] = _parseFeeWithFlip(_fee);\n        emit DefaultPayoutFeeSet(_entityType, _fee);\n    }\n\n    /**\n     * @notice Sets the payout fee override for a specific entity.\n     * @param _entity Entity.\n     * @param _fee The overriding fee (a zoc).\n     */\n    function setPayoutFeeOverride(Entity _entity, uint32 _fee) external requiresAuth {\n        payoutFeeOverride[_entity] = _parseFeeWithFlip(_fee);\n        emit PayoutFeeOverrideSet(address(_entity), _fee);\n    }\n\n    /**\n     * @notice Sets the default transfer fee for transfers from one specific entity type to another.\n     * @param _fromEntityType The entityType making the transfer.\n     * @param _toEntityType The receiving entityType.\n     * @param _fee The transfer fee percentage (a zoc).\n     */\n    function setDefaultTransferFee(uint8 _fromEntityType, uint8 _toEntityType, uint32 _fee) external requiresAuth {\n        defaultTransferFee[_fromEntityType][_toEntityType] = _parseFeeWithFlip(_fee);\n        emit DefaultTransferFeeSet(_fromEntityType, _toEntityType, _fee);\n    }\n\n    /**\n     * @notice Sets the transfer fee override for transfers from one specific entity to entities of a given type.\n     * @param _fromEntity The entity making the transfer.\n     * @param _toEntityType The receiving entityType.\n     * @param _fee The overriding fee percentage (a zoc).\n     */\n    function setTransferFeeSenderOverride(Entity _fromEntity, uint8 _toEntityType, uint32 _fee) external requiresAuth {\n        transferFeeSenderOverride[_fromEntity][_toEntityType] = _parseFeeWithFlip(_fee);\n        emit TransferFeeSenderOverrideSet(address(_fromEntity), _toEntityType, _fee);\n    }\n\n    /**\n     * @notice Sets the transfer fee override for transfers from entities of a given type to a specific entity.\n     * @param _fromEntityType The entityType making the transfer.\n     * @param _toEntity The receiving entity.\n     * @param _fee The overriding fee percentage (a zoc).\n     */\n    function setTransferFeeReceiverOverride(uint8 _fromEntityType, Entity _toEntity, uint32 _fee) external requiresAuth {\n        transferFeeReceiverOverride[_fromEntityType][_toEntity] = _parseFeeWithFlip(_fee);\n        emit TransferFeeReceiverOverrideSet(_fromEntityType, address(_toEntity), _fee);\n    }\n\n    /**\n     * @notice Sets the enable/disable state of a SwapWrapper. System owners must ensure meticulous review of SwapWrappers before approving them.\n     * @param _swapWrapper A contract that implements ISwapWrapper.\n     * @param _supported `true` if supported, `false` if unsupported.\n     */\n    function setSwapWrapperStatus(ISwapWrapper _swapWrapper, bool _supported) external requiresAuth {\n        isSwapperSupported[_swapWrapper] = _supported;\n        emit SwapWrapperStatusSet(address(_swapWrapper), _supported);\n    }\n}\n"
      },
      "src/RegistryAuth.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity 0.8.13;\n\nimport { Auth, Authority } from \"./lib/auth/Auth.sol\"; \nimport { RolesAuthority } from \"./lib/auth/authorities/RolesAuthority.sol\";\n\n// --- Errors ---\nerror OwnershipInvalid();\n\n/**\n * @notice RegistryAuth - contract to control ownership of the Registry.\n */\ncontract RegistryAuth is RolesAuthority {\n\n    /// @notice Emitted when the first step of an ownership transfer (proposal) is done.\n    event OwnershipTransferProposed(address indexed user, address indexed newOwner);\n\n    /// @notice Emitted when the second step of an ownership transfer (claim) is done.\n    event OwnershipChanged(address indexed owner, address indexed newOwner);\n\n    // --- Storage ---\n    /// @notice Pending owner for 2 step ownership transfer\n    address public pendingOwner;\n\n    // --- Constructor ---\n    constructor(address _owner, Authority _authority) RolesAuthority(_owner, _authority) {}\n\n    /**\n     * @notice Starts the 2 step process of transferring registry authorization to a new owner.\n     * @param _newOwner Proposed new owner of registry authorization.\n     */\n    function transferOwnership(address _newOwner) external requiresAuth {\n        pendingOwner = _newOwner;\n\n        emit OwnershipTransferProposed(msg.sender, _newOwner);\n    }\n\n    /**\n     * @notice Completes the 2 step process of transferring registry authorization to a new owner.\n     * This function must be called by the proposed new owner.\n     */\n    function claimOwnership() external {\n        if (msg.sender != pendingOwner) revert OwnershipInvalid();\n        emit OwnershipChanged(owner, pendingOwner);\n        owner = pendingOwner;\n        pendingOwner = address(0);\n    }\n\n    /**\n     * @notice Old approach of setting a new owner in a single step.\n     * @dev This function throws an error to force use of the new 2-step approach.\n     */\n    function setOwner(address /*newOwner*/ ) public view override requiresAuth {\n        revert OwnershipInvalid();\n    }\n}\n"
      },
      "src/interfaces/ISwapWrapper.sol": {
        "content": "//SPDX-License-Identifier: BSD 3-Clause\npragma solidity >=0.8.0;\n\nerror ETHAmountInMismatch();\n\n/**\n * @notice ISwapWrapper is the interface that all swap wrappers should implement.\n * This will be used to support swap protocols like Uniswap V2 and V3, Sushiswap, 1inch, etc.\n */\ninterface ISwapWrapper {\n\n    /// @notice Event emitted after a successful swap.\n    event WrapperSwapExecuted(address indexed tokenIn, address indexed tokenOut, address sender, address indexed recipient, uint256 amountIn, uint256 amountOut);\n\n    /// @notice Name of swap wrapper for UX readability.\n    function name() external returns (string memory);\n\n    /**\n     * @notice Swap function. Generally we expect the implementer to call some exactAmountIn-like swap method, and so the documentation\n     * is written with this in mind. However, the method signature is general enough to support exactAmountOut swaps as well.\n     * @param _tokenIn Token to be swapped (or 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH).\n     * @param _tokenOut Token to receive (or 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH).\n     * @param _recipient Receiver of `_tokenOut`.\n     * @param _amount Amount of `_tokenIn` that should be swapped.\n     * @param _data Additional data that the swap wrapper may require to execute the swap.\n     * @return Amount of _tokenOut received.\n     */\n    function swap(address _tokenIn, address _tokenOut, address _recipient, uint256 _amount, bytes calldata _data) external payable returns (uint256);\n}\n"
      },
      "src/lib/Math.sol": {
        "content": "// SPDX-License-Identifier: BSD 3-Clause\npragma solidity 0.8.13;\n\nlibrary Math {\n    uint256 internal constant ZOC = 1e4;\n\n    /**\n     * @dev Multiply 2 numbers where at least one is a zoc, return product in original units of the other number.\n     */\n    function zocmul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        z = x * y;\n        unchecked {\n            z /= ZOC;\n        }\n    }\n\n    // Below is WAD math from solmate's FixedPointMathLib.\n    // https://github.com/Rari-Capital/solmate/blob/c8278b3cb948cffda3f1de5a401858035f262060/src/utils/FixedPointMathLib.sol\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 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    // For tokens with 6 decimals like USDC, these scale by 1e6 (one million).\n    function mulMilDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, 1e6); // Equivalent to (x * y) / 1e6 rounded down.\n    }\n\n    function divMilDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, 1e6, y); // Equivalent to (x * 1e6) / y rounded down.\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        assembly {\n            // Store x * y in z for now.\n            z := mul(x, y)\n\n            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n                revert(0, 0)\n            }\n\n            // Divide z by the denominator.\n            z := div(z, denominator)\n        }\n    }\n}\n"
      },
      "src/lib/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized reentrancy protection for smart contracts.\n/// @author Modified Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)\nabstract contract ReentrancyGuard {\n    uint256 private reentrancyStatus;\n    error Reentrancy();\n\n    function __initReentrancyGuard() internal {\n        if(reentrancyStatus != 0) revert Reentrancy();\n        reentrancyStatus = 1;\n    }\n\n    modifier nonReentrant() {\n        if(reentrancyStatus != 1) revert Reentrancy();\n\n        reentrancyStatus = 2;\n\n        _;\n\n        reentrancyStatus = 1;\n    }\n}\n"
      },
      "src/lib/auth/Auth.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n// This contract is modified from Solmate only to make requiresAuth virtual on line 26\n\n/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\nabstract contract Auth {\n    event OwnerUpdated(address indexed user, address indexed newOwner);\n\n    event AuthorityUpdated(address indexed user, Authority indexed newAuthority);\n\n    address public owner;\n\n    Authority public authority;\n\n    constructor(address _owner, Authority _authority) {\n        owner = _owner;\n        authority = _authority;\n\n        emit OwnerUpdated(msg.sender, _owner);\n        emit AuthorityUpdated(msg.sender, _authority);\n    }\n\n    modifier requiresAuth virtual {\n        require(isAuthorized(msg.sender, msg.sig), \"UNAUTHORIZED\");\n\n        _;\n    }\n\n    function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {\n        Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\n\n        // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be\n        // aware that this makes protected functions uncallable even to the owner if the authority is out of order.\n        return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;\n    }\n\n    function setAuthority(Authority newAuthority) public virtual {\n        // We check if the caller is the owner first because we want to ensure they can\n        // always swap out the authority even if it's reverting or using up a lot of gas.\n        require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));\n\n        authority = newAuthority;\n\n        emit AuthorityUpdated(msg.sender, newAuthority);\n    }\n\n    function setOwner(address newOwner) public virtual requiresAuth {\n        owner = newOwner;\n\n        emit OwnerUpdated(msg.sender, newOwner);\n    }\n}\n\n/// @notice A generic interface for a contract which provides authorization data to an Auth instance.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\ninterface Authority {\n    function canCall(\n        address user,\n        address target,\n        bytes4 functionSig\n    ) external view returns (bool);\n}\n"
      },
      "src/lib/auth/EndaomentAuth.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport { RolesAuthority } from './authorities/RolesAuthority.sol';\n\n/**\n * @notice An abstract Auth that contracts in the Endaoment ecosystem can inherit from. It is based on\n * the `Auth.sol` contract from Solmate, but does not inherit from it. Most of the functionality\n * is either slightly different, or not needed. In particular:\n * - EndaomentAuth uses an initializer such that it can be deployed with minimal proxies.\n * - EndaomentAuth contracts reference a RolesAuthority, not just an Authority, when looking up permissions.\n *   In the Endaoment ecosystem, this is assumed to be the Registry.\n * - EndaomentAuth contracts do not have an owner, but instead grant ubiquitous permission to its RoleAuthority's\n *   owner. In the Endaoment ecosystem, this is assumed to be the board of directors multi-sig.\n * - EndaomentAuth contracts can optionally declare themselves a \"special target\" at deploy time. Instead of passing\n *   their address to the authority when looking up their permissions, they'll instead pass the special target bytes.\n *   See documentation on `specialTarget` for more information.\n *\n */\nabstract contract EndaomentAuth {\n\n    /// @notice Thrown when an account without proper permissions calls a privileged method.\n    error Unauthorized();\n\n    /// @notice Thrown if there is an attempt to deploy with address 0 as the authority.\n    error InvalidAuthority();\n\n    /// @notice Thrown if there is a second call to initialize.\n    error AlreadyInitialized();\n\n    /// @notice The contract used to source permissions for accounts targeting this contract.\n    RolesAuthority public authority;\n\n    /**\n     * @notice If set to a non-zero value, this contract will pass these byes as the target contract\n     * to the RolesAuthority's `canCall` method, rather than its own contract. This allows a single\n     * RolesAuthority permission to manage permissions simultaneously for a group of contracts that\n     * identify themselves as a certain type. For example: set a permission for all \"entity\" contracts.\n     */\n    bytes20 public specialTarget;\n\n    /**\n     * @notice One time method to be called at deployment to configure the contract. Required so EndaomentAuth\n     * contracts can be deployed as minimal proxies (clones).\n     * @param _authority Contract that will be used to source permissions for accounts targeting this contract.\n     * @param _specialTarget The bytes that this contract will pass as the \"target\" when looking up permissions\n     * from the authority. If set to empty bytes, this contract will pass its own address instead.\n     */\n    function __initEndaomentAuth(RolesAuthority _authority, bytes20 _specialTarget) internal virtual {\n        if (address(_authority) == address(0)) revert InvalidAuthority();\n        if (address(authority) != address(0)) revert AlreadyInitialized();\n        authority = _authority;\n        specialTarget = _specialTarget;\n    }\n\n    /**\n     * @notice Modifier for methods that require authorization to execute.\n     */\n    modifier requiresAuth virtual {\n        if(!isAuthorized(msg.sender, msg.sig)) revert Unauthorized();\n        _;\n    }\n\n     /**\n     * @notice Internal method that asks the authority whether the caller has permission to execute a method.\n     * @param user The account attempting to call a permissioned method on this contract\n     * @param functionSig The signature hash of the permissioned method being invoked.\n     */\n    function isAuthorized(address user, bytes4 functionSig) internal virtual view returns (bool) {\n        RolesAuthority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\n        address _target = specialTarget == \"\" ? address(this) : address(specialTarget);\n\n        // The caller has permission on authority, or the caller is the RolesAuthority owner\n        return auth.canCall(user, _target, functionSig) || user == auth.owner();\n    }\n}\n"
      },
      "src/lib/auth/authorities/RolesAuthority.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n// This contract is modified from Solmate only to import modified Auth.sol on line 5\nimport {Auth, Authority} from \"../Auth.sol\";\n\n/// @notice Role based Authority that supports up to 256 roles.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/authorities/RolesAuthority.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol)\ncontract RolesAuthority is Auth, Authority {\n    /*///////////////////////////////////////////////////////////////\n                                  EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);\n\n    event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);\n\n    event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);\n\n    /*///////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}\n\n    /*///////////////////////////////////////////////////////////////\n                            ROLE/USER STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    mapping(address => bytes32) public getUserRoles;\n\n    mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;\n\n    mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;\n\n    function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {\n        return (uint256(getUserRoles[user]) >> role) & 1 != 0;\n    }\n\n    function doesRoleHaveCapability(\n        uint8 role,\n        address target,\n        bytes4 functionSig\n    ) public view virtual returns (bool) {\n        return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                          AUTHORIZATION LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function canCall(\n        address user,\n        address target,\n        bytes4 functionSig\n    ) public view virtual override returns (bool) {\n        return\n            isCapabilityPublic[target][functionSig] ||\n            bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                  ROLE CAPABILITY CONFIGURATION LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function setPublicCapability(\n        address target,\n        bytes4 functionSig,\n        bool enabled\n    ) public virtual requiresAuth {\n        isCapabilityPublic[target][functionSig] = enabled;\n\n        emit PublicCapabilityUpdated(target, functionSig, enabled);\n    }\n\n    function setRoleCapability(\n        uint8 role,\n        address target,\n        bytes4 functionSig,\n        bool enabled\n    ) public virtual requiresAuth {\n        if (enabled) {\n            getRolesWithCapability[target][functionSig] |= bytes32(1 << role);\n        } else {\n            getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);\n        }\n\n        emit RoleCapabilityUpdated(role, target, functionSig, enabled);\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                      USER ROLE ASSIGNMENT LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function setUserRole(\n        address user,\n        uint8 role,\n        bool enabled\n    ) public virtual requiresAuth {\n        if (enabled) {\n            getUserRoles[user] |= bytes32(1 << role);\n        } else {\n            getUserRoles[user] &= ~bytes32(1 << role);\n        }\n\n        emit UserRoleUpdated(user, role, enabled);\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "murky/=lib/murky/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "solmate/=lib/solmate/src/",
        "weird-erc20/=lib/solmate/lib/weird-erc20/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 9999999
      },
      "metadata": {
        "bytecodeHash": "ipfs"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "london",
      "libraries": {}
    }
  }}