File size: 58,694 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
{
  "language": "Solidity",
  "sources": {
    "contracts/commands/AutoTakeProfitCommand.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// AutoTakeProfitCommand.sol\n\n// Copyright (C) 2022-2022 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\npragma solidity ^0.8.0;\nimport { ManagerLike } from \"../interfaces/ManagerLike.sol\";\nimport { BotLike } from \"../interfaces/BotLike.sol\";\nimport { MPALike } from \"../interfaces/MPALike.sol\";\nimport { ServiceRegistry } from \"../ServiceRegistry.sol\";\nimport { McdView } from \"../McdView.sol\";\nimport { BaseMPACommand } from \"./BaseMPACommand.sol\";\n\n/// @title An Auto Take Profit Command for the AutomationBot\ncontract AutoTakeProfitCommand is BaseMPACommand {\n    constructor(ServiceRegistry _serviceRegistry) BaseMPACommand(_serviceRegistry) {}\n\n    struct AutoTakeProfitTriggerData {\n        uint256 cdpId;\n        uint16 triggerType;\n        uint256 executionPrice;\n        uint32 maxBaseFeeInGwei;\n    }\n\n    /// @notice Returns the correctness of the vault state post execution of the command.\n    /// @param cdpId The CDP id\n    /// @return Correctness of the trigger execution\n    function isExecutionCorrect(uint256 cdpId, bytes memory) external view override returns (bool) {\n        address viewAddress = ServiceRegistry(serviceRegistry).getRegisteredService(MCD_VIEW_KEY);\n        McdView viewerContract = McdView(viewAddress);\n        (uint256 collateral, uint256 debt) = viewerContract.getVaultInfo(cdpId);\n        return !(collateral > 0 || debt > 0);\n    }\n\n    /// @notice Checks the validity of the trigger data when the trigger is executed\n    /// @param _cdpId The CDP id\n    /// @param triggerData  Encoded AutoTakeProfitTriggerData struct\n    /// @return Correctness of the trigger data during execution\n    function isExecutionLegal(uint256 _cdpId, bytes memory triggerData)\n        external\n        view\n        override\n        returns (bool)\n    {\n        AutoTakeProfitTriggerData memory autoTakeProfitTriggerData = abi.decode(\n            triggerData,\n            (AutoTakeProfitTriggerData)\n        );\n\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n        bytes32 ilk = manager.ilks(_cdpId);\n        McdView mcdView = McdView(serviceRegistry.getRegisteredService(MCD_VIEW_KEY));\n        uint256 nextPrice = mcdView.getNextPrice(ilk);\n        uint256 nextCollRatio = mcdView.getRatio(_cdpId, true);\n\n        require(\n            ManagerLike(ServiceRegistry(serviceRegistry).getRegisteredService(CDP_MANAGER_KEY))\n                .owns(_cdpId) != address(0),\n            \"auto-take-profit/no-owner\"\n        );\n        bool vaultNotEmpty = nextCollRatio != 0; // MCD_VIEW contract returns 0 (instead of infinity) as a collateralisation ratio of empty vault\n        return\n            vaultNotEmpty &&\n            baseFeeIsValid(autoTakeProfitTriggerData.maxBaseFeeInGwei) &&\n            nextPrice >= autoTakeProfitTriggerData.executionPrice;\n    }\n\n    /// @notice Checks the validity of the trigger data when the trigger is created\n    /// @param _cdpId The CDP id\n    /// @param triggerData  Encoded AutoTakeProfitTriggerData struct\n    /// @return Correctness of the trigger data\n    function isTriggerDataValid(uint256 _cdpId, bytes memory triggerData)\n        external\n        view\n        override\n        returns (bool)\n    {\n        AutoTakeProfitTriggerData memory autoTakeProfitTriggerData = abi.decode(\n            triggerData,\n            (AutoTakeProfitTriggerData)\n        );\n\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n        bytes32 ilk = manager.ilks(_cdpId);\n        McdView mcdView = McdView(serviceRegistry.getRegisteredService(MCD_VIEW_KEY));\n        uint256 nextPrice = mcdView.getNextPrice(ilk);\n\n \n        return\n            _cdpId == autoTakeProfitTriggerData.cdpId &&\n            (autoTakeProfitTriggerData.triggerType == 7 ||\n                autoTakeProfitTriggerData.triggerType == 8);\n    }\n\n    /// @notice Executes the trigger\n    /// @param executionData Execution data from the Automation Worker\n    /// @param triggerData  Encoded AutoTakeProfitTriggerData struct\n    function execute(\n        bytes calldata executionData,\n        uint256,\n        bytes memory triggerData\n    ) external override {\n        AutoTakeProfitTriggerData memory autoTakeProfitTriggerData = abi.decode(\n            triggerData,\n            (AutoTakeProfitTriggerData)\n        );\n\n        address mpaAddress = ServiceRegistry(serviceRegistry).getRegisteredService(MPA_KEY);\n\n        if (autoTakeProfitTriggerData.triggerType == 7) {\n            validateSelector(MPALike.closeVaultExitCollateral.selector, executionData);\n        } else if (autoTakeProfitTriggerData.triggerType == 8) {\n            validateSelector(MPALike.closeVaultExitDai.selector, executionData);\n        } else revert(\"auto-take-profit/unsupported-trigger-type\");\n\n        (bool status, ) = mpaAddress.delegatecall(executionData);\n        require(status, \"auto-take-profit/execution-failed\");\n    }\n}\n"
    },
    "contracts/interfaces/ManagerLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface ManagerLike {\n    function cdpCan(\n        address owner,\n        uint256 cdpId,\n        address allowedAddr\n    ) external view returns (uint256);\n\n    function vat() external view returns (address);\n\n    function ilks(uint256) external view returns (bytes32);\n\n    function owns(uint256) external view returns (address);\n\n    function urns(uint256) external view returns (address);\n\n    function cdpAllow(\n        uint256 cdp,\n        address usr,\n        uint256 ok\n    ) external;\n\n    function frob(\n        uint256,\n        int256,\n        int256\n    ) external;\n\n    function flux(\n        uint256,\n        address,\n        uint256\n    ) external;\n\n    function move(\n        uint256,\n        address,\n        uint256\n    ) external;\n\n    function exit(\n        address,\n        uint256,\n        address,\n        uint256\n    ) external;\n}\n"
    },
    "contracts/interfaces/BotLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface BotLike {\n    function addRecord(\n        uint256 cdpId,\n        uint256 triggerType,\n        uint256 replacedTriggerId,\n        bytes memory triggerData\n    ) external;\n\n    function removeRecord(\n        // This function should be executed allways in a context of AutomationBot address not DsProxy,\n        //msg.sender should be dsProxy\n        uint256 cdpId,\n        uint256 triggerId\n    ) external;\n\n    function execute(\n        bytes calldata executionData,\n        uint256 cdpId,\n        bytes calldata triggerData,\n        address commandAddress,\n        uint256 triggerId,\n        uint256 daiCoverage\n    ) external;\n}\n"
    },
    "contracts/interfaces/MPALike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface MPALike {\n    struct CdpData {\n        address gemJoin;\n        address payable fundsReceiver;\n        uint256 cdpId;\n        bytes32 ilk;\n        uint256 requiredDebt;\n        uint256 borrowCollateral;\n        uint256 withdrawCollateral;\n        uint256 withdrawDai;\n        uint256 depositDai;\n        uint256 depositCollateral;\n        bool skipFL;\n        string methodName;\n    }\n\n    struct AddressRegistry {\n        address jug;\n        address manager;\n        address multiplyProxyActions;\n        address lender;\n        address exchange;\n    }\n\n    struct ExchangeData {\n        address fromTokenAddress;\n        address toTokenAddress;\n        uint256 fromTokenAmount;\n        uint256 toTokenAmount;\n        uint256 minToTokenAmount;\n        address exchangeAddress;\n        bytes _exchangeCalldata;\n    }\n\n    function increaseMultiple(\n        ExchangeData calldata exchangeData,\n        CdpData memory cdpData,\n        AddressRegistry calldata addressRegistry\n    ) external;\n\n    function decreaseMultiple(\n        ExchangeData calldata exchangeData,\n        CdpData memory cdpData,\n        AddressRegistry calldata addressRegistry\n    ) external;\n\n    function closeVaultExitCollateral(\n        ExchangeData calldata exchangeData,\n        CdpData memory cdpData,\n        AddressRegistry calldata addressRegistry\n    ) external;\n\n    function closeVaultExitDai(\n        ExchangeData calldata exchangeData,\n        CdpData memory cdpData,\n        AddressRegistry calldata addressRegistry\n    ) external;\n}\n"
    },
    "contracts/ServiceRegistry.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// ServiceRegistry.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\npragma solidity ^0.8.0;\n\ncontract ServiceRegistry {\n    uint256 public constant MAX_DELAY = 30 days;\n\n    mapping(bytes32 => uint256) public lastExecuted;\n    mapping(bytes32 => address) private namedService;\n    address public owner;\n    uint256 public requiredDelay;\n\n    modifier validateInput(uint256 len) {\n        require(msg.data.length == len, \"registry/illegal-padding\");\n        _;\n    }\n\n    modifier delayedExecution() {\n        bytes32 operationHash = keccak256(msg.data);\n        uint256 reqDelay = requiredDelay;\n\n        /* solhint-disable not-rely-on-time */\n        if (lastExecuted[operationHash] == 0 && reqDelay > 0) {\n            // not called before, scheduled for execution\n            lastExecuted[operationHash] = block.timestamp;\n            emit ChangeScheduled(operationHash, block.timestamp + reqDelay, msg.data);\n        } else {\n            require(\n                block.timestamp - reqDelay > lastExecuted[operationHash],\n                \"registry/delay-too-small\"\n            );\n            emit ChangeApplied(operationHash, block.timestamp, msg.data);\n            _;\n            lastExecuted[operationHash] = 0;\n        }\n        /* solhint-enable not-rely-on-time */\n    }\n\n    modifier onlyOwner() {\n        require(msg.sender == owner, \"registry/only-owner\");\n        _;\n    }\n\n    constructor(uint256 initialDelay) {\n        require(initialDelay <= MAX_DELAY, \"registry/invalid-delay\");\n        requiredDelay = initialDelay;\n        owner = msg.sender;\n    }\n\n    function transferOwnership(address newOwner)\n        external\n        onlyOwner\n        validateInput(36)\n        delayedExecution\n    {\n        owner = newOwner;\n    }\n\n    function changeRequiredDelay(uint256 newDelay)\n        external\n        onlyOwner\n        validateInput(36)\n        delayedExecution\n    {\n        require(newDelay <= MAX_DELAY, \"registry/invalid-delay\");\n        requiredDelay = newDelay;\n    }\n\n    function getServiceNameHash(string memory name) external pure returns (bytes32) {\n        return keccak256(abi.encodePacked(name));\n    }\n\n    function addNamedService(bytes32 serviceNameHash, address serviceAddress)\n        external\n        onlyOwner\n        validateInput(68)\n        delayedExecution\n    {\n        require(namedService[serviceNameHash] == address(0), \"registry/service-override\");\n        namedService[serviceNameHash] = serviceAddress;\n    }\n\n    function updateNamedService(bytes32 serviceNameHash, address serviceAddress)\n        external\n        onlyOwner\n        validateInput(68)\n        delayedExecution\n    {\n        require(namedService[serviceNameHash] != address(0), \"registry/service-does-not-exist\");\n        namedService[serviceNameHash] = serviceAddress;\n    }\n\n    function removeNamedService(bytes32 serviceNameHash) external onlyOwner validateInput(36) {\n        require(namedService[serviceNameHash] != address(0), \"registry/service-does-not-exist\");\n        namedService[serviceNameHash] = address(0);\n        emit NamedServiceRemoved(serviceNameHash);\n    }\n\n    function getRegisteredService(string memory serviceName) external view returns (address) {\n        return namedService[keccak256(abi.encodePacked(serviceName))];\n    }\n\n    function getServiceAddress(bytes32 serviceNameHash) external view returns (address) {\n        return namedService[serviceNameHash];\n    }\n\n    function clearScheduledExecution(bytes32 scheduledExecution)\n        external\n        onlyOwner\n        validateInput(36)\n    {\n        require(lastExecuted[scheduledExecution] > 0, \"registry/execution-not-scheduled\");\n        lastExecuted[scheduledExecution] = 0;\n        emit ChangeCancelled(scheduledExecution);\n    }\n\n    event ChangeScheduled(bytes32 dataHash, uint256 scheduledFor, bytes data);\n    event ChangeApplied(bytes32 dataHash, uint256 appliedAt, bytes data);\n    event ChangeCancelled(bytes32 dataHash);\n    event NamedServiceRemoved(bytes32 nameHash);\n}\n"
    },
    "contracts/McdView.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// McdView.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\npragma solidity ^0.8.0;\nimport \"./interfaces/ManagerLike.sol\";\nimport \"./interfaces/ICommand.sol\";\nimport \"./interfaces/BotLike.sol\";\nimport \"./ServiceRegistry.sol\";\n\nimport \"./interfaces/SpotterLike.sol\";\nimport \"./interfaces/VatLike.sol\";\nimport \"./interfaces/OsmMomLike.sol\";\nimport \"./interfaces/OsmLike.sol\";\nimport \"./external/DSMath.sol\";\n\n/// @title Getter contract for Vault info from Maker protocol\ncontract McdView is DSMath {\n    ManagerLike public manager;\n    VatLike public vat;\n    SpotterLike public spotter;\n    OsmMomLike public osmMom;\n    address public owner;\n    mapping(address => bool) public whitelisted;\n\n    constructor(\n        address _vat,\n        address _manager,\n        address _spotter,\n        address _mom,\n        address _owner\n    ) {\n        manager = ManagerLike(_manager);\n        vat = VatLike(_vat);\n        spotter = SpotterLike(_spotter);\n        osmMom = OsmMomLike(_mom);\n        owner = _owner;\n    }\n\n    function approve(address _allowedReader, bool isApproved) external {\n        require(msg.sender == owner, \"mcd-view/not-authorised\");\n        whitelisted[_allowedReader] = isApproved;\n    }\n\n    /// @notice Gets Vault info (collateral, debt)\n    /// @param vaultId Id of the Vault\n    function getVaultInfo(uint256 vaultId) public view returns (uint256, uint256) {\n        address urn = manager.urns(vaultId);\n        bytes32 ilk = manager.ilks(vaultId);\n\n        (uint256 collateral, uint256 debt) = vat.urns(ilk, urn);\n        (, uint256 rate, , , ) = vat.ilks(ilk);\n\n        return (collateral, rmul(debt, rate));\n    }\n\n    /// @notice Gets a price of the asset\n    /// @param ilk Ilk of the Vault\n    function getPrice(bytes32 ilk) public view returns (uint256) {\n        (, uint256 mat) = spotter.ilks(ilk);\n        (, , uint256 spot, , ) = vat.ilks(ilk);\n\n        return div(rmul(rmul(spot, spotter.par()), mat), 10**9);\n    }\n\n    /// @notice Gets oracle next price of the asset\n    /// @param ilk Ilk of the Vault\n    function getNextPrice(bytes32 ilk) public view returns (uint256) {\n        require(whitelisted[msg.sender], \"mcd-view/not-whitelisted\");\n        OsmLike osm = OsmLike(osmMom.osms(ilk));\n        (bytes32 val, bool status) = osm.peep();\n        require(status, \"mcd-view/osm-price-error\");\n        return uint256(val);\n    }\n\n    /// @notice Gets Vaults ratio\n    /// @param vaultId Id of the Vault\n    function getRatio(uint256 vaultId, bool useNextPrice) public view returns (uint256) {\n        bytes32 ilk = manager.ilks(vaultId);\n        uint256 price = useNextPrice ? getNextPrice(ilk) : getPrice(ilk);\n        (uint256 collateral, uint256 debt) = getVaultInfo(vaultId);\n        if (debt == 0) return 0;\n        return wdiv(wmul(collateral, price), debt);\n    }\n}\n"
    },
    "contracts/commands/BaseMPACommand.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// BaseMPACommand.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\npragma solidity ^0.8.0;\n\nimport { RatioUtils } from \"../libs/RatioUtils.sol\";\nimport { ICommand } from \"../interfaces/ICommand.sol\";\nimport { ManagerLike } from \"../interfaces/ManagerLike.sol\";\nimport { ServiceRegistry } from \"../ServiceRegistry.sol\";\nimport { McdView } from \"../McdView.sol\";\nimport { AutomationBot } from \"../AutomationBot.sol\";\n\nabstract contract BaseMPACommand is ICommand {\n    using RatioUtils for uint256;\n\n    string public constant MCD_VIEW_KEY = \"MCD_VIEW\";\n    string public constant CDP_MANAGER_KEY = \"CDP_MANAGER\";\n    string public constant MPA_KEY = \"MULTIPLY_PROXY_ACTIONS\";\n    string public constant MCD_SPOT_KEY = \"MCD_SPOT\";\n    string public constant MCD_VAT_KEY = \"MCD_VAT\";\n\n    uint256 public constant MIN_ALLOWED_DEVIATION = 50;\n\n    ServiceRegistry public immutable serviceRegistry;\n\n    constructor(ServiceRegistry _serviceRegistry) {\n        serviceRegistry = _serviceRegistry;\n    }\n\n    function getVaultAndMarketInfo(uint256 cdpId)\n        public\n        view\n        returns (\n            uint256 collRatio,\n            uint256 nextCollRatio,\n            uint256 currPrice,\n            uint256 nextPrice,\n            bytes32 ilk\n        )\n    {\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n        ilk = manager.ilks(cdpId);\n\n        McdView mcdView = McdView(serviceRegistry.getRegisteredService(MCD_VIEW_KEY));\n        collRatio = mcdView.getRatio(cdpId, false);\n        nextCollRatio = mcdView.getRatio(cdpId, true);\n        currPrice = mcdView.getPrice(ilk);\n        nextPrice = mcdView.getNextPrice(ilk);\n    }\n\n    function getVaultDebt(uint256 cdpId) internal view returns (uint256) {\n        McdView mcdView = McdView(serviceRegistry.getRegisteredService(MCD_VIEW_KEY));\n        (, uint256 debt) = mcdView.getVaultInfo(cdpId);\n        return debt;\n    }\n\n    function baseFeeIsValid(uint256 maxAcceptableBaseFeeInGwei) public view returns (bool) {\n        return block.basefee <= maxAcceptableBaseFeeInGwei * (10**9);\n    }\n\n    function deviationIsValid(uint256 deviation) public pure returns (bool) {\n        return deviation >= MIN_ALLOWED_DEVIATION;\n    }\n\n    function validateTriggerType(uint16 triggerType, uint16 expectedTriggerType) public pure {\n        require(triggerType == expectedTriggerType, \"base-mpa-command/type-not-supported\");\n    }\n\n    function validateSelector(bytes4 expectedSelector, bytes memory executionData) public pure {\n        bytes4 selector = abi.decode(executionData, (bytes4));\n        require(selector == expectedSelector, \"base-mpa-command/invalid-selector\");\n    }\n\n    function executeMPAMethod(bytes memory executionData) internal {\n        (bool status, bytes memory reason) = serviceRegistry\n            .getRegisteredService(MPA_KEY)\n            .delegatecall(executionData);\n        require(status, string(reason));\n    }\n\n    function recreateTrigger(\n        uint256 cdpId,\n        uint16 triggerType,\n        bytes memory triggerData\n    ) internal virtual {\n        (bool status, ) = msg.sender.delegatecall(\n            abi.encodeWithSelector(\n                AutomationBot(msg.sender).addTrigger.selector,\n                cdpId,\n                triggerType,\n                0,\n                triggerData\n            )\n        );\n        require(status, \"base-mpa-command/trigger-recreation-failed\");\n    }\n}\n"
    },
    "contracts/interfaces/ICommand.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface ICommand {\n    function isTriggerDataValid(uint256 _cdpId, bytes memory triggerData)\n        external\n        view\n        returns (bool);\n\n    function isExecutionCorrect(uint256 cdpId, bytes memory triggerData)\n        external\n        view\n        returns (bool);\n\n    function isExecutionLegal(uint256 cdpId, bytes memory triggerData) external view returns (bool);\n\n    function execute(\n        bytes calldata executionData,\n        uint256 cdpId,\n        bytes memory triggerData\n    ) external;\n}\n"
    },
    "contracts/interfaces/SpotterLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface IPipInterface {\n    function read() external returns (bytes32);\n}\n\ninterface SpotterLike {\n    function ilks(bytes32) external view returns (IPipInterface pip, uint256 mat);\n\n    function par() external view returns (uint256);\n}\n"
    },
    "contracts/interfaces/VatLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface VatLike {\n    function urns(bytes32, address) external view returns (uint256 ink, uint256 art);\n\n    function ilks(bytes32)\n        external\n        view\n        returns (\n            uint256 art, // Total Normalised Debt      [wad]\n            uint256 rate, // Accumulated Rates         [ray]\n            uint256 spot, // Price with Safety Margin  [ray]\n            uint256 line, // Debt Ceiling              [rad]\n            uint256 dust // Urn Debt Floor             [rad]\n        );\n\n    function gem(bytes32, address) external view returns (uint256); // [wad]\n\n    function can(address, address) external view returns (uint256);\n\n    function dai(address) external view returns (uint256);\n\n    function frob(\n        bytes32,\n        address,\n        address,\n        address,\n        int256,\n        int256\n    ) external;\n\n    function hope(address) external;\n\n    function move(\n        address,\n        address,\n        uint256\n    ) external;\n\n    function fork(\n        bytes32,\n        address,\n        address,\n        int256,\n        int256\n    ) external;\n}\n"
    },
    "contracts/interfaces/OsmMomLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface OsmMomLike {\n    function osms(bytes32) external view returns (address);\n}\n"
    },
    "contracts/interfaces/OsmLike.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ninterface OsmLike {\n    function peep() external view returns (bytes32, bool);\n\n    function bud(address) external view returns (uint256);\n\n    function kiss(address a) external;\n}\n"
    },
    "contracts/external/DSMath.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\ncontract DSMath {\n    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x + y) >= x, \"\");\n    }\n\n    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x - y) <= x, \"\");\n    }\n\n    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require(y == 0 || (z = x * y) / y == x, \"\");\n    }\n\n    function div(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        return x / y;\n    }\n\n    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        return x <= y ? x : y;\n    }\n\n    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        return x >= y ? x : y;\n    }\n\n    function imin(int256 x, int256 y) internal pure returns (int256 z) {\n        return x <= y ? x : y;\n    }\n\n    function imax(int256 x, int256 y) internal pure returns (int256 z) {\n        return x >= y ? x : y;\n    }\n\n    uint256 internal constant WAD = 10**18;\n    uint256 internal constant RAY = 10**27;\n\n    function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        z = add(mul(x, y), WAD / 2) / WAD;\n    }\n\n    function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        z = add(mul(x, y), RAY / 2) / RAY;\n    }\n\n    function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        z = add(mul(x, WAD), y / 2) / y;\n    }\n\n    function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        z = add(mul(x, RAY), y / 2) / y;\n    }\n\n    // This famous algorithm is called \"exponentiation by squaring\"\n    // and calculates x^n with x as fixed-point and n as regular unsigned.\n    //\n    // It's O(log n), instead of O(n) for naive repeated multiplication.\n    //\n    // These facts are why it works:\n    //\n    //  If n is even, then x^n = (x^2)^(n/2).\n    //  If n is odd,  then x^n = x * x^(n-1),\n    //   and applying the equation for even x gives\n    //    x^n = x * (x^2)^((n-1) / 2).\n    //\n    //  Also, EVM division is flooring and\n    //    floor[(n-1) / 2] = floor[n / 2].\n    //\n    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {\n        z = n % 2 != 0 ? x : RAY;\n\n        for (n /= 2; n != 0; n /= 2) {\n            x = rmul(x, x);\n\n            if (n % 2 != 0) {\n                z = rmul(z, x);\n            }\n        }\n    }\n}\n"
    },
    "contracts/libs/RatioUtils.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// BasicBuyCommand.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\npragma solidity ^0.8.0;\n\nimport { SafeMath } from \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\n\nlibrary RatioUtils {\n    using SafeMath for uint256;\n\n    uint256 public constant RATIO = 10**4;\n    uint256 public constant WAD = 10**18;\n    uint256 public constant RAY = 10**27;\n    uint256 public constant RAD = 10**45;\n\n    // convert base units to ratio\n    function toRatio(uint256 units) internal pure returns (uint256) {\n        return units.mul(RATIO);\n    }\n\n    function wad(uint256 ratio) internal pure returns (uint256) {\n        return ratio.mul(WAD).div(RATIO);\n    }\n\n    function ray(uint256 ratio) internal pure returns (uint256) {\n        return ratio.mul(RAY).div(RATIO);\n    }\n\n    function bounds(uint256 ratio, uint64 deviation)\n        internal\n        pure\n        returns (uint256 lower, uint256 upper)\n    {\n        uint256 offset = ratio.mul(deviation).div(RATIO);\n        return (ratio.sub(offset), ratio.add(offset));\n    }\n\n    function rayToWad(uint256 _ray) internal pure returns (uint256 _wad) {\n        _wad = _ray.mul(WAD).div(RAY);\n    }\n\n    function wadToRay(uint256 _wad) internal pure returns (uint256 _ray) {\n        _ray = _wad.mul(RAY).div(WAD);\n    }\n\n    function radToWad(uint256 _rad) internal pure returns (uint256 _wad) {\n        _wad = _rad.mul(WAD).div(RAD);\n    }\n\n    function wadToRad(uint256 _wad) internal pure returns (uint256 _rad) {\n        _rad = _wad.mul(RAD).div(WAD);\n    }\n}\n"
    },
    "contracts/AutomationBot.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// AutomationBot.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\npragma solidity ^0.8.0;\n\nimport \"./interfaces/ManagerLike.sol\";\nimport \"./interfaces/ICommand.sol\";\nimport \"./interfaces/BotLike.sol\";\nimport \"./ServiceRegistry.sol\";\nimport \"./McdUtils.sol\";\n\ncontract AutomationBot {\n    struct TriggerRecord {\n        bytes32 triggerHash;\n        uint256 cdpId;\n    }\n\n    string private constant CDP_MANAGER_KEY = \"CDP_MANAGER\";\n    string private constant AUTOMATION_BOT_KEY = \"AUTOMATION_BOT\";\n    string private constant AUTOMATION_EXECUTOR_KEY = \"AUTOMATION_EXECUTOR\";\n    string private constant MCD_UTILS_KEY = \"MCD_UTILS\";\n\n    mapping(uint256 => TriggerRecord) public activeTriggers;\n\n    uint256 public triggersCounter = 0;\n\n    ServiceRegistry public immutable serviceRegistry;\n    address public immutable self;\n\n    constructor(ServiceRegistry _serviceRegistry) {\n        serviceRegistry = _serviceRegistry;\n        self = address(this);\n    }\n\n    modifier auth(address caller) {\n        require(\n            serviceRegistry.getRegisteredService(AUTOMATION_EXECUTOR_KEY) == caller,\n            \"bot/not-executor\"\n        );\n        _;\n    }\n\n    modifier onlyDelegate() {\n        require(address(this) != self, \"bot/only-delegate\");\n        _;\n    }\n\n    // works correctly in any context\n    function validatePermissions(\n        uint256 cdpId,\n        address operator,\n        ManagerLike manager\n    ) private view {\n        require(isCdpOwner(cdpId, operator, manager), \"bot/no-permissions\");\n    }\n\n    // works correctly in any context\n    function isCdpAllowed(\n        uint256 cdpId,\n        address operator,\n        ManagerLike manager\n    ) public view returns (bool) {\n        address cdpOwner = manager.owns(cdpId);\n        return (manager.cdpCan(cdpOwner, cdpId, operator) == 1) || (operator == cdpOwner);\n    }\n\n    // works correctly in any context\n    function isCdpOwner(\n        uint256 cdpId,\n        address operator,\n        ManagerLike manager\n    ) private view returns (bool) {\n        return (operator == manager.owns(cdpId));\n    }\n\n    // works correctly in any context\n    function getCommandAddress(uint256 triggerType) public view returns (address) {\n        bytes32 commandHash = keccak256(abi.encode(\"Command\", triggerType));\n\n        address commandAddress = serviceRegistry.getServiceAddress(commandHash);\n\n        return commandAddress;\n    }\n\n    // works correctly in any context\n    function getTriggersHash(\n        uint256 cdpId,\n        bytes memory triggerData,\n        address commandAddress\n    ) private view returns (bytes32) {\n        bytes32 triggersHash = keccak256(\n            abi.encodePacked(cdpId, triggerData, serviceRegistry, commandAddress)\n        );\n\n        return triggersHash;\n    }\n\n    // works correctly in context of Automation Bot\n    function checkTriggersExistenceAndCorrectness(\n        uint256 cdpId,\n        uint256 triggerId,\n        address commandAddress,\n        bytes memory triggerData\n    ) private view {\n        bytes32 triggersHash = activeTriggers[triggerId].triggerHash;\n\n        require(\n            triggersHash != bytes32(0) &&\n                triggersHash == getTriggersHash(cdpId, triggerData, commandAddress),\n            \"bot/invalid-trigger\"\n        );\n    }\n\n    function checkTriggersExistenceAndCorrectness(uint256 cdpId, uint256 triggerId) private view {\n        require(activeTriggers[triggerId].cdpId == cdpId, \"bot/invalid-trigger\");\n    }\n\n    // works correctly in context of automationBot\n    function addRecord(\n        // This function should be executed allways in a context of AutomationBot address not DsProxy,\n        // msg.sender should be dsProxy\n        uint256 cdpId,\n        uint256 triggerType,\n        uint256 replacedTriggerId,\n        bytes memory triggerData\n    ) external {\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n        address commandAddress = getCommandAddress(triggerType);\n\n        require(\n            ICommand(commandAddress).isTriggerDataValid(cdpId, triggerData),\n            \"bot/invalid-trigger-data\"\n        );\n\n        require(isCdpAllowed(cdpId, msg.sender, manager), \"bot/no-permissions\");\n\n        triggersCounter = triggersCounter + 1;\n        activeTriggers[triggersCounter] = TriggerRecord(\n            getTriggersHash(cdpId, triggerData, commandAddress),\n            cdpId\n        );\n\n        if (replacedTriggerId != 0) {\n            require(\n                activeTriggers[replacedTriggerId].cdpId == cdpId,\n                \"bot/trigger-removal-illegal\"\n            );\n            activeTriggers[replacedTriggerId] = TriggerRecord(0, 0);\n            emit TriggerRemoved(cdpId, replacedTriggerId);\n        }\n        emit TriggerAdded(triggersCounter, commandAddress, cdpId, triggerData);\n    }\n\n    // works correctly in context of automationBot\n    function removeRecord(\n        // This function should be executed allways in a context of AutomationBot address not DsProxy,\n        // msg.sender should be dsProxy\n        uint256 cdpId,\n        uint256 triggerId\n    ) external {\n        address managerAddress = serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);\n\n        require(isCdpAllowed(cdpId, msg.sender, ManagerLike(managerAddress)), \"bot/no-permissions\");\n        // validatePermissions(cdpId, msg.sender, ManagerLike(managerAddress));\n\n        checkTriggersExistenceAndCorrectness(cdpId, triggerId);\n\n        activeTriggers[triggerId] = TriggerRecord(0, 0);\n        emit TriggerRemoved(cdpId, triggerId);\n    }\n\n    //works correctly in context of dsProxy\n    function addTrigger(\n        uint256 cdpId,\n        uint256 triggerType,\n        uint256 replacedTriggerId,\n        bytes memory triggerData\n    ) external onlyDelegate {\n        // TODO: consider adding isCdpAllow add flag in tx payload, make sense from extensibility perspective\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n\n        address automationBot = serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);\n        BotLike(automationBot).addRecord(cdpId, triggerType, replacedTriggerId, triggerData);\n        if (!isCdpAllowed(cdpId, automationBot, manager)) {\n            manager.cdpAllow(cdpId, automationBot, 1);\n            emit ApprovalGranted(cdpId, automationBot);\n        }\n    }\n\n    //works correctly in context of dsProxy\n\n    // TODO: removeAllowance parameter of this method moves responsibility to decide on this to frontend.\n    // In case of a bug on frontend allowance might be revoked by setting this parameter to `true`\n    // despite there still be some active triggers which will be disables by this call.\n    // One of the solutions is to add counter of active triggers and revoke allowance only if last trigger is being deleted\n    function removeTrigger(\n        uint256 cdpId,\n        uint256 triggerId,\n        bool removeAllowance\n    ) external onlyDelegate {\n        address managerAddress = serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);\n        ManagerLike manager = ManagerLike(managerAddress);\n\n        address automationBot = serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);\n\n        BotLike(automationBot).removeRecord(cdpId, triggerId);\n\n        if (removeAllowance) {\n            manager.cdpAllow(cdpId, automationBot, 0);\n            emit ApprovalRemoved(cdpId, automationBot);\n        }\n\n        emit TriggerRemoved(cdpId, triggerId);\n    }\n\n    //works correctly in context of dsProxy\n    function removeApproval(ServiceRegistry _serviceRegistry, uint256 cdpId) external onlyDelegate {\n        address approvedEntity = changeApprovalStatus(_serviceRegistry, cdpId, 0);\n        emit ApprovalRemoved(cdpId, approvedEntity);\n    }\n\n    //works correctly in context of dsProxy\n    function grantApproval(ServiceRegistry _serviceRegistry, uint256 cdpId) external onlyDelegate {\n        address approvedEntity = changeApprovalStatus(_serviceRegistry, cdpId, 1);\n        emit ApprovalGranted(cdpId, approvedEntity);\n    }\n\n    //works correctly in context of dsProxy\n    function changeApprovalStatus(\n        ServiceRegistry _serviceRegistry,\n        uint256 cdpId,\n        uint256 status\n    ) private returns (address) {\n        address managerAddress = _serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);\n        ManagerLike manager = ManagerLike(managerAddress);\n        address automationBot = _serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);\n        require(\n            isCdpAllowed(cdpId, automationBot, manager) != (status == 1),\n            \"bot/approval-unchanged\"\n        );\n        validatePermissions(cdpId, address(this), manager);\n        manager.cdpAllow(cdpId, automationBot, status);\n        return automationBot;\n    }\n\n    function drawDaiFromVault(\n        uint256 cdpId,\n        ManagerLike manager,\n        uint256 daiCoverage\n    ) internal {\n        address utilsAddress = serviceRegistry.getRegisteredService(MCD_UTILS_KEY);\n\n        McdUtils utils = McdUtils(utilsAddress);\n        manager.cdpAllow(cdpId, utilsAddress, 1);\n        utils.drawDebt(daiCoverage, cdpId, manager, msg.sender);\n        manager.cdpAllow(cdpId, utilsAddress, 0);\n    }\n\n    //works correctly in context of automationBot\n    function execute(\n        bytes calldata executionData,\n        uint256 cdpId,\n        bytes calldata triggerData,\n        address commandAddress,\n        uint256 triggerId,\n        uint256 daiCoverage\n    ) external auth(msg.sender) {\n        checkTriggersExistenceAndCorrectness(cdpId, triggerId, commandAddress, triggerData);\n        ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));\n        drawDaiFromVault(cdpId, manager, daiCoverage);\n\n        ICommand command = ICommand(commandAddress);\n        require(command.isExecutionLegal(cdpId, triggerData), \"bot/trigger-execution-illegal\");\n\n        manager.cdpAllow(cdpId, commandAddress, 1);\n        command.execute(executionData, cdpId, triggerData);\n        activeTriggers[triggerId] = TriggerRecord(0, 0);\n        manager.cdpAllow(cdpId, commandAddress, 0);\n\n        require(command.isExecutionCorrect(cdpId, triggerData), \"bot/trigger-execution-wrong\");\n\n        emit TriggerExecuted(triggerId, cdpId, executionData);\n    }\n\n    event ApprovalRemoved(uint256 indexed cdpId, address approvedEntity);\n\n    event ApprovalGranted(uint256 indexed cdpId, address approvedEntity);\n\n    event TriggerRemoved(uint256 indexed cdpId, uint256 indexed triggerId);\n\n    event TriggerAdded(\n        uint256 indexed triggerId,\n        address indexed commandAddress,\n        uint256 indexed cdpId,\n        bytes triggerData\n    );\n\n    event TriggerExecuted(uint256 indexed triggerId, uint256 indexed cdpId, bytes executionData);\n}\n"
    },
    "@openzeppelin/contracts/utils/math/SafeMath.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a + b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a * b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator.\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b <= a, errorMessage);\n            return a - b;\n        }\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a / b;\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a % b;\n        }\n    }\n}\n"
    },
    "contracts/McdUtils.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-or-later\n\n/// McdUtils.sol\n\n// Copyright (C) 2021-2021 Oazo Apps Limited\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\npragma solidity ^0.8.0;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./external/DSMath.sol\";\nimport \"./interfaces/ManagerLike.sol\";\nimport \"./interfaces/ICommand.sol\";\nimport \"./interfaces/Mcd.sol\";\nimport \"./interfaces/BotLike.sol\";\n\nimport \"./ServiceRegistry.sol\";\n\n/// @title Getter contract for Vault info from Maker protocol\ncontract McdUtils is DSMath {\n    address public immutable serviceRegistry;\n    IERC20 private immutable DAI;\n    address private immutable daiJoin;\n    address public immutable jug;\n\n    constructor(\n        address _serviceRegistry,\n        IERC20 _dai,\n        address _daiJoin,\n        address _jug\n    ) {\n        serviceRegistry = _serviceRegistry;\n        DAI = _dai;\n        daiJoin = _daiJoin;\n        jug = _jug;\n    }\n\n    function toInt256(uint256 x) internal pure returns (int256 y) {\n        y = int256(x);\n        require(y >= 0, \"int256-overflow\");\n    }\n\n    function _getDrawDart(\n        address vat,\n        address urn,\n        bytes32 ilk,\n        uint256 wad\n    ) internal returns (int256 dart) {\n        // Updates stability fee rate\n        uint256 rate = IJug(jug).drip(ilk);\n\n        // Gets DAI balance of the urn in the vat\n        uint256 dai = IVat(vat).dai(urn);\n\n        // If there was already enough DAI in the vat balance, just exits it without adding more debt\n        if (dai < mul(wad, RAY)) {\n            // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens\n            dart = toInt256(sub(mul(wad, RAY), dai) / rate);\n            // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)\n            dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;\n        }\n    }\n\n    function drawDebt(\n        uint256 borrowedDai,\n        uint256 cdpId,\n        ManagerLike manager,\n        address sendTo\n    ) external {\n        address urn = manager.urns(cdpId);\n        address vat = manager.vat();\n\n        manager.frob(cdpId, 0, _getDrawDart(vat, urn, manager.ilks(cdpId), borrowedDai));\n        manager.move(cdpId, address(this), mul(borrowedDai, RAY));\n\n        if (IVat(vat).can(address(this), daiJoin) == 0) {\n            IVat(vat).hope(daiJoin);\n        }\n\n        IJoin(daiJoin).exit(sendTo, borrowedDai);\n    }\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
    },
    "contracts/interfaces/Mcd.sol": {
      "content": "//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\nabstract contract IVat {\n    struct Urn {\n        uint256 ink; // Locked Collateral  [wad]\n        uint256 art; // Normalised Debt    [wad]\n    }\n\n    struct Ilk {\n        uint256 Art; // Total Normalised Debt     [wad]\n        uint256 rate; // Accumulated Rates         [ray]\n        uint256 spot; // Price with Safety Margin  [ray]\n        uint256 line; // Debt Ceiling              [rad]\n        uint256 dust; // Urn Debt Floor            [rad]\n    }\n\n    mapping(bytes32 => mapping(address => Urn)) public urns;\n    mapping(bytes32 => Ilk) public ilks;\n    mapping(bytes32 => mapping(address => uint256)) public gem; // [wad]\n\n    function can(address, address) public view virtual returns (uint256);\n\n    function dai(address) public view virtual returns (uint256);\n\n    function frob(\n        bytes32,\n        address,\n        address,\n        address,\n        int256,\n        int256\n    ) public virtual;\n\n    function hope(address) public virtual;\n\n    function move(\n        address,\n        address,\n        uint256\n    ) public virtual;\n\n    function fork(\n        bytes32,\n        address,\n        address,\n        int256,\n        int256\n    ) public virtual;\n}\n\nabstract contract IGem {\n    function dec() public virtual returns (uint256);\n\n    function gem() public virtual returns (IGem);\n\n    function join(address, uint256) public payable virtual;\n\n    function exit(address, uint256) public virtual;\n\n    function approve(address, uint256) public virtual;\n\n    function transfer(address, uint256) public virtual returns (bool);\n\n    function transferFrom(\n        address,\n        address,\n        uint256\n    ) public virtual returns (bool);\n\n    function deposit() public payable virtual;\n\n    function withdraw(uint256) public virtual;\n\n    function allowance(address, address) public virtual returns (uint256);\n}\n\nabstract contract IJoin {\n    bytes32 public ilk;\n\n    function dec() public view virtual returns (uint256);\n\n    function gem() public view virtual returns (IGem);\n\n    function join(address, uint256) public payable virtual;\n\n    function exit(address, uint256) public virtual;\n}\n\nabstract contract IDaiJoin {\n    function vat() public virtual returns (IVat);\n\n    function dai() public virtual returns (IGem);\n\n    function join(address, uint256) public payable virtual;\n\n    function exit(address, uint256) public virtual;\n}\n\nabstract contract IJug {\n    struct Ilk {\n        uint256 duty;\n        uint256 rho;\n    }\n\n    mapping(bytes32 => Ilk) public ilks;\n\n    function drip(bytes32) public virtual returns (uint256);\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 1000
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "libraries": {}
  }
}