{"file_path":"contracts/gateway/FrontendGateway.sol","creation_status":"success","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Equity} from \"../Equity.sol\";\nimport {IDecentralizedEURO} from \"../interface/IDecentralizedEURO.sol\";\nimport {DEPSWrapper} from \"../utils/DEPSWrapper.sol\";\nimport {SavingsGateway} from \"./SavingsGateway.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Context} from \"@openzeppelin/contracts/utils/Context.sol\";\nimport {IFrontendGateway} from \"./interface/IFrontendGateway.sol\";\nimport {IMintingHubGateway} from \"./interface/IMintingHubGateway.sol\";\n\ncontract FrontendGateway is IFrontendGateway, Context, Ownable {\n    IERC20 public immutable DEURO;\n    Equity public immutable EQUITY;\n    DEPSWrapper public immutable DEPS;\n\n    // solhint-disable-next-line var-name-mixedcase\n    IMintingHubGateway public MINTING_HUB;\n\n    // solhint-disable-next-line var-name-mixedcase\n    SavingsGateway public SAVINGS;\n\n    uint24 public feeRate; // Fee rate in PPM (parts per million), for example 10'000 = 1%\n    uint24 public savingsFeeRate; // Fee rate of savings in PPM (parts per million), for example 10 = 1%\n    uint24 public mintingFeeRate; // Reward rate of newly minted positions in PPM (parts per million), for example 10 = 1%\n    uint24 public nextFeeRate;\n    uint24 public nextSavingsFeeRate;\n    uint24 public nextMintingFeeRate;\n    uint256 public changeTimeLock;\n\n    mapping(bytes32 => FrontendCode) public frontendCodes;\n    mapping(address => bytes32) public referredPositions;\n    mapping(address => bytes32) public lastUsedFrontendCode;\n\n    modifier frontendCodeOwnerOnly(bytes32 frontendCode) {\n        if (frontendCodes[frontendCode].owner != _msgSender()) revert NotFrontendCodeOwner();\n        _;\n    }\n\n    modifier onlyGatewayService(address service) {\n        if (_msgSender() != address(service)) revert NotGatewayService();\n        _;\n    }\n\n    constructor(address deuro_, address deps_) Ownable(_msgSender()) {\n        DEURO = IERC20(deuro_);\n        EQUITY = Equity(address(IDecentralizedEURO(deuro_).reserve()));\n        DEPS = DEPSWrapper(deps_);\n        feeRate = 10_000; // 10_000/1_000_000 = 1% fee\n        savingsFeeRate = 50_000; // 50_000/1_000_000 = 5% fee of the of the savings interest\n        mintingFeeRate = 50_000; // 50_000/1_000_000 = 5% fee of the of the interest paid by the position owner\n    }\n\n    /**\n     * @notice Call this a wrapper method to obtain newly minted pool shares in exchange for\n     * DecentralizedEUROs and reward frontend providers with a small commission.\n     * No allowance required (i.e., it is hard-coded in the DecentralizedEURO token contract).\n     * Make sure to invest at least 10e-12 * market cap to avoid rounding losses.\n     *\n     * @dev If equity is close to zero or negative, you need to send enough dEURO to bring equity back to 1_000 dEURO.\n     *\n     * @param amount            DecentralizedEUROs to invest\n     * @param expectedShares    Minimum amount of expected shares for front running protection\n     * @param frontendCode      Code of the used frontend or referrer\n     */\n    function invest(uint256 amount, uint256 expectedShares, bytes32 frontendCode) external returns (uint256) {\n        uint256 actualShares = EQUITY.investFor(_msgSender(), amount, expectedShares);\n\n        uint256 reward = updateFrontendAccount(frontendCode, amount);\n        emit InvestRewardAdded(frontendCode, _msgSender(), amount, reward);\n        return actualShares;\n    }\n\n    function redeem(\n        address target,\n        uint256 shares,\n        uint256 expectedProceeds,\n        bytes32 frontendCode\n    ) external returns (uint256) {\n        uint256 actualProceeds = EQUITY.redeemFrom(_msgSender(), target, shares, expectedProceeds);\n\n        uint256 reward = updateFrontendAccount(frontendCode, actualProceeds);\n        emit RedeemRewardAdded(frontendCode, _msgSender(), actualProceeds, reward);\n        return actualProceeds;\n    }\n\n    function unwrapAndSell(uint256 amount, bytes32 frontendCode) external returns (uint256) {\n        DEPS.transferFrom(_msgSender(), address(this), amount);\n        uint256 actualProceeds = DEPS.unwrapAndSell(amount);\n        DEURO.transfer(_msgSender(), actualProceeds);\n\n        uint256 reward = updateFrontendAccount(frontendCode, actualProceeds);\n        emit UnwrapAndSellRewardAdded(frontendCode, _msgSender(), actualProceeds, reward);\n        return actualProceeds;\n    }\n\n    ///////////////////\n    // Accounting Logic\n    ///////////////////\n\n    function updateFrontendAccount(bytes32 frontendCode, uint256 amount) internal returns (uint256) {\n        if (frontendCode == bytes32(0)) return 0;\n        lastUsedFrontendCode[_msgSender()] = frontendCode;\n        uint256 reward = (amount * feeRate) / 1_000_000;\n        frontendCodes[frontendCode].balance += reward;\n        return reward;\n    }\n\n    function updateSavingCode(\n        address savingsOwner,\n        bytes32 frontendCode\n    ) external onlyGatewayService(address(SAVINGS)) {\n        if (frontendCode == bytes32(0)) return;\n        lastUsedFrontendCode[savingsOwner] = frontendCode;\n    }\n\n    function updateSavingRewards(address saver, uint256 interest) external onlyGatewayService(address(SAVINGS)) {\n        bytes32 frontendCode = lastUsedFrontendCode[saver];\n        if (frontendCode == bytes32(0)) return;\n\n        uint256 reward = (interest * savingsFeeRate) / 1_000_000;\n        frontendCodes[frontendCode].balance += reward;\n\n        emit SavingsRewardAdded(frontendCode, saver, interest, reward);\n    }\n\n    function registerPosition(\n        address position,\n        bytes32 frontendCode\n    ) external onlyGatewayService(address(MINTING_HUB)) {\n        if (frontendCode == bytes32(0)) return;\n\n        referredPositions[position] = frontendCode;\n        emit NewPositionRegistered(position, frontendCode);\n    }\n\n    function updatePositionRewards(address position, uint256 amount) external onlyGatewayService(address(MINTING_HUB)) {\n        bytes32 frontendCode = referredPositions[position];\n        if (frontendCode == bytes32(0)) return;\n        \n        uint256 reward = (amount * mintingFeeRate) / 1_000_000;\n        frontendCodes[frontendCode].balance += reward;\n\n        emit PositionRewardAdded(frontendCode, position, amount, reward);\n    }\n\n    function getPositionFrontendCode(address position) external view returns (bytes32) {\n        return referredPositions[position];\n    }\n\n    //////////////////////\n    // Frontend Code Logic\n    //////////////////////\n\n    function registerFrontendCode(bytes32 frontendCode) external returns (bool) {\n        if (frontendCodes[frontendCode].owner != address(0) || frontendCode == bytes32(0))\n            revert FrontendCodeAlreadyExists();\n        frontendCodes[frontendCode].owner = _msgSender();\n        emit FrontendCodeRegistered(_msgSender(), frontendCode);\n        return true;\n    }\n\n    function transferFrontendCode(\n        bytes32 frontendCode,\n        address to\n    ) external frontendCodeOwnerOnly(frontendCode) returns (bool) {\n        frontendCodes[frontendCode].owner = to;\n        emit FrontendCodeTransferred(_msgSender(), to, frontendCode);\n        return true;\n    }\n\n    function withdrawRewards(bytes32 frontendCode) external frontendCodeOwnerOnly(frontendCode) returns (uint256) {\n        return _withdrawRewardsTo(frontendCode, _msgSender());\n    }\n\n    function withdrawRewardsTo(\n        bytes32 frontendCode,\n        address to\n    ) external frontendCodeOwnerOnly(frontendCode) returns (uint256) {\n        return _withdrawRewardsTo(frontendCode, to);\n    }\n\n    function _withdrawRewardsTo(bytes32 frontendCode, address to) internal returns (uint256) {\n        uint256 amount = frontendCodes[frontendCode].balance;\n\n        if (IDecentralizedEURO(address(DEURO)).equity() < amount) revert EquityTooLow();\n\n        frontendCodes[frontendCode].balance = 0;\n        IDecentralizedEURO(address(DEURO)).distributeProfits(to, amount);\n        emit FrontendCodeRewardsWithdrawn(to, amount, frontendCode);\n        return amount;\n    }\n\n    /**\n     * @notice Proposes new referral rates that will available to be executed after seven days.\n     * To cancel a proposal, just overwrite it with a new one proposing the current rate.\n     */\n    function proposeChanges(\n        uint24 newFeeRatePPM_,\n        uint24 newSavingsFeeRatePPM_,\n        uint24 newMintingFeeRatePPM_,\n        address[] calldata helpers\n    ) external {\n        if (newFeeRatePPM_ > 20_000 || newSavingsFeeRatePPM_ > 1_000_000 || newMintingFeeRatePPM_ > 1_000_000)\n            revert ProposedChangesToHigh();\n        EQUITY.checkQualified(_msgSender(), helpers);\n        nextFeeRate = newFeeRatePPM_;\n        nextSavingsFeeRate = newSavingsFeeRatePPM_;\n        nextMintingFeeRate = newMintingFeeRatePPM_;\n        changeTimeLock = block.timestamp + 7 days;\n        emit RateChangesProposed(\n            _msgSender(),\n            newFeeRatePPM_,\n            newSavingsFeeRatePPM_,\n            newMintingFeeRatePPM_,\n            changeTimeLock\n        );\n    }\n\n    function executeChanges() external {\n        if (nextFeeRate == feeRate && nextSavingsFeeRate == savingsFeeRate && nextMintingFeeRate == mintingFeeRate)\n            revert NoOpenChanges();\n        if (block.timestamp < changeTimeLock) revert NotDoneWaiting(changeTimeLock);\n        feeRate = nextFeeRate;\n        savingsFeeRate = nextSavingsFeeRate;\n        mintingFeeRate = nextMintingFeeRate;\n        emit RateChangesExecuted(_msgSender(), feeRate, savingsFeeRate, mintingFeeRate);\n    }\n\n    function init(address savings, address mintingHub) external onlyOwner {\n        SAVINGS = SavingsGateway(savings);\n        MINTING_HUB = IMintingHubGateway(mintingHub);\n        renounceOwnership();\n    }\n}\n","deployed_bytecode":"0x608060405234801561001057600080fd5b50600436106101fb5760003560e01c80638da5cb5b1161011a578063d8f21747116100ad578063e28a0b961161007c578063e28a0b96146104f8578063f09a401614610507578063f2fde38b1461051a578063f83279501461052d578063fe9f9d2c1461054057600080fd5b8063d8f2174714610475578063dbe8a4c21461049e578063dc3012ef146104c5578063e0c01f79146104d857600080fd5b8063a34ca630116100e9578063a34ca6301461041d578063c275a20014610444578063c2db9d3214610457578063d8db60c91461045f57600080fd5b80638da5cb5b146103d0578063978bbdb9146103e15780639bfe870b146103f7578063a07377761461040a57600080fd5b8063423bf67411610192578063736a3f0511610161578063736a3f05146103715780637b025bdf146103945780637dfb6626146103aa5780638467004f146103bd57600080fd5b8063423bf6741461032357806357eac85f146103365780635ebdc04314610356578063715018a61461036957600080fd5b806331266ff5116101ce57806331266ff5146102965780633603f35d146102a9578063368da021146102f65780633f6068fb1461030c57600080fd5b806301137702146102005780631aa7a5591461022f5780631acad25d1461025a5780632a5e323114610281575b600080fd5b60025461021690600160e81b900462ffffff1681565b60405162ffffff90911681526020015b60405180910390f35b600254610242906001600160a01b031681565b6040516001600160a01b039091168152602001610226565b6102427f000000000000000000000000103747924e74708139a9400e4ab4bea79fffa38081565b61029461028f36600461145d565b610553565b005b6102946102a436600461145d565b61063c565b6102d96102b7366004611487565b600560205260009081526040902080546001909101546001600160a01b031682565b604080519283526001600160a01b03909116602083015201610226565b60025461021690600160b81b900462ffffff1681565b61031560045481565b604051908152602001610226565b61029461033136600461145d565b610715565b6103156103443660046114a0565b60076020526000908152604090205481565b6103156103643660046114bb565b610765565b6102946107b3565b61038461037f366004611487565b6107c7565b6040519015158152602001610226565b60025461021690600160d01b900462ffffff1681565b6103156103b8366004611487565b610873565b6103156103cb3660046114e7565b6108c0565b6000546001600160a01b0316610242565b60025461021690600160a01b900462ffffff1681565b610315610405366004611513565b6109c1565b61029461041836600461145d565b610bf2565b6102427f000000000000000000000000c71104001a3ccda1bef1177d765831bd1bfe8ee681565b610294610452366004611548565b610c7d565b610294610e02565b600354610216906301000000900462ffffff1681565b6103156104833660046114a0565b6001600160a01b031660009081526006602052604090205490565b6102427f000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea81565b6103156104d33660046115ef565b610f61565b6103156104e63660046114a0565b60066020526000908152604090205481565b6003546102169062ffffff1681565b610294610515366004611628565b61106b565b6102946105283660046114a0565b6110af565b600154610242906001600160a01b031681565b61038461054e3660046114bb565b6110ed565b6001546001600160a01b031633811461057f576040516338b601a360e11b815260040160405180910390fd5b6001600160a01b038316600090815260066020526040902054806105a35750505050565b600254600090620f4240906105c490600160d01b900462ffffff1686611668565b6105ce919061167f565b6000838152600560205260408120805492935083929091906105f19084906116a1565b90915550506040517ff67326db9c82bb81a05afd0d0db07bc3f75f7613c9dca5eedeff02d8cdcc74fb9061062c9084908890889086906116b4565b60405180910390a150505b505050565b6002546001600160a01b0316338114610668576040516338b601a360e11b815260040160405180910390fd5b6001600160a01b0383166000908152600760205260409020548061068c5750505050565b600254600090620f4240906106ad90600160b81b900462ffffff1686611668565b6106b7919061167f565b6000838152600560205260408120805492935083929091906106da9084906116a1565b90915550506040517fc4049913e96e245623a2d45ab552836b79e99d66befb96d82ff96b9b7f7eeb0e9061062c9084908890889086906116b4565b6002546001600160a01b0316338114610741576040516338b601a360e11b815260040160405180910390fd5b811561063757506001600160a01b0391909116600090815260076020526040902055565b60008281526005602052604081206001015483906001600160a01b031633146107a15760405163729260b160e11b815260040160405180910390fd5b6107ab84846111a8565b949350505050565b6107bb61134b565b6107c56000611378565b565b6000818152600560205260408120600101546001600160a01b03161515806107ed575081155b1561080b576040516378d0770560e01b815260040160405180910390fd5b60008281526005602090815260409182902060010180546001600160a01b03191633908117909155825190815290810184905281517fac113b25e2f6da9f42c0fcfcb2a028fd74e615dca6ef2a71abffad4577797072929181900390910190a1506001919050565b60008181526005602052604081206001015482906001600160a01b031633146108af5760405163729260b160e11b815260040160405180910390fd5b6108b983336111a8565b9392505050565b6000806001600160a01b037f000000000000000000000000c71104001a3ccda1bef1177d765831bd1bfe8ee61663a1c1fb4f336040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260248101889052604481018790526064016020604051808303816000875af1158015610947573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096b91906116d8565b9050600061097984876113c8565b90507f77ad8b04cbab9dca6c50359ef623aa13f7d709398d384e0884b234aec5681385843388846040516109b094939291906116b4565b60405180910390a150949350505050565b60006001600160a01b037f000000000000000000000000103747924e74708139a9400e4ab4bea79fffa380166323b872dd336040516001600160e01b031960e084901b1681526001600160a01b039091166004820152306024820152604481018690526064016020604051808303816000875af1158015610a46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6a91906116f1565b506040516387481e7360e01b8152600481018490526000907f000000000000000000000000103747924e74708139a9400e4ab4bea79fffa3806001600160a01b0316906387481e73906024016020604051808303816000875af1158015610ad5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af991906116d8565b90506001600160a01b037f000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea1663a9059cbb336040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303816000875af1158015610b78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9c91906116f1565b506000610ba984836113c8565b90507f3ce823bb669d9fe2c8dff0dc88f8ce4297ea49600b3eafc60954c87bff594f5584338484604051610be094939291906116b4565b60405180910390a15090505b92915050565b6001546001600160a01b0316338114610c1e576040516338b601a360e11b815260040160405180910390fd5b8115610637576001600160a01b038316600081815260066020908152604091829020859055815192835282018490527f9e429360cfeef15ad3c2ba1c39a2c8788c2774663312112e0af1b084a5d56010910160405180910390a1505050565b614e208562ffffff161180610c995750620f42408462ffffff16115b80610cab5750620f42408362ffffff16115b15610cc95760405163c2c7709b60e01b815260040160405180910390fd5b60405163352e3a8360e01b81527f000000000000000000000000c71104001a3ccda1bef1177d765831bd1bfe8ee66001600160a01b03169063352e3a8390610d1990339086908690600401611713565b60006040518083038186803b158015610d3157600080fd5b505afa158015610d45573d6000803e3d6000fd5b50506002805462ffffff808a16600160e81b026001600160e81b03909216919091179091556003805487831663010000000265ffffffffffff199091169289169290921791909117905550610d9f90504262093a806116a1565b6004557f7675f8a1fec4ff7e3c4b4a7771beca147e122e702f5e632a812a983d74136e0133600454604080516001600160a01b03909316835262ffffff808a1660208501528089169184019190915286166060830152608082015260a00161062c565b600254600160e81b810462ffffff908116600160a01b90920416148015610e3c575060025460035462ffffff908116600160b81b90920416145b8015610e6257506002546003546301000000900462ffffff908116600160d01b90920416145b15610e80576040516304fe479160e01b815260040160405180910390fd5b600454421015610eac57600480546040516374f75f6360e01b8152918201526024015b60405180910390fd5b60028054600354600160d01b6301000000820462ffffff908116820262ffffff60d01b19600160b81b948316850262ffffff60b81b19600160a01b600160e81b8904861681029190911665ffffffffffff60a01b19909816979097171716179485905560408051338152948604821660208601529285048116848401529304909216606082015290517fad985451be636dfc329b4c01326f5378dd03b425d9ddc03d21a38d7ebc8f6e599181900360800190a1565b6000806001600160a01b037f000000000000000000000000c71104001a3ccda1bef1177d765831bd1bfe8ee6166391ac6f99336040516001600160e01b031960e084901b1681526001600160a01b039182166004820152908916602482015260448101889052606481018790526084016020604051808303816000875af1158015610ff0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101491906116d8565b9050600061102284836113c8565b90507fb2eade9032a35a2c8bf13d1232bffcfe60383b7541d8f3fddaa9eb53a832e1678433848460405161105994939291906116b4565b60405180910390a15095945050505050565b61107361134b565b600280546001600160a01b038085166001600160a01b03199283161790925560018054928416929091169190911790556110ab6107b3565b5050565b6110b761134b565b6001600160a01b0381166110e157604051631e4fbdf760e01b815260006004820152602401610ea3565b6110ea81611378565b50565b60008281526005602052604081206001015483906001600160a01b031633146111295760405163729260b160e11b815260040160405180910390fd5b600084815260056020526040902060010180546001600160a01b0319166001600160a01b0385161790557f4f1b00fb86992889ee465121c65a60c82612738f92c5de138d81ed4576e2544733604080516001600160a01b0392831681529186166020830152810186905260600160405180910390a15060019392505050565b60008060056000858152602001908152602001600020600001549050807f000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea6001600160a01b03166391a0ac6a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611223573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124791906116d8565b101561126657604051639efc0a6960e01b815260040160405180910390fd5b60008481526005602052604080822091909155516308b8bb4b60e01b81526001600160a01b038481166004830152602482018390527f000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea16906308b8bb4b90604401600060405180830381600087803b1580156112e157600080fd5b505af11580156112f5573d6000803e3d6000fd5b5050604080516001600160a01b0387168152602081018590529081018790527f7728e907e9a9ce01e7031dcc773e276dab993b745d3295702af40a91d67683f89250606001905060405180910390a19392505050565b6000546001600160a01b031633146107c55760405163118cdaa760e01b8152336004820152602401610ea3565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000826113d757506000610bec565b336000908152600760205260408120849055600254620f42409061140790600160a01b900462ffffff1685611668565b611411919061167f565b6000858152600560205260408120805492935083929091906114349084906116a1565b9091555090949350505050565b80356001600160a01b038116811461145857600080fd5b919050565b6000806040838503121561147057600080fd5b61147983611441565b946020939093013593505050565b60006020828403121561149957600080fd5b5035919050565b6000602082840312156114b257600080fd5b6108b982611441565b600080604083850312156114ce57600080fd5b823591506114de60208401611441565b90509250929050565b6000806000606084860312156114fc57600080fd5b505081359360208301359350604090920135919050565b6000806040838503121561152657600080fd5b50508035926020909101359150565b803562ffffff8116811461145857600080fd5b60008060008060006080868803121561156057600080fd5b61156986611535565b945061157760208701611535565b935061158560408701611535565b9250606086013567ffffffffffffffff8111156115a157600080fd5b8601601f810188136115b257600080fd5b803567ffffffffffffffff8111156115c957600080fd5b8860208260051b84010111156115de57600080fd5b959894975092955050506020019190565b6000806000806080858703121561160557600080fd5b61160e85611441565b966020860135965060408601359560600135945092505050565b6000806040838503121561163b57600080fd5b61164483611441565b91506114de60208401611441565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610bec57610bec611652565b60008261169c57634e487b7160e01b600052601260045260246000fd5b500490565b80820180821115610bec57610bec611652565b9384526001600160a01b039290921660208401526040830152606082015260800190565b6000602082840312156116ea57600080fd5b5051919050565b60006020828403121561170357600080fd5b815180151581146108b957600080fd5b6001600160a01b0384168152604060208201819052810182905260008360608301825b85811015611764576001600160a01b0361174f84611441565b16825260209283019290910190600101611736565b50969550505050505056fea2646970667358221220ed28aa5c8a1320a6f611dc76294edb6710c34bd6fcc1fd2bb5907db72564f83e64736f6c634300081a0033","optimization_enabled":true,"verified_twin_address_hash":null,"is_verified":true,"compiler_settings":{"evmVersion":"paris","libraries":{},"metadata":{"bytecodeHash":"ipfs","useLiteralContent":true},"optimizer":{"enabled":true,"runs":200},"remappings":[]},"optimization_runs":200,"sourcify_repo_url":"https://repo.sourcify.dev/contracts/full_match/1/0x5c49C00f897bD970d964BFB8c3065ae65a180994/","decoded_constructor_args":[["0xbA3f535bbCcCcA2A154b573Ca6c5A49BAAE0a3ea",{"internalType":"address","name":"deuro_","type":"address"}],["0x103747924E74708139a9400e4Ab4BEA79FFFA380",{"internalType":"address","name":"deps_","type":"address"}]],"compiler_version":"0.8.26+commit.8a97fa7a","is_verified_via_verifier_alliance":false,"verified_at":"2026-03-22T15:22:33.195360Z","implementations":[],"proxy_type":null,"external_libraries":[],"creation_bytecode":"0x60e060405234801561001057600080fd5b506040516119d73803806119d783398101604081905261002f9161016d565b338061005557604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b61005e81610105565b506001600160a01b03821660808190526040805163669949ef60e11b8152905163cd3293de916004808201926020929091908290030181865afa1580156100a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100cd91906101a7565b6001600160a01b0390811660a0521660c0525060028054600160a01b600160e81b031916670c35000c3500027160a41b1790556101cb565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b038116811461016a57600080fd5b50565b6000806040838503121561018057600080fd5b825161018b81610155565b602084015190925061019c81610155565b809150509250929050565b6000602082840312156101b957600080fd5b81516101c481610155565b9392505050565b60805160a05160c0516117a56102326000396000818161025f015281816109cd0152610a84015260008181610422015281816108cd01528181610cd80152610f6e0152600081816104a301528181610b05015281816111c7015261129d01526117a56000f3fe608060405234801561001057600080fd5b50600436106101fb5760003560e01c80638da5cb5b1161011a578063d8f21747116100ad578063e28a0b961161007c578063e28a0b96146104f8578063f09a401614610507578063f2fde38b1461051a578063f83279501461052d578063fe9f9d2c1461054057600080fd5b8063d8f2174714610475578063dbe8a4c21461049e578063dc3012ef146104c5578063e0c01f79146104d857600080fd5b8063a34ca630116100e9578063a34ca6301461041d578063c275a20014610444578063c2db9d3214610457578063d8db60c91461045f57600080fd5b80638da5cb5b146103d0578063978bbdb9146103e15780639bfe870b146103f7578063a07377761461040a57600080fd5b8063423bf67411610192578063736a3f0511610161578063736a3f05146103715780637b025bdf146103945780637dfb6626146103aa5780638467004f146103bd57600080fd5b8063423bf6741461032357806357eac85f146103365780635ebdc04314610356578063715018a61461036957600080fd5b806331266ff5116101ce57806331266ff5146102965780633603f35d146102a9578063368da021146102f65780633f6068fb1461030c57600080fd5b806301137702146102005780631aa7a5591461022f5780631acad25d1461025a5780632a5e323114610281575b600080fd5b60025461021690600160e81b900462ffffff1681565b60405162ffffff90911681526020015b60405180910390f35b600254610242906001600160a01b031681565b6040516001600160a01b039091168152602001610226565b6102427f000000000000000000000000000000000000000000000000000000000000000081565b61029461028f36600461145d565b610553565b005b6102946102a436600461145d565b61063c565b6102d96102b7366004611487565b600560205260009081526040902080546001909101546001600160a01b031682565b604080519283526001600160a01b03909116602083015201610226565b60025461021690600160b81b900462ffffff1681565b61031560045481565b604051908152602001610226565b61029461033136600461145d565b610715565b6103156103443660046114a0565b60076020526000908152604090205481565b6103156103643660046114bb565b610765565b6102946107b3565b61038461037f366004611487565b6107c7565b6040519015158152602001610226565b60025461021690600160d01b900462ffffff1681565b6103156103b8366004611487565b610873565b6103156103cb3660046114e7565b6108c0565b6000546001600160a01b0316610242565b60025461021690600160a01b900462ffffff1681565b610315610405366004611513565b6109c1565b61029461041836600461145d565b610bf2565b6102427f000000000000000000000000000000000000000000000000000000000000000081565b610294610452366004611548565b610c7d565b610294610e02565b600354610216906301000000900462ffffff1681565b6103156104833660046114a0565b6001600160a01b031660009081526006602052604090205490565b6102427f000000000000000000000000000000000000000000000000000000000000000081565b6103156104d33660046115ef565b610f61565b6103156104e63660046114a0565b60066020526000908152604090205481565b6003546102169062ffffff1681565b610294610515366004611628565b61106b565b6102946105283660046114a0565b6110af565b600154610242906001600160a01b031681565b61038461054e3660046114bb565b6110ed565b6001546001600160a01b031633811461057f576040516338b601a360e11b815260040160405180910390fd5b6001600160a01b038316600090815260066020526040902054806105a35750505050565b600254600090620f4240906105c490600160d01b900462ffffff1686611668565b6105ce919061167f565b6000838152600560205260408120805492935083929091906105f19084906116a1565b90915550506040517ff67326db9c82bb81a05afd0d0db07bc3f75f7613c9dca5eedeff02d8cdcc74fb9061062c9084908890889086906116b4565b60405180910390a150505b505050565b6002546001600160a01b0316338114610668576040516338b601a360e11b815260040160405180910390fd5b6001600160a01b0383166000908152600760205260409020548061068c5750505050565b600254600090620f4240906106ad90600160b81b900462ffffff1686611668565b6106b7919061167f565b6000838152600560205260408120805492935083929091906106da9084906116a1565b90915550506040517fc4049913e96e245623a2d45ab552836b79e99d66befb96d82ff96b9b7f7eeb0e9061062c9084908890889086906116b4565b6002546001600160a01b0316338114610741576040516338b601a360e11b815260040160405180910390fd5b811561063757506001600160a01b0391909116600090815260076020526040902055565b60008281526005602052604081206001015483906001600160a01b031633146107a15760405163729260b160e11b815260040160405180910390fd5b6107ab84846111a8565b949350505050565b6107bb61134b565b6107c56000611378565b565b6000818152600560205260408120600101546001600160a01b03161515806107ed575081155b1561080b576040516378d0770560e01b815260040160405180910390fd5b60008281526005602090815260409182902060010180546001600160a01b03191633908117909155825190815290810184905281517fac113b25e2f6da9f42c0fcfcb2a028fd74e615dca6ef2a71abffad4577797072929181900390910190a1506001919050565b60008181526005602052604081206001015482906001600160a01b031633146108af5760405163729260b160e11b815260040160405180910390fd5b6108b983336111a8565b9392505050565b6000806001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001663a1c1fb4f336040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260248101889052604481018790526064016020604051808303816000875af1158015610947573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096b91906116d8565b9050600061097984876113c8565b90507f77ad8b04cbab9dca6c50359ef623aa13f7d709398d384e0884b234aec5681385843388846040516109b094939291906116b4565b60405180910390a150949350505050565b60006001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166323b872dd336040516001600160e01b031960e084901b1681526001600160a01b039091166004820152306024820152604481018690526064016020604051808303816000875af1158015610a46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6a91906116f1565b506040516387481e7360e01b8152600481018490526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906387481e73906024016020604051808303816000875af1158015610ad5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af991906116d8565b90506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001663a9059cbb336040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303816000875af1158015610b78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9c91906116f1565b506000610ba984836113c8565b90507f3ce823bb669d9fe2c8dff0dc88f8ce4297ea49600b3eafc60954c87bff594f5584338484604051610be094939291906116b4565b60405180910390a15090505b92915050565b6001546001600160a01b0316338114610c1e576040516338b601a360e11b815260040160405180910390fd5b8115610637576001600160a01b038316600081815260066020908152604091829020859055815192835282018490527f9e429360cfeef15ad3c2ba1c39a2c8788c2774663312112e0af1b084a5d56010910160405180910390a1505050565b614e208562ffffff161180610c995750620f42408462ffffff16115b80610cab5750620f42408362ffffff16115b15610cc95760405163c2c7709b60e01b815260040160405180910390fd5b60405163352e3a8360e01b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063352e3a8390610d1990339086908690600401611713565b60006040518083038186803b158015610d3157600080fd5b505afa158015610d45573d6000803e3d6000fd5b50506002805462ffffff808a16600160e81b026001600160e81b03909216919091179091556003805487831663010000000265ffffffffffff199091169289169290921791909117905550610d9f90504262093a806116a1565b6004557f7675f8a1fec4ff7e3c4b4a7771beca147e122e702f5e632a812a983d74136e0133600454604080516001600160a01b03909316835262ffffff808a1660208501528089169184019190915286166060830152608082015260a00161062c565b600254600160e81b810462ffffff908116600160a01b90920416148015610e3c575060025460035462ffffff908116600160b81b90920416145b8015610e6257506002546003546301000000900462ffffff908116600160d01b90920416145b15610e80576040516304fe479160e01b815260040160405180910390fd5b600454421015610eac57600480546040516374f75f6360e01b8152918201526024015b60405180910390fd5b60028054600354600160d01b6301000000820462ffffff908116820262ffffff60d01b19600160b81b948316850262ffffff60b81b19600160a01b600160e81b8904861681029190911665ffffffffffff60a01b19909816979097171716179485905560408051338152948604821660208601529285048116848401529304909216606082015290517fad985451be636dfc329b4c01326f5378dd03b425d9ddc03d21a38d7ebc8f6e599181900360800190a1565b6000806001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166391ac6f99336040516001600160e01b031960e084901b1681526001600160a01b039182166004820152908916602482015260448101889052606481018790526084016020604051808303816000875af1158015610ff0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101491906116d8565b9050600061102284836113c8565b90507fb2eade9032a35a2c8bf13d1232bffcfe60383b7541d8f3fddaa9eb53a832e1678433848460405161105994939291906116b4565b60405180910390a15095945050505050565b61107361134b565b600280546001600160a01b038085166001600160a01b03199283161790925560018054928416929091169190911790556110ab6107b3565b5050565b6110b761134b565b6001600160a01b0381166110e157604051631e4fbdf760e01b815260006004820152602401610ea3565b6110ea81611378565b50565b60008281526005602052604081206001015483906001600160a01b031633146111295760405163729260b160e11b815260040160405180910390fd5b600084815260056020526040902060010180546001600160a01b0319166001600160a01b0385161790557f4f1b00fb86992889ee465121c65a60c82612738f92c5de138d81ed4576e2544733604080516001600160a01b0392831681529186166020830152810186905260600160405180910390a15060019392505050565b60008060056000858152602001908152602001600020600001549050807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166391a0ac6a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611223573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124791906116d8565b101561126657604051639efc0a6960e01b815260040160405180910390fd5b60008481526005602052604080822091909155516308b8bb4b60e01b81526001600160a01b038481166004830152602482018390527f000000000000000000000000000000000000000000000000000000000000000016906308b8bb4b90604401600060405180830381600087803b1580156112e157600080fd5b505af11580156112f5573d6000803e3d6000fd5b5050604080516001600160a01b0387168152602081018590529081018790527f7728e907e9a9ce01e7031dcc773e276dab993b745d3295702af40a91d67683f89250606001905060405180910390a19392505050565b6000546001600160a01b031633146107c55760405163118cdaa760e01b8152336004820152602401610ea3565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000826113d757506000610bec565b336000908152600760205260408120849055600254620f42409061140790600160a01b900462ffffff1685611668565b611411919061167f565b6000858152600560205260408120805492935083929091906114349084906116a1565b9091555090949350505050565b80356001600160a01b038116811461145857600080fd5b919050565b6000806040838503121561147057600080fd5b61147983611441565b946020939093013593505050565b60006020828403121561149957600080fd5b5035919050565b6000602082840312156114b257600080fd5b6108b982611441565b600080604083850312156114ce57600080fd5b823591506114de60208401611441565b90509250929050565b6000806000606084860312156114fc57600080fd5b505081359360208301359350604090920135919050565b6000806040838503121561152657600080fd5b50508035926020909101359150565b803562ffffff8116811461145857600080fd5b60008060008060006080868803121561156057600080fd5b61156986611535565b945061157760208701611535565b935061158560408701611535565b9250606086013567ffffffffffffffff8111156115a157600080fd5b8601601f810188136115b257600080fd5b803567ffffffffffffffff8111156115c957600080fd5b8860208260051b84010111156115de57600080fd5b959894975092955050506020019190565b6000806000806080858703121561160557600080fd5b61160e85611441565b966020860135965060408601359560600135945092505050565b6000806040838503121561163b57600080fd5b61164483611441565b91506114de60208401611441565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610bec57610bec611652565b60008261169c57634e487b7160e01b600052601260045260246000fd5b500490565b80820180821115610bec57610bec611652565b9384526001600160a01b039290921660208401526040830152606082015260800190565b6000602082840312156116ea57600080fd5b5051919050565b60006020828403121561170357600080fd5b815180151581146108b957600080fd5b6001600160a01b0384168152604060208201819052810182905260008360608301825b85811015611764576001600160a01b0361174f84611441565b16825260209283019290910190600101611736565b50969550505050505056fea2646970667358221220ed28aa5c8a1320a6f611dc76294edb6710c34bd6fcc1fd2bb5907db72564f83e64736f6c634300081a0033000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea000000000000000000000000103747924e74708139a9400e4ab4bea79fffa380","name":"FrontendGateway","is_blueprint":false,"license_type":"none","is_fully_verified":true,"is_verified_via_eth_bytecode_db":true,"language":"solidity","evm_version":"paris","can_be_visualized_via_sol2uml":true,"is_verified_via_sourcify":true,"additional_sources":[{"file_path":"@openzeppelin/contracts/interfaces/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},{"file_path":"contracts/MintingHubV2/interface/IMintingHub.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {ILeadrate} from \"../../interface/ILeadrate.sol\";\nimport {IPosition} from \"./IPosition.sol\";\nimport {PositionRoller} from \"../PositionRoller.sol\";\n\ninterface IMintingHub {\n    function RATE() external view returns (ILeadrate);\n\n    function ROLLER() external view returns (PositionRoller);\n\n    function challenge(\n        address _positionAddr,\n        uint256 _collateralAmount,\n        uint256 minimumPrice\n    ) external returns (uint256);\n\n    function bid(uint32 _challengeNumber, uint256 size, bool postponeCollateralReturn) external;\n\n    function returnPostponedCollateral(address collateral, address target) external;\n\n    function buyExpiredCollateral(IPosition pos, uint256 upToAmount) external returns (uint256);\n\n    function clone(address owner, address parent, uint256 _initialCollateral, uint256 _initialMint, uint40 expiration) external returns (address);\n}\n"},{"file_path":"@openzeppelin/contracts/utils/cryptography/EIP712.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.20;\n\nimport {MessageHashUtils} from \"./MessageHashUtils.sol\";\nimport {ShortStrings, ShortString} from \"../ShortStrings.sol\";\nimport {IERC5267} from \"../../interfaces/IERC5267.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose\n * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract\n * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to\n * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n *\n * @custom:oz-upgrades-unsafe-allow state-variable-immutable\n */\nabstract contract EIP712 is IERC5267 {\n    using ShortStrings for *;\n\n    bytes32 private constant TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to\n    // invalidate the cached domain separator if the chain id changes.\n    bytes32 private immutable _cachedDomainSeparator;\n    uint256 private immutable _cachedChainId;\n    address private immutable _cachedThis;\n\n    bytes32 private immutable _hashedName;\n    bytes32 private immutable _hashedVersion;\n\n    ShortString private immutable _name;\n    ShortString private immutable _version;\n    string private _nameFallback;\n    string private _versionFallback;\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    constructor(string memory name, string memory version) {\n        _name = name.toShortStringWithFallback(_nameFallback);\n        _version = version.toShortStringWithFallback(_versionFallback);\n        _hashedName = keccak256(bytes(name));\n        _hashedVersion = keccak256(bytes(version));\n\n        _cachedChainId = block.chainid;\n        _cachedDomainSeparator = _buildDomainSeparator();\n        _cachedThis = address(this);\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {\n            return _cachedDomainSeparator;\n        } else {\n            return _buildDomainSeparator();\n        }\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /**\n     * @dev See {IERC-5267}.\n     */\n    function eip712Domain()\n        public\n        view\n        virtual\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _name which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Name() internal view returns (string memory) {\n        return _name.toStringWithFallback(_nameFallback);\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _version which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Version() internal view returns (string memory) {\n        return _version.toStringWithFallback(_versionFallback);\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Address.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            assembly (\"memory-safe\") {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/interfaces/IERC5267.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)\n\npragma solidity ^0.8.20;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"},{"file_path":"@openzeppelin/contracts/utils/cryptography/ECDSA.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS\n    }\n\n    /**\n     * @dev The signature derives the `address(0)`.\n     */\n    error ECDSAInvalidSignature();\n\n    /**\n     * @dev The signature has an invalid length.\n     */\n    error ECDSAInvalidSignatureLength(uint256 length);\n\n    /**\n     * @dev The signature has an S value that is in the upper half order.\n     */\n    error ECDSAInvalidSignatureS(bytes32 s);\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n     * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n     * and a bytes32 providing additional information about the error.\n     *\n     * If no error is returned, then the address can be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes memory signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly (\"memory-safe\") {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        unchecked {\n            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n            // We do not check for an overflow here since the shift operation results in 0 or 1.\n            uint8 v = uint8((uint256(vs) >> 255) + 27);\n            return tryRecover(hash, v, r, s);\n        }\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS, s);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature, bytes32(0));\n        }\n\n        return (signer, RecoverError.NoError, bytes32(0));\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n     */\n    function _throwError(RecoverError error, bytes32 errorArg) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert ECDSAInvalidSignature();\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert ECDSAInvalidSignatureLength(uint256(errorArg));\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert ECDSAInvalidSignatureS(errorArg);\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/introspection/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20Permit} from \"./IERC20Permit.sol\";\nimport {ERC20} from \"../ERC20.sol\";\nimport {ECDSA} from \"../../../utils/cryptography/ECDSA.sol\";\nimport {EIP712} from \"../../../utils/cryptography/EIP712.sol\";\nimport {Nonces} from \"../../../utils/Nonces.sol\";\n\n/**\n * @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\nabstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {\n    bytes32 private constant PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n\n    /**\n     * @dev Permit deadline has expired.\n     */\n    error ERC2612ExpiredSignature(uint256 deadline);\n\n    /**\n     * @dev Mismatched signature.\n     */\n    error ERC2612InvalidSigner(address signer, address owner);\n\n    /**\n     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n     *\n     * It's a good idea to use the same `name` that is defined as the ERC-20 token name.\n     */\n    constructor(string memory name) EIP712(name, \"1\") {}\n\n    /**\n     * @inheritdoc IERC20Permit\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        if (block.timestamp > deadline) {\n            revert ERC2612ExpiredSignature(deadline);\n        }\n\n        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        address signer = ECDSA.recover(hash, v, r, s);\n        if (signer != owner) {\n            revert ERC2612InvalidSigner(signer, owner);\n        }\n\n        _approve(owner, spender, value);\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {\n        return super.nonces(owner);\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {\n        return _domainSeparatorV4();\n    }\n}\n"},{"file_path":"contracts/Leadrate.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IReserve} from \"./interface/IReserve.sol\";\n\n/**\n * @title Leadrate (attempt at translating the concise German term 'Leitzins')\n *\n * A module that can provide other modules with the leading interest rate for the system.\n *\n **/\ncontract Leadrate {\n    IReserve public immutable equity;\n\n    // The following five variables are less than 256 bits, so they should be stored\n    // in the same slot, making them cheaper to access together, right?\n\n    uint24 public currentRatePPM; // 24 bits allows rates of up to ~1670% per year\n    uint24 public nextRatePPM;\n    uint40 public nextChange;\n\n    uint40 private anchorTime; // 40 bits for time in seconds spans up to 1000 human generations\n    uint64 private ticksAnchor; // in bips * seconds\n\n    event RateProposed(address who, uint24 nextRate, uint40 nextChange);\n    event RateChanged(uint24 newRate);\n\n    error NoPendingChange();\n    error ChangeNotReady();\n\n    constructor(IReserve equity_, uint24 initialRatePPM) {\n        equity = equity_;\n        nextRatePPM = initialRatePPM;\n        currentRatePPM = initialRatePPM;\n        nextChange = uint40(block.timestamp);\n        anchorTime = nextChange;\n        ticksAnchor = 0;\n        emit RateChanged(initialRatePPM); // emit for initialization indexing, if desired\n    }\n\n    /**\n     * Proposes a new interest rate that will automatically be applied after seven days.\n     * To cancel a proposal, just overwrite it with a new one proposing the current rate.\n     */\n    function proposeChange(uint24 newRatePPM_, address[] calldata helpers) external {\n        equity.checkQualified(msg.sender, helpers);\n        nextRatePPM = newRatePPM_;\n        nextChange = uint40(block.timestamp + 7 days);\n        emit RateProposed(msg.sender, nextRatePPM, nextChange);\n    }\n\n    /**\n     * Setting a previously proposed interest rate change into force.\n     */\n    function applyChange() external {\n        if (currentRatePPM == nextRatePPM) revert NoPendingChange();\n        uint40 timeNow = uint40(block.timestamp);\n        if (timeNow < nextChange) revert ChangeNotReady();\n        ticksAnchor += (timeNow - anchorTime) * currentRatePPM;\n        anchorTime = timeNow;\n        currentRatePPM = nextRatePPM;\n        emit RateChanged(currentRatePPM);\n    }\n\n    /**\n     * Total accumulated 'interest ticks' since this contract was deployed.\n     * One 'tick' is a ppm-second, so one month of 12% annual interest is\n     *   120000*30*24*3600 = 311040000000 ticks.\n     * Two months of 6% annual interest would result in the same number of\n     * ticks. For simplicity, this is linear, so there is no \"interest on interest\".\n     */\n    function currentTicks() public view returns (uint64) {\n        return ticks(block.timestamp);\n    }\n\n    function ticks(uint256 timestamp) public view returns (uint64) {\n        return ticksAnchor + (uint64(timestamp) - anchorTime) * currentRatePPM;\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/math/SafeCast.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/ERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n    mapping(address account => uint256) private _balances;\n\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            _totalSupply += value;\n        } else {\n            uint256 fromBalance = _balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                _balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                _totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                _balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        _allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},{"file_path":"contracts/Savings.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IDecentralizedEURO} from \"./interface/IDecentralizedEURO.sol\";\nimport {IReserve} from \"./interface/IReserve.sol\";\nimport {Leadrate} from \"./Leadrate.sol\";\n\n/**\n * @title Savings\n *\n * Module to enable savings based on a Leadrate (\"Leitzins\") module.\n *\n * As the interest rate changes, the speed at which 'ticks' are accumulated is\n * adjusted. The ticks counter serves as the basis for calculating the interest\n * due for the individual accounts.\n */\ncontract Savings is Leadrate {\n    IERC20 public immutable deuro;\n\n    mapping(address => Account) public savings;\n\n    struct Account {\n        uint192 saved;\n        uint64 ticks;\n    }\n\n    event Saved(address indexed account, uint192 amount);\n    event InterestCollected(address indexed account, uint256 interest);\n    event Withdrawn(address indexed account, uint192 amount);\n\n    // The module is considered disabled if the interest is zero or about to become zero within three days.\n    error ModuleDisabled();\n\n    constructor(IDecentralizedEURO deuro_, uint24 initialRatePPM) Leadrate(IReserve(deuro_.reserve()), initialRatePPM) {\n        deuro = IERC20(deuro_);\n    }\n\n    /**\n     * Shortcut for refreshBalance(msg.sender)\n     */\n    function refreshMyBalance() public returns (uint192) {\n        return refreshBalance(msg.sender);\n    }\n\n    /**\n     * Collects the accrued interest and adds it to the account.\n     *\n     * It can be beneficial to do so every now and then in order to start collecting\n     * interest on the accrued interest.\n     */\n    function refreshBalance(address owner) public returns (uint192) {\n        return refresh(owner).saved;\n    }\n\n    function refresh(address accountOwner) virtual internal returns (Account storage) {\n        Account storage account = savings[accountOwner];\n        uint64 ticks = currentTicks();\n        if (ticks > account.ticks) {\n            uint192 earnedInterest = calculateInterest(account, ticks);\n            if (earnedInterest > 0) {\n                // collect interest as you go and trigger accounting event\n                (IDecentralizedEURO(address(deuro))).distributeProfits(address(this), earnedInterest);\n                account.saved += earnedInterest;\n                emit InterestCollected(accountOwner, earnedInterest);\n            }\n            account.ticks = ticks;\n        }\n        return account;\n    }\n\n    function accruedInterest(address accountOwner) public view returns (uint192) {\n        return accruedInterest(accountOwner, block.timestamp);\n    }\n\n    function accruedInterest(address accountOwner, uint256 timestamp) public view returns (uint192) {\n        Account memory account = savings[accountOwner];\n        return calculateInterest(account, ticks(timestamp));\n    }\n\n    function calculateInterest(Account memory account, uint64 ticks) public view returns (uint192) {\n        if (ticks <= account.ticks || account.ticks == 0) {\n            return 0;\n        } else {\n            uint192 earnedInterest = uint192((uint256(ticks - account.ticks) * account.saved) / 1_000_000 / 365 days);\n            uint256 equity = IDecentralizedEURO(address(deuro)).equity();\n            if (earnedInterest > equity) {\n                return uint192(equity); // safe conversion as equity is smaller than uint192 earnedInterest\n            } else {\n                return earnedInterest;\n            }\n        }\n    }\n\n    /**\n     * Save 'amount'.\n     */\n    function save(uint192 amount) public {\n        save(msg.sender, amount);\n    }\n\n    function adjust(uint192 targetAmount) public {\n        Account storage balance = refresh(msg.sender);\n        if (balance.saved < targetAmount) {\n            save(targetAmount - balance.saved);\n        } else if (balance.saved > targetAmount) {\n            withdraw(msg.sender, balance.saved - targetAmount);\n        }\n    }\n\n    /**\n     * Send 'amount' to the account of the provided owner.\n     */\n    function save(address owner, uint192 amount) public {\n        if (currentRatePPM == 0) revert ModuleDisabled();\n        if (nextRatePPM == 0 && (nextChange <= block.timestamp)) revert ModuleDisabled();\n        Account storage balance = refresh(owner);\n        deuro.transferFrom(msg.sender, address(this), amount);\n        assert(balance.ticks >= currentTicks()); // @dev: should not differ, since there is no shift of interests\n        balance.saved += amount;\n        emit Saved(owner, amount);\n    }\n\n    /**\n     * Withdraw up to 'amount' to the target address.\n     * When trying to withdraw more than available, all that is available is withdrawn.\n     * Returns the actually transferred amount.\n     */\n    function withdraw(address target, uint192 amount) public returns (uint256) {\n        Account storage account = refresh(msg.sender);\n        if (amount >= account.saved) {\n            amount = account.saved;\n            delete savings[msg.sender];\n        } else {\n            account.saved -= amount;\n        }\n        deuro.transfer(target, amount);\n        emit Withdrawn(msg.sender, amount);\n        return amount;\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Errors.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"},{"file_path":"contracts/interface/ILeadrate.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ILeadrate {\n   function currentRatePPM() external view returns (uint24);\n   function currentTicks() external view returns (uint64);\n}"},{"file_path":"contracts/interface/IDecentralizedEURO.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IReserve} from \"./IReserve.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IDecentralizedEURO is IERC20 {\n    function suggestMinter(\n        address _minter,\n        uint256 _applicationPeriod,\n        uint256 _applicationFee,\n        string calldata _message\n    ) external;\n\n    function registerPosition(address position) external;\n\n    function denyMinter(address minter, address[] calldata helpers, string calldata message) external;\n\n    function reserve() external view returns (IReserve);\n\n    function minterReserve() external view returns (uint256);\n\n    function calculateAssignedReserve(uint256 mintedAmount, uint32 _reservePPM) external view returns (uint256);\n\n    function calculateFreedAmount(uint256 amountExcludingReserve, uint32 _reservePPM) external view returns (uint256);\n\n    function equity() external view returns (uint256);\n\n    function isMinter(address minter) external view returns (bool);\n\n    function getPositionParent(address position) external view returns (address);\n\n    function mint(address target, uint256 amount) external;\n\n    function mintWithReserve(address target, uint256 amount, uint32 reservePPM) external;\n\n    function burn(uint256 amount) external;\n\n    function burnFrom(address target, uint256 amount) external;\n\n    function burnWithoutReserve(uint256 amount, uint32 reservePPM) external;\n\n    function burnFromWithReserve(\n        address payer,\n        uint256 targetTotalBurnAmount,\n        uint32 reservePPM\n    ) external returns (uint256);\n\n    function coverLoss(address source, uint256 amount) external;\n\n    function distributeProfits(address recipient, uint256 amount) external;\n\n    function collectProfits(address source, uint256 _amount) external;\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},{"file_path":"contracts/utils/DEPSWrapper.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport {Equity} from \"../Equity.sol\";\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\nimport {ERC20Wrapper} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Wrapper.sol\";\n\ncontract DEPSWrapper is ERC20Permit, ERC20Wrapper {\n    Equity private immutable nDEPS;\n\n    constructor(\n        Equity nDEPS_\n    )\n        ERC20Permit(\"Decentralized Euro Protocol Share\")\n        ERC20(\"Decentralized Euro Protocol Share\", \"DEPS\")\n        ERC20Wrapper(nDEPS_)\n    {\n        nDEPS = nDEPS_;\n    }\n\n    // requires allowance\n    function wrap(uint256 amount) public {\n        depositFor(_msgSender(), amount);\n    }\n\n    function unwrap(uint256 amount) public {\n        withdrawTo(_msgSender(), amount);\n    }\n\n    function decimals() public view override(ERC20, ERC20Wrapper) returns (uint8) {\n        return ERC20Wrapper.decimals();\n    }\n\n    /**\n     * Sell immediately, bypassing the 90 day holding requirement if the\n     * average wrapped token has been around for long enough and no one\n     * cancelled the votes of this contract. Can help with market making\n     * between chains when this token is bridged.\n     *\n     * Anyone can prevent this method from being executable via the\n     * halveHoldingDuration function. Also, it won't be executable in an\n     * expanding market where the number of wrapped nDEPS doubles every\n     * 90 days such that the average holding period of this contract stays\n     * below that duration.\n     */\n    function unwrapAndSell(uint256 amount) public returns (uint256) {\n        super._burn(_msgSender(), amount);\n        return nDEPS.redeem(_msgSender(), amount);\n    }\n\n    /**\n     * Reduces the recorded holding duration of the wrapped nDEPS. This has two effects:\n     * - Averts the risk of this contract accumulating too many votes over time (i.e. 98%)\n     * - Can prevent \"unwrapAndSell\" from succeeding (which can be desired to prevent short\n     *   term arbitrage at the cost of all other nDEPS holders)\n     *\n     * Anyone with 2% of the votes can call this.\n     */\n    function halveHoldingDuration(address[] calldata helpers) public {\n        nDEPS.checkQualified(_msgSender(), helpers);\n        // causes our votes to be cut in half\n        nDEPS.transfer(address(this), totalSupply());\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/ShortStrings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.20;\n\nimport {StorageSlot} from \"./StorageSlot.sol\";\n\n// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |\n// | length  | 0x                                                              BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n *     using ShortStrings for *;\n *\n *     ShortString private immutable _name;\n *     string private _nameFallback;\n *\n *     constructor(string memory contractName) {\n *         _name = contractName.toShortStringWithFallback(_nameFallback);\n *     }\n *\n *     function name() external view returns (string memory) {\n *         return _name.toStringWithFallback(_nameFallback);\n *     }\n * }\n * ```\n */\nlibrary ShortStrings {\n    // Used as an identifier for strings longer than 31 bytes.\n    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n    error StringTooLong(string str);\n    error InvalidShortString();\n\n    /**\n     * @dev Encode a string of at most 31 chars into a `ShortString`.\n     *\n     * This will trigger a `StringTooLong` error is the input string is too long.\n     */\n    function toShortString(string memory str) internal pure returns (ShortString) {\n        bytes memory bstr = bytes(str);\n        if (bstr.length > 31) {\n            revert StringTooLong(str);\n        }\n        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n    }\n\n    /**\n     * @dev Decode a `ShortString` back to a \"normal\" string.\n     */\n    function toString(ShortString sstr) internal pure returns (string memory) {\n        uint256 len = byteLength(sstr);\n        // using `new string(len)` would work locally but is not memory safe.\n        string memory str = new string(32);\n        assembly (\"memory-safe\") {\n            mstore(str, len)\n            mstore(add(str, 0x20), sstr)\n        }\n        return str;\n    }\n\n    /**\n     * @dev Return the length of a `ShortString`.\n     */\n    function byteLength(ShortString sstr) internal pure returns (uint256) {\n        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n        if (result > 31) {\n            revert InvalidShortString();\n        }\n        return result;\n    }\n\n    /**\n     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n     */\n    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n        if (bytes(value).length < 32) {\n            return toShortString(value);\n        } else {\n            StorageSlot.getStringSlot(store).value = value;\n            return ShortString.wrap(FALLBACK_SENTINEL);\n        }\n    }\n\n    /**\n     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n     */\n    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return toString(value);\n        } else {\n            return store;\n        }\n    }\n\n    /**\n     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using\n     * {setWithFallback}.\n     *\n     * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n     */\n    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return byteLength(value);\n        } else {\n            return bytes(store).length;\n        }\n    }\n}\n"},{"file_path":"contracts/gateway/interface/IMintingHubGateway.sol","source_code":"// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\nimport {IMintingHub} from \"../../MintingHubV2/interface/IMintingHub.sol\";\nimport {IFrontendGateway} from \"./IFrontendGateway.sol\";\n\ninterface IMintingHubGateway {\n    function GATEWAY() external view returns (IFrontendGateway);\n    function notifyInterestPaid(uint256 amount) external;\n    function openPosition(address _collateralAddress, uint256 _minCollateral, uint256 _initialCollateral, uint256 _mintingMaximum, uint40 _initPeriodSeconds, uint40 _expirationSeconds, uint40 _challengeSeconds, uint24 _riskPremium, uint256 _liqPrice, uint24 _reservePPM, bytes32 _frontendCode) external returns (address);\n    function clone(address owner, address parent, uint256 _initialCollateral, uint256 _initialMint, uint40 expiration, bytes32 frontendCode) external returns (address);\n}\n"},{"file_path":"@openzeppelin/contracts/utils/introspection/ERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/interfaces/IERC1363.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Context.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/StorageSlot.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Strings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"},{"file_path":"contracts/Equity.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport {DecentralizedEURO} from \"./DecentralizedEURO.sol\";\nimport {ERC165} from \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport {ERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC3009} from \"./impl/ERC3009.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IReserve} from \"./interface/IReserve.sol\";\nimport {MathUtil} from \"./utils/MathUtil.sol\";\n\n/**\n * @title Equity\n * @notice If the DecentralizedEURO system was a bank, this contract would represent the equity on its balance sheet.\n * Like a corporation, the owners of the equity capital are the shareholders, or in this case the holders\n * of Native Decentralized Euro Protocol Share (nDEPS) tokens. Anyone can mint additional nDEPS tokens by adding DecentralizedEUROs to the\n * reserve pool. Also, nDEPS tokens can be redeemed for DecentralizedEUROs again after a minimum holding period.\n * Furthermore, the nDEPS shares come with some voting power. Anyone that held at least 2% of the holding-period-\n * weighted reserve pool shares gains veto power and can veto new proposals.\n */\ncontract Equity is ERC20Permit, ERC3009, MathUtil, IReserve, ERC165 {\n    /**\n     * The VALUATION_FACTOR determines the market cap of the reserve pool shares relative to the equity reserves.\n     * The following always holds: Market Cap = Valuation Factor * Equity Reserve = Price * Supply\n     *\n     * In the absence of fees, profits and losses, the variables grow as follows when nDEPS tokens are minted:\n     *\n     * |        Reserve     |      Market Cap    |     Price    |       Supply    |\n     * |              1_000 |              5_000 |       0.0005 |      10_000_000 |\n     * |        100_000_000 |        500_000_000 |       5      |     100_000_000 |\n     * | 10_000_000_000_000 | 50_000_000_000_000 |  50_000      |   1_000_000_000 |\n     *\n     * i.e., the supply is proportional to the fifth root of the reserve and the price is proportional to the\n     * squared cubic root. When profits accumulate or losses materialize, the reserve, the market cap,\n     * and the price are adjusted proportionally. In the absence of extreme inflation of the Euro, it is unlikely\n     * that there will ever be more than ten million nDEPS.\n     */\n    uint32 public constant VALUATION_FACTOR = 5; // Changed from 3 to 5 as requested\n\n    uint256 private constant MINIMUM_EQUITY = 1_000 * ONE_DEC18;\n\n    /**\n     * @notice The quorum in basis points. 100 is 1%.\n     */\n    uint32 private constant QUORUM = 200;\n\n    /**\n     * @notice The number of digits to store the average holding time of share tokens.\n     */\n    uint8 private constant TIME_RESOLUTION_BITS = 20;\n\n    /**\n     * @notice The minimum holding duration. You are not allowed to redeem your pool shares if you held them\n     * for less than the minimum holding duration at average. For example, if you have two pool shares at your\n     * address, one acquired 5 days ago and one acquired 105 days ago, you cannot redeem them as the average\n     * holding duration of your shares is only 55 days < 90 days.\n     */\n    uint256 public constant MIN_HOLDING_DURATION = 90 days << TIME_RESOLUTION_BITS; // Set to 5 for local testing\n\n    DecentralizedEURO public immutable dEURO;\n\n    /**\n     * @dev To track the total number of votes we need to know the number of votes at the anchor time and when the\n     * anchor time was. This is (hopefully) stored in one 256 bit slot, with the anchor time taking 64 Bits and\n     * the total vote count 192 Bits. Given the sub-second resolution of 20 Bits, the implicit assumption is\n     * that the timestamp can always be stored in 44 Bits (i.e., it does not exceed half a million years). Further,\n     * given 18 decimals (about 60 Bits), this implies that the total supply cannot exceed\n     *   192 - 60 - 44 - 20 = 68 Bits\n     * Here, we are also safe, as 68 Bits would imply more than a trillion outstanding shares. In fact,\n     * a limit of about 2**36 shares (that's about 2**96 Bits when taking into account the decimals) is imposed\n     * when minting. This means that the maximum supply is billions of shares, which could only be reached in\n     * a scenario with hyperinflation, in which case the stablecoin is worthless anyway.\n     */\n    uint192 private totalVotesAtAnchor; // Total number of votes at the anchor time\n    uint64 private totalVotesAnchorTime; // 44 Bits for the time stamp, 20 Bit sub-second resolution\n\n    /**\n     * @notice Keeping track of who delegated votes to whom.\n     * Note that delegation does not mean you cannot vote / veto anymore; it just means that the delegate can\n     * benefit from your votes when invoking a veto. Circular delegations are valid but do not help when voting.\n     */\n    mapping(address owner => address delegate) public delegates;\n\n    /**\n     * @notice A time stamp in the past such that: votes = balance * (time passed since anchor was set).\n     */\n    mapping(address owner => uint64 timestamp) private voteAnchor; // 44 bits for time stamp, 20 sub-second resolution\n\n    event Delegation(address indexed from, address indexed to); // indicates a delegation\n    event Trade(address who, int256 amount, uint256 totPrice, uint256 newprice); // amount pos or neg for mint or redemption\n\n    error BelowMinimumHoldingPeriod();\n    error NotQualified();\n    error NotMinter();\n    error InsufficientEquity();\n    error TooManyShares();\n    error TotalSupplyExceeded();\n\n    constructor(\n        DecentralizedEURO dEURO_\n    )\n        ERC20Permit(\"Native Decentralized Euro Protocol Share\")\n        ERC20(\"Native Decentralized Euro Protocol Share\", \"nDEPS\")\n    {\n        dEURO = dEURO_;\n    }\n\n    /**\n     * @notice Returns the price of one nDEPS in dEURO with 18 decimals precision.\n     */\n    function price() public view returns (uint256) {\n        uint256 equity = dEURO.equity();\n        if (equity == 0 || totalSupply() == 0) {\n            return 10 ** 14; \n        } else {\n            return (VALUATION_FACTOR * dEURO.equity() * ONE_DEC18) / totalSupply();\n        }\n    }\n\n    function _update(address from, address to, uint256 value) internal override {\n        if (value > 0) {\n            // No need to adjust the sender's votes. When they send out 10% of their shares, they also lose 10% of\n            // their votes, so everything falls nicely into place. Recipient votes should stay the same, but grow\n            // faster in the future, requiring an adjustment of the anchor.\n            uint256 roundingLoss = _adjustRecipientVoteAnchor(to, value);\n            // The total also must be adjusted and kept accurate by taking into account the rounding error.\n            _adjustTotalVotes(from, value, roundingLoss);\n        }\n        super._update(from, to, value);\n    }\n\n    /**\n     * @notice Returns whether the given address is allowed to redeem nDEPS, which is the\n     * case after their average holding duration is larger than the required minimum.\n     */\n    function canRedeem(address owner) public view returns (bool) {\n        return _anchorTime() - voteAnchor[owner] >= MIN_HOLDING_DURATION;\n    }\n\n    /**\n     * @notice Decrease the total votes anchor when tokens lose their voting power due to being moved.\n     * @param from      sender\n     * @param amount    amount to be sent\n     */\n    function _adjustTotalVotes(address from, uint256 amount, uint256 roundingLoss) internal {\n        uint64 time = _anchorTime();\n        uint256 lostVotes = from == address(0x0) ? 0 : (time - voteAnchor[from]) * amount;\n        totalVotesAtAnchor = uint192(totalVotes() - roundingLoss - lostVotes);\n        totalVotesAnchorTime = time;\n    }\n\n    /**\n     * @notice The vote anchor of the recipient is moved forward such that the number of calculated\n     * votes does not change despite the higher balance.\n     * @param to        receiver address\n     * @param amount    amount to be received\n     * @return the number of votes lost due to rounding errors\n     */\n    function _adjustRecipientVoteAnchor(address to, uint256 amount) internal returns (uint256) {\n        if (to != address(0x0)) {\n            uint256 recipientVotes = votes(to); // for example 21 if 7 shares were held for 3 seconds\n            uint256 newbalance = balanceOf(to) + amount; // for example 11 if 4 shares are added\n            // new example: anchor is only 21 / 11 = ~1 second in the past\n            voteAnchor[to] = uint64(_anchorTime() - recipientVotes / newbalance);\n            return recipientVotes % newbalance; // we have lost 21 % 11 = 10 votes\n        } else {\n            // optimization for burn, vote anchor of null address does not matter\n            return 0;\n        }\n    }\n\n    /**\n     * @notice Time stamp with some additional bits for higher resolution.\n     */\n    function _anchorTime() internal view returns (uint64) {\n        return uint64(block.timestamp << TIME_RESOLUTION_BITS);\n    }\n\n    /**\n     * @notice The relative voting power of the address.\n     * @return A percentage with 1e18 being 100%\n     */\n    function relativeVotes(address holder) external view returns (uint256) {\n        return (ONE_DEC18 * votes(holder)) / totalVotes();\n    }\n\n    /**\n     * @notice The votes of the holder, excluding votes from delegates.\n     */\n    function votes(address holder) public view returns (uint256) {\n        return balanceOf(holder) * (_anchorTime() - voteAnchor[holder]);\n    }\n\n    /**\n     * @notice How long the holder already held onto their average nDEPS in seconds.\n     */\n    function holdingDuration(address holder) public view returns (uint256) {\n        return (_anchorTime() - voteAnchor[holder]) >> TIME_RESOLUTION_BITS;\n    }\n\n    /**\n     * @notice Total number of votes in the system.\n     */\n    function totalVotes() public view returns (uint256) {\n        return totalVotesAtAnchor + totalSupply() * (_anchorTime() - totalVotesAnchorTime);\n    }\n\n    /**\n     * @notice The number of votes the sender commands when taking the support of the helpers into account.\n     * @param sender    The address whose total voting power is of interest\n     * @param helpers   An incrementally sorted list of helpers without duplicates and without the sender.\n     *                  The call fails if the list contains an address that does not delegate to sender.\n     *                  For indirect delegates, i.e. a -> b -> c, both a and b must be included for both to count.\n     * @return          The total number of votes of sender at the current point in time.\n     */\n    function votesDelegated(address sender, address[] calldata helpers) public view returns (uint256) {\n        uint256 _votes = votes(sender);\n        require(_checkDuplicatesAndSorted(helpers));\n        for (uint i = 0; i < helpers.length; i++) {\n            address current = helpers[i];\n            require(current != sender);\n            require(_canVoteFor(sender, current));\n            _votes += votes(current);\n        }\n        return _votes;\n    }\n\n    function _checkDuplicatesAndSorted(address[] calldata helpers) internal pure returns (bool ok) {\n        if (helpers.length <= 1) {\n            return true;\n        } else {\n            address prevAddress = helpers[0];\n            for (uint i = 1; i < helpers.length; i++) {\n                if (helpers[i] <= prevAddress) {\n                    return false;\n                }\n                prevAddress = helpers[i];\n            }\n            return true;\n        }\n    }\n\n    /**\n     * @notice Checks whether the sender address is qualified given a list of helpers that delegated their votes\n     * directly or indirectly to the sender. It is the responsibility of the caller to figure out whether\n     * helpers are necessary and to identify them by scanning the blockchain for Delegation events.\n     */\n    function checkQualified(address sender, address[] calldata helpers) public view override {\n        uint256 _votes = votesDelegated(sender, helpers);\n        if (_votes * 10_000 < QUORUM * totalVotes()) revert NotQualified();\n    }\n\n    /**\n     * @notice Increases the voting power of the delegate by your number of votes without taking away any voting power\n     * from the sender.\n     */\n    function delegateVoteTo(address delegate) external {\n        delegates[msg.sender] = delegate;\n        emit Delegation(msg.sender, delegate);\n    }\n\n    function _canVoteFor(address delegate, address owner) internal view returns (bool) {\n        if (owner == delegate) {\n            return true;\n        } else if (owner == address(0x0)) {\n            return false;\n        } else {\n            return _canVoteFor(delegate, delegates[owner]);\n        }\n    }\n\n    /**\n     * @notice Since quorum is rather low, it is important to have a way to prevent malicious minority holders\n     * from blocking the whole system. This method provides a way for the good guys to team up and destroy\n     * the bad guy's votes (at the cost of also reducing their own votes). This mechanism potentially\n     * gives full control over the system to whoever has 51% of the votes.\n     *\n     * Since this is a rather aggressive measure, delegation is not supported. Every holder must call this\n     * method on their own.\n     * @param targets          The target addresses to remove votes from\n     * @param votesToDestroy   The maximum number of votes the caller is willing to sacrifice\n     */\n    function kamikaze(address[] calldata targets, uint256 votesToDestroy) external {\n        uint256 budget = _reduceVotes(msg.sender, votesToDestroy);\n        uint256 destroyedVotes = 0;\n        for (uint256 i = 0; i < targets.length && destroyedVotes < budget; i++) {\n            destroyedVotes += _reduceVotes(targets[i], budget - destroyedVotes);\n        }\n        require(destroyedVotes > 0); // sanity check\n        totalVotesAtAnchor = uint192(totalVotes() - destroyedVotes - budget);\n        totalVotesAnchorTime = _anchorTime();\n    }\n\n    function _reduceVotes(address target, uint256 amount) internal returns (uint256) {\n        uint256 votesBefore = votes(target);\n        if (amount >= votesBefore) {\n            amount = votesBefore;\n            voteAnchor[target] = _anchorTime();\n            return votesBefore;\n        } else {\n            voteAnchor[target] = uint64(_anchorTime() - (votesBefore - amount) / balanceOf(target));\n            return votesBefore - votes(target);\n        }\n    }\n\n    /**\n     * @notice Call this method to obtain newly minted pool shares in exchange for DecentralizedEUROs.\n     * No allowance required (i.e., it is hard-coded in the DecentralizedEURO token contract).\n     * Make sure to invest at least 10e-12 * market cap to avoid rounding losses.\n     *\n     * @dev If equity is close to zero or negative, you need to send enough dEURO to bring equity back to 1_000 dEURO.\n     *\n     * @param amount            DecentralizedEUROs to invest\n     * @param expectedShares    Minimum amount of expected shares for front running protection\n     */\n    function invest(uint256 amount, uint256 expectedShares) external returns (uint256) {\n        return _invest(_msgSender(), amount, expectedShares);\n    }\n\n    function investFor(address investor, uint256 amount, uint256 expectedShares) external returns (uint256) {\n        if (!dEURO.isMinter(_msgSender())) revert NotMinter();\n        return _invest(investor, amount, expectedShares);\n    }\n\n    function _invest(address investor, uint256 amount, uint256 expectedShares) internal returns (uint256) {\n        dEURO.transferFrom(investor, address(this), amount);\n        uint256 equity = dEURO.equity();\n        if (equity < MINIMUM_EQUITY) revert InsufficientEquity(); // ensures that the initial deposit is at least 1_000 dEURO\n\n        uint256 shares = _calculateShares(equity <= amount ? 0 : equity - amount, amount);\n        require(shares >= expectedShares);\n        _mint(investor, shares);\n        emit Trade(investor, int(shares), amount, price());\n\n        // limit the total supply to a reasonable amount to guard against overflows with price and vote calculations\n        if(totalSupply() > type(uint96).max) revert TotalSupplyExceeded();\n        return shares;\n    }\n\n    /**\n     * @notice Calculate shares received when investing DecentralizedEUROs\n     * @param investment    dEURO to be invested\n     * @return shares to be received in return\n     */\n    function calculateShares(uint256 investment) external view returns (uint256) {\n        return _calculateShares(dEURO.equity(), investment);\n    }\n\n    function _calculateShares(uint256 capitalBefore, uint256 investment) internal view returns (uint256) {\n        uint256 totalShares = totalSupply();\n        uint256 investmentExFees = (investment * 980) / 1_000; // remove 2% fee\n        // Assign 10_000_000 nDEPS for the initial deposit, calculate the amount otherwise\n        uint256 newTotalShares = (capitalBefore < MINIMUM_EQUITY || totalShares == 0)\n            ? totalShares + 10_000_000 * ONE_DEC18\n            : _mulD18(totalShares, _fifthRoot(_divD18(capitalBefore + investmentExFees, capitalBefore)));\n        return newTotalShares - totalShares;\n    }\n\n    /**\n     * @notice Redeem the given amount of shares owned by the sender and transfer the proceeds to the target.\n     * @return The amount of dEURO transferred to the target\n     */\n    function redeem(address target, uint256 shares) external returns (uint256) {\n        return _redeemFrom(msg.sender, target, shares);\n    }\n\n    /**\n     * @notice Like redeem(...), but with an extra parameter to protect against front running.\n     * @param expectedProceeds  The minimum acceptable redemption proceeds.\n     */\n    function redeemExpected(address target, uint256 shares, uint256 expectedProceeds) external returns (uint256) {\n        uint256 proceeds = _redeemFrom(msg.sender, target, shares);\n        require(proceeds >= expectedProceeds);\n        return proceeds;\n    }\n\n    /**\n     * @notice Redeem nDEPS based on an allowance from the owner to the caller.\n     * See also redeemExpected(...).\n     */\n    function redeemFrom(\n        address owner,\n        address target,\n        uint256 shares,\n        uint256 expectedProceeds\n    ) external returns (uint256) {\n        _spendAllowance(owner, msg.sender, shares);\n        uint256 proceeds = _redeemFrom(owner, target, shares);\n        require(proceeds >= expectedProceeds);\n        return proceeds;\n    }\n\n    function _redeemFrom(address owner, address target, uint256 shares) internal returns (uint256) {\n        if(!canRedeem(owner)) revert BelowMinimumHoldingPeriod();\n        uint256 proceeds = calculateProceeds(shares);\n        _burn(owner, shares);\n        dEURO.transfer(target, proceeds);\n        emit Trade(owner, -int(shares), proceeds, price());\n        return proceeds;\n    }\n\n    /**\n     * @notice Calculate dEURO received when depositing shares\n     * @param shares number of shares we want to exchange for dEURO,\n     *               in dec18 format\n     * @return amount of dEURO received for the shares\n     */\n    function calculateProceeds(uint256 shares) public view returns (uint256) {\n        uint256 totalShares = totalSupply();\n        if (shares + ONE_DEC18 >= totalShares) revert TooManyShares(); // make sure there is always at least one share\n        uint256 capital = dEURO.equity();\n        uint256 reductionAfterFees = (shares * 980) / 1_000; // remove 2% fee\n        uint256 newCapital = _mulD18(capital, _power5(_divD18(totalShares - reductionAfterFees, totalShares)));\n        return capital - newCapital;\n    }\n\n    /**\n     * @notice If there is less than 1_000 dEURO in equity left (maybe even negative), the system is at risk\n     * and we should allow qualified nDEPS holders to restructure the system.\n     *\n     * Example: there was a devastating loss and equity stands at -1'000'000. Most shareholders have lost hope in the\n     * DecentralizedEURO system except for a group of small nDEPS holders who still believe in it and are willing to provide\n     * 2'000'000 dEURO to save it. These brave souls are essentially donating 1'000'000 to the minter reserve and it\n     * would be wrong to force them to share the other million with the passive nDEPS holders. Instead, they will get\n     * the possibility to bootstrap the system again owning 100% of all nDEPS shares.\n     *\n     * @param helpers          A list of addresses that delegate to the caller in incremental order\n     * @param addressesToWipe  A list of addresses whose nDEPS will be burned to zero\n     */\n    function restructureCapTable(address[] calldata helpers, address[] calldata addressesToWipe) external {\n        require(dEURO.equity() < MINIMUM_EQUITY);\n        checkQualified(msg.sender, helpers);\n        for (uint256 i = 0; i < addressesToWipe.length; i++) {\n            address current = addressesToWipe[i];\n            _burn(current, balanceOf(current));\n        }\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return\n            interfaceId == type(IERC20).interfaceId ||\n            interfaceId == type(ERC20Permit).interfaceId ||\n            interfaceId == type(ERC3009).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},{"file_path":"contracts/utils/MathUtil.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @title Functions for share valuation\n */\ncontract MathUtil {\n    uint256 internal constant ONE_DEC18 = 10 ** 18;\n\n    // Let's go for 12 digits of precision (18-6)\n    uint256 internal constant THRESH_DEC18 = 10 ** 6;\n\n    /**\n     * @notice Fifth root with Halley approximation\n     *         Number 1e18 decimal\n     * @param _v     number for which we calculate x**(1/5)\n     * @return returns _v**(1/5)\n     */\n    function _fifthRoot(uint256 _v) internal pure returns (uint256) {\n        // Good first guess for _v slightly above 1.0, which is often the case in the dEURO system\n        uint256 x = _v > ONE_DEC18 && _v < 10 ** 19 ? (_v - ONE_DEC18) / 5 + ONE_DEC18 : ONE_DEC18;\n        uint256 diff;\n        do {\n            uint256 powX5 = _power5(x);\n            uint256 xnew = (x * (2 * powX5 + 3 * _v)) / (3 * powX5 + 2 * _v);\n            diff = xnew > x ? xnew - x : x - xnew;\n            x = xnew;\n        } while (diff > THRESH_DEC18);\n        return x;\n    }\n\n    function _mulD18(uint256 _a, uint256 _b) internal pure returns (uint256) {\n        return (_a * _b) / ONE_DEC18;\n    }\n\n    function _divD18(uint256 _a, uint256 _b) internal pure returns (uint256) {\n        return (_a * ONE_DEC18) / _b;\n    }\n\n    function _power5(uint256 _x) internal pure returns (uint256) {\n        return _mulD18(_mulD18(_mulD18(_mulD18(_x, _x), _x), _x), _x);\n    }\n\n    function _min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n    \n    /**\n     * @notice Performs ceiling division for PPM calculations using formula: ceil(amount / (1 - ppm/1000000))\n     * @param amount The base amount to divide\n     * @param ppm Parts per million value (e.g., 200000 for 20%)\n     * @return The result of ceiling division\n     */\n    function _ceilDivPPM(uint256 amount, uint24 ppm) internal pure returns (uint256) {\n        return amount == 0 ? 0 : (amount * 1_000_000 - 1) / (1_000_000 - ppm) + 1;\n    }\n}\n"},{"file_path":"contracts/gateway/interface/IFrontendGateway.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFrontendGateway {\n    struct FrontendCode {\n        uint256 balance;\n        address owner;\n    }\n\n    event FrontendCodeRegistered(address owner, bytes32 frontendCode);\n    event FrontendCodeTransferred(address from, address to, bytes32 frontendCode);\n    event FrontendCodeRewardsWithdrawn(address to, uint256 amount, bytes32 frontendCode);\n    event NewPositionRegistered(address position, bytes32 frontendCode);\n    event RateChangesProposed(address who, uint24 nextFeeRate, uint24 nextSavingsFeeRate, uint24 nextMintingFeeRate, uint256 nextChange);\n    event RateChangesExecuted(address who, uint24 nextFeeRate, uint24 nextSavingsFeeRate, uint24 nextMintingFeeRate);\n    \n    event InvestRewardAdded(bytes32 frontendCode, address user, uint256 amount, uint256 reward);\n    event RedeemRewardAdded(bytes32 frontendCode, address user, uint256 amount, uint256 reward);\n    event UnwrapAndSellRewardAdded(bytes32 frontendCode, address user, uint256 amount, uint256 reward);\n    event SavingsRewardAdded(bytes32 frontendCode, address saver, uint256 interest, uint256 reward);\n    event PositionRewardAdded(bytes32 frontendCode, address position, uint256 amount, uint256 reward);\n\n    error FrontendCodeAlreadyExists();\n    error NotFrontendCodeOwner();\n    error NotGatewayService();\n    error ProposedChangesToHigh();\n    error NoOpenChanges();\n    error NotDoneWaiting(uint256 minmumExecutionTime);\n    error EquityTooLow();\n\n    function invest(uint256 amount, uint256 expectedShares, bytes32 frontendCode) external returns (uint256);\n    function redeem(address target, uint256 shares, uint256 expectedProceeds, bytes32 frontendCode) external returns (uint256);\n    function unwrapAndSell(uint256 amount, bytes32 frontendCode) external returns (uint256);\n\n    function updateSavingCode(address savingsOwner, bytes32 frontendCode) external;\n    function updateSavingRewards(address saver, uint256 interest) external;\n\n    function registerPosition(address position, bytes32 frontendCode) external;\n    function updatePositionRewards(address position, uint256 amount) external;\n    function getPositionFrontendCode(address position)view external  returns(bytes32);\n\n    // Frontend Code Logic\n    function registerFrontendCode(bytes32 frontendCode) external returns (bool);\n    function transferFrontendCode(bytes32 frontendCode, address to) external returns (bool);\n    function withdrawRewards(bytes32 frontendCode) external returns (uint256);\n    function withdrawRewardsTo(bytes32 frontendCode, address to) external returns (uint256);\n\n    // Governance\n    function proposeChanges(uint24 newFeeRatePPM_, uint24 newSavingsFeeRatePPM_, uint24 newMintingFeeRatePPM_, address[] calldata helpers) external;\n    function executeChanges() external;\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/extensions/ERC20Wrapper.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Wrapper.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20, IERC20Metadata, ERC20} from \"../ERC20.sol\";\nimport {SafeERC20} from \"../utils/SafeERC20.sol\";\n\n/**\n * @dev Extension of the ERC-20 token contract to support token wrapping.\n *\n * Users can deposit and withdraw \"underlying tokens\" and receive a matching number of \"wrapped tokens\". This is useful\n * in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the\n * wrapping of an existing \"basic\" ERC-20 into a governance token.\n *\n * WARNING: Any mechanism in which the underlying token changes the {balanceOf} of an account without an explicit transfer\n * may desynchronize this contract's supply and its underlying balance. Please exercise caution when wrapping tokens that\n * may undercollateralize the wrapper (i.e. wrapper's total supply is higher than its underlying balance). See {_recover}\n * for recovering value accrued to the wrapper.\n */\nabstract contract ERC20Wrapper is ERC20 {\n    IERC20 private immutable _underlying;\n\n    /**\n     * @dev The underlying token couldn't be wrapped.\n     */\n    error ERC20InvalidUnderlying(address token);\n\n    constructor(IERC20 underlyingToken) {\n        if (underlyingToken == this) {\n            revert ERC20InvalidUnderlying(address(this));\n        }\n        _underlying = underlyingToken;\n    }\n\n    /**\n     * @dev See {ERC20-decimals}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) {\n            return value;\n        } catch {\n            return super.decimals();\n        }\n    }\n\n    /**\n     * @dev Returns the address of the underlying ERC-20 token that is being wrapped.\n     */\n    function underlying() public view returns (IERC20) {\n        return _underlying;\n    }\n\n    /**\n     * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.\n     */\n    function depositFor(address account, uint256 value) public virtual returns (bool) {\n        address sender = _msgSender();\n        if (sender == address(this)) {\n            revert ERC20InvalidSender(address(this));\n        }\n        if (account == address(this)) {\n            revert ERC20InvalidReceiver(account);\n        }\n        SafeERC20.safeTransferFrom(_underlying, sender, address(this), value);\n        _mint(account, value);\n        return true;\n    }\n\n    /**\n     * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.\n     */\n    function withdrawTo(address account, uint256 value) public virtual returns (bool) {\n        if (account == address(this)) {\n            revert ERC20InvalidReceiver(account);\n        }\n        _burn(_msgSender(), value);\n        SafeERC20.safeTransfer(_underlying, account, value);\n        return true;\n    }\n\n    /**\n     * @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake or acquired from\n     * rebasing mechanisms. Internal function that can be exposed with access control if desired.\n     */\n    function _recover(address account) internal virtual returns (uint256) {\n        uint256 value = _underlying.balanceOf(address(this)) - totalSupply();\n        _mint(account, value);\n        return value;\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\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    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},{"file_path":"@openzeppelin/contracts/interfaces/draft-IERC6093.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Panic.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/token/ERC20/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\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    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n     * 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 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"},{"file_path":"@openzeppelin/contracts/utils/math/SignedMath.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},{"file_path":"contracts/DecentralizedEURO.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Equity} from \"./Equity.sol\";\nimport {IDecentralizedEURO} from \"./interface/IDecentralizedEURO.sol\";\nimport {IReserve} from \"./interface/IReserve.sol\";\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\nimport {ERC165} from \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport {ERC3009} from \"./impl/ERC3009.sol\";\n\n/**\n * @title DecentralizedEURO\n * @notice The DecentralizedEURO (dEURO) is an ERC-20 token that is designed to track the value of the Euro.\n * It is not upgradable, but open to arbitrary minting plugins. These are automatically accepted if none of the\n * qualified pool shareholders casts a veto, leading to a flexible but conservative governance.\n */\ncontract DecentralizedEURO is ERC20Permit, ERC3009, IDecentralizedEURO, ERC165 {\n    /**\n     * @notice Minimal fee and application period when suggesting a new minter.\n     */\n    uint256 public constant MIN_FEE = 1000 * (10 ** 18);\n    uint256 public immutable MIN_APPLICATION_PERIOD; // For example: 10 days\n\n    /**\n     * @notice The contract that holds the reserve.\n     */\n    IReserve public immutable override reserve;\n\n    /**\n     * @notice How much of the reserve belongs to the minters. Everything else belongs to the pool shareholders.\n     * Stored with 6 additional digits of accuracy so no rounding is necessary when dealing with parts per\n     * million (ppm) in reserve calculations.\n     */\n    uint256 private minterReserveE6;\n\n    /**\n     * @notice Map of minters to approval time stamps. If the time stamp is in the past, the minter contract is allowed\n     * to mint DecentralizedEUROs.\n     */\n    mapping(address minter => uint256 validityStart) public minters;\n\n    /**\n     * @notice List of positions that are allowed to mint and the minter that registered them.\n     */\n    mapping(address position => address registeringMinter) public positions;\n\n    event MinterApplied(address indexed minter, uint256 applicationPeriod, uint256 applicationFee, string message);\n    event MinterDenied(address indexed minter, string message);\n    event Loss(address indexed reportingMinter, uint256 amount);\n    event Profit(address indexed reportingMinter, uint256 amount);\n    event ProfitDistributed(address indexed recipient, uint256 amount);\n\n    error PeriodTooShort();\n    error FeeTooLow();\n    error AlreadyRegistered();\n    error NotMinter();\n    error TooLate();\n\n    modifier minterOnly() {\n        if (!isMinter(msg.sender) && !isMinter(positions[msg.sender])) revert NotMinter();\n        _;\n    }\n\n    /**\n     * @notice Initiates the DecentralizedEURO with the provided minimum application period for new plugins\n     * in seconds, for example 10 days, i.e. 3600*24*10 = 864000\n     */\n    constructor(uint256 _minApplicationPeriod) ERC20Permit(\"DecentralizedEURO\") ERC20(\"DecentralizedEURO\", \"dEURO\") {\n        MIN_APPLICATION_PERIOD = _minApplicationPeriod;\n        reserve = new Equity(this);\n    }\n\n    function initialize(address _minter, string calldata _message) external {\n        require(totalSupply() == 0 && reserve.totalSupply() == 0);\n        minters[_minter] = block.timestamp;\n        emit MinterApplied(_minter, 0, 0, _message);\n    }\n\n    /**\n     * @notice Publicly accessible method to suggest a new way of minting DecentralizedEURO.\n     * @dev The caller has to pay an application fee that is irrevocably lost even if the new minter is vetoed.\n     * The caller must assume that someone will veto the new minter unless there is broad consensus that the new minter\n     * adds value to the DecentralizedEURO system. Complex proposals should have application periods and applications fees\n     * above the minimum. It is assumed that over time, informal ways to coordinate on new minters will emerge. The message\n     * parameter might be useful for initiating further communication. Maybe it contains a link to a website describing\n     * the proposed minter.\n     *\n     * @param _minter              An address that is given the permission to mint DecentralizedEUROs\n     * @param _applicationPeriod   The time others have to veto the suggestion, at least MIN_APPLICATION_PERIOD\n     * @param _applicationFee      The fee paid by the caller, at least MIN_FEE\n     * @param _message             An optional human readable message to everyone watching this contract\n     */\n    function suggestMinter(\n        address _minter,\n        uint256 _applicationPeriod,\n        uint256 _applicationFee,\n        string calldata _message\n    ) external override {\n        if (_applicationPeriod < MIN_APPLICATION_PERIOD) revert PeriodTooShort();\n        if (_applicationFee < MIN_FEE) revert FeeTooLow();\n        if (minters[_minter] != 0) revert AlreadyRegistered();\n        _collectProfits(address(this), msg.sender, _applicationFee);\n        minters[_minter] = block.timestamp + _applicationPeriod;\n        emit MinterApplied(_minter, _applicationPeriod, _applicationFee, _message);\n    }\n\n    /**\n     * @notice Make the system more user friendly by skipping the allowance in many cases.\n     * @dev We trust minters and the positions they have created to mint and burn as they please, so\n     * giving them arbitrary allowances does not pose an additional risk.\n     */\n    function allowance(address owner, address spender) public view override(IERC20, ERC20) returns (uint256) {\n        uint256 explicit = super.allowance(owner, spender);\n        if (explicit > 0) {\n            return explicit; // don't waste gas checking minter\n        }\n\n        if (spender == address(reserve)) {\n            return type(uint256).max;\n        }\n\n        if (\n            (isMinter(spender) || isMinter(getPositionParent(spender))) &&\n            (isMinter(owner) || positions[owner] != address(0) || owner == address(reserve))\n        ) {\n            return type(uint256).max;\n        }\n\n        return 0;\n    }\n\n    /**\n     * @notice The reserve provided by the owners of collateralized positions.\n     * @dev The minter reserve can be used to cover losses after the equity holders have been wiped out.\n     */\n    function minterReserve() public view returns (uint256) {\n        return minterReserveE6 / 1_000_000;\n    }\n\n    /**\n     * @notice Allows minters to register collateralized debt positions, thereby giving them the ability to mint DecentralizedEUROs.\n     * @dev It is assumed that the responsible minter that registers the position ensures that the position can be trusted.\n     */\n    function registerPosition(address _position) external override {\n        if (!isMinter(msg.sender)) revert NotMinter();\n        positions[_position] = msg.sender;\n    }\n\n    /**\n     * @notice The amount of equity of the DecentralizedEURO system in dEURO, owned by the holders of Native Decentralized Euro Protocol Shares.\n     * @dev Note that the equity contract technically holds both the minter reserve as well as the equity, so the minter\n     * reserve must be subtracted. All fees and other kinds of income are added to the Equity contract and essentially\n     * constitute profits attributable to the pool shareholders.\n     */\n    function equity() public view returns (uint256) {\n        uint256 balance = balanceOf(address(reserve));\n        uint256 minReserve = minterReserve();\n        if (balance <= minReserve) {\n            return 0;\n        } else {\n            return balance - minReserve;\n        }\n    }\n\n    /**\n     * @notice Qualified pool shareholders can deny minters during the application period.\n     * @dev Calling this function is relatively cheap thanks to the deletion of a storage slot.\n     */\n    function denyMinter(address _minter, address[] calldata _helpers, string calldata _message) external override {\n        if (block.timestamp > minters[_minter]) revert TooLate();\n        reserve.checkQualified(msg.sender, _helpers);\n        delete minters[_minter];\n        emit MinterDenied(_minter, _message);\n    }\n\n    /**\n     * @notice Mints the provided amount of dEURO to the target address, automatically forwarding\n     * the minting fee and the reserve to the right place.\n     */\n    function mintWithReserve(address _target, uint256 _amount, uint32 _reservePPM) external override minterOnly {\n        uint256 usableMint = (_amount * (1_000_000 - _reservePPM)) / 1_000_000; // rounding down is fine\n        _mint(_target, usableMint);\n        _mint(address(reserve), _amount - usableMint); // rest goes to equity as reserves or as fees\n        minterReserveE6 += _amount * _reservePPM;\n    }\n\n    function mint(address _target, uint256 _amount) external override minterOnly {\n        _mint(_target, _amount);\n    }\n\n    /**\n     * Anyone is allowed to burn their dEURO.\n     */\n    function burn(uint256 _amount) external {\n        _burn(msg.sender, _amount);\n    }\n\n    /**\n     * @notice Burn someone else's dEURO.\n     */\n    function burnFrom(address _owner, uint256 _amount) external override minterOnly {\n        _spendAllowance(_owner, msg.sender, _amount);\n        _burn(_owner, _amount);\n    }\n\n    /**\n     * @notice Burn the amount without reclaiming the reserve, but freeing it up and thereby essentially donating it to the\n     * pool shareholders. This can make sense in combination with 'coverLoss', i.e. when it is the pool shareholders\n     * that bear the risk and depending on the outcome they make a profit or a loss.\n     *\n     * Design rule: Minters calling this method are only allowed to do so for token amounts they previously minted with\n     * the same _reservePPM amount.\n     *\n     * For example, if someone minted 50 dEURO earlier with a 20% reserve requirement (200000 ppm), they got 40 dEURO\n     * and paid 10 dEURO into the reserve. Now they want to repay the debt by burning 50 dEURO. When doing so using this\n     * method, 50 dEURO get burned and on top of that, 10 dEURO previously assigned to the minter's reserve are\n     * reassigned to the pool shareholders.\n     */\n    function burnWithoutReserve(uint256 amount, uint32 reservePPM) public override minterOnly {\n        _burn(msg.sender, amount);\n\n        uint256 equityBefore = equity();\n        uint256 reserveReduction = amount * reservePPM;\n        minterReserveE6 = minterReserveE6 > reserveReduction ? minterReserveE6 - reserveReduction : 0;\n        uint256 equityAfter = equity();\n\n        if (equityAfter > equityBefore) {\n            emit Profit(msg.sender, equityAfter - equityBefore);\n        }\n    }\n\n    /**\n     * @notice Burns the target amount taking the tokens to be burned from the payer and the payer's reserve.\n     * Only use this method for tokens also minted by the caller with the same reservePPM.\n     *\n     * Example: the calling contract has previously minted 100 dEURO with a reserve ratio of 20% (i.e. 200000 ppm).\n     * To burn half of that again, the minter calls burnFromWithReserve with a target amount of 50 dEURO. Assuming that reserves\n     * are only 90% covered, this call will deduct 41 dEURO from the payer's balance and 9 from the reserve, while\n     * reducing the minter reserve by 10.\n     */\n    function burnFromWithReserve(\n        address payer,\n        uint256 targetTotalBurnAmount,\n        uint32 reservePPM\n    ) public override minterOnly returns (uint256) {\n        uint256 assigned = calculateAssignedReserve(targetTotalBurnAmount, reservePPM);\n        _spendAllowance(payer, msg.sender, targetTotalBurnAmount - assigned); // spend amount excluding the reserve\n        _burn(address(reserve), assigned); // burn reserve amount from the reserve\n        _burn(payer, targetTotalBurnAmount - assigned); // burn remaining amount from the payer\n        minterReserveE6 -= targetTotalBurnAmount * reservePPM; // reduce reserve requirements by original ratio\n        return assigned;\n    }\n\n    /**\n     * @notice Calculates the assigned reserve for a given amount and reserve requirement, adjusted for reserve losses.\n     * @return `amountExcludingReserve` plus its share of the reserve.\n     */\n    function calculateFreedAmount(uint256 amountExcludingReserve, uint32 _reservePPM) public view returns (uint256) {\n        uint256 effectiveReservePPM = _effectiveReservePPM(_reservePPM);\n        return (1_000_000 * amountExcludingReserve) / (1_000_000 - effectiveReservePPM);\n    }\n\n    /**\n     * @notice Calculates the reserve attributable to someone who minted the given amount with the given reserve requirement.\n     * Under normal circumstances, this is just the reserve requirement multiplied by the amount. However, after a\n     * severe loss of capital that burned into the minter's reserve, this can also be less than that.\n     */\n    function calculateAssignedReserve(uint256 mintedAmount, uint32 _reservePPM) public view returns (uint256) {\n        uint256 effectiveReservePPM = _effectiveReservePPM(_reservePPM);\n        return (effectiveReservePPM * mintedAmount) / 1_000_000;\n    }\n\n    /**\n     * @notice Calculates the reserve ratio adjusted for any reserve shortfall\n     * @dev When there's a reserve shortfall (currentReserve < minterReserve), the effective reserve ratio is proportionally reduced.\n     * This ensures fair distribution of remaining reserves during repayment.\n     * @param reservePPM The nominal reserve ratio in parts per million\n     * @return The effective reserve ratio in parts per million, adjusted for any shortfall\n     */\n    function _effectiveReservePPM(uint32 reservePPM) internal view returns (uint256) {\n        uint256 minterReserve_ = minterReserve();\n        uint256 currentReserve = balanceOf(address(reserve));\n        return currentReserve < minterReserve_ ? (reservePPM * currentReserve) / minterReserve_ : reservePPM;\n    }\n\n    /**\n     * @notice Notify the DecentralizedEURO that a minter lost economic access to some coins. This does not mean that the coins are\n     * literally lost. It just means that some dEURO will likely never be repaid and that in order to bring the system\n     * back into balance, the lost amount of dEURO must be removed from the reserve instead.\n     *\n     * For example, if a minter printed 1 million dEURO for a mortgage and the mortgage turned out to be unsound with\n     * the house only yielding 800,000 in the subsequent auction, there is a loss of 200,000 that needs to be covered\n     * by the reserve.\n     */\n    function coverLoss(address source, uint256 _amount) external override minterOnly {\n        _withdrawFromReserve(source, _amount);\n        emit Loss(source, _amount);\n    }\n\n    /**\n     * @notice Distribute profits (e.g., savings interest) from the reserve to recipients.\n     *\n     * @param recipient The address receiving the payout.\n     * @param amount The amount of dEURO to distribute.\n     */\n    function distributeProfits(address recipient, uint256 amount) external override minterOnly {\n        _withdrawFromReserve(recipient, amount);\n        emit ProfitDistributed(recipient, amount);\n    }\n\n    function collectProfits(address source, uint256 _amount) external override minterOnly {\n        _collectProfits(msg.sender, source, _amount);\n    }\n\n    function _collectProfits(address minter, address source, uint256 _amount) internal {\n        _spendAllowance(source, minter, _amount);\n        _transfer(source, address(reserve), _amount);\n        emit Profit(minter, _amount);\n    }\n\n    /**\n     * @notice Transfers the specified amount from the reserve if possible; mints the remainder if necessary.\n     * @param recipient The address receiving the funds.\n     * @param amount The total amount to be paid.\n     */\n    function _withdrawFromReserve(address recipient, uint256 amount) internal {\n        uint256 reserveLeft = balanceOf(address(reserve));\n        if (reserveLeft >= amount) {\n            _transfer(address(reserve), recipient, amount);\n        } else {\n            _transfer(address(reserve), recipient, reserveLeft);\n            _mint(recipient, amount - reserveLeft);\n        }\n    }\n\n    /**\n     * @notice Returns true if the address is an approved minter.\n     */\n    function isMinter(address _minter) public view override returns (bool) {\n        return minters[_minter] != 0 && block.timestamp >= minters[_minter];\n    }\n\n    /**\n     * @notice Returns the address of the minter that created this position or null if the provided address is unknown.\n     */\n    function getPositionParent(address _position) public view override returns (address) {\n        return positions[_position];\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return\n            interfaceId == type(IERC20).interfaceId ||\n            interfaceId == type(ERC20Permit).interfaceId ||\n            interfaceId == type(ERC3009).interfaceId ||\n            interfaceId == type(IDecentralizedEURO).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/Nonces.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides tracking nonces for addresses. Nonces will only increment.\n */\nabstract contract Nonces {\n    /**\n     * @dev The nonce used for an `account` is not the expected current nonce.\n     */\n    error InvalidAccountNonce(address account, uint256 currentNonce);\n\n    mapping(address account => uint256) private _nonces;\n\n    /**\n     * @dev Returns the next unused nonce for an address.\n     */\n    function nonces(address owner) public view virtual returns (uint256) {\n        return _nonces[owner];\n    }\n\n    /**\n     * @dev Consumes a nonce.\n     *\n     * Returns the current value and increments nonce.\n     */\n    function _useNonce(address owner) internal virtual returns (uint256) {\n        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be\n        // decremented or reset. This guarantees that the nonce never overflows.\n        unchecked {\n            // It is important to do x++ and not ++x here.\n            return _nonces[owner]++;\n        }\n    }\n\n    /**\n     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.\n     */\n    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {\n        uint256 current = _useNonce(owner);\n        if (nonce != current) {\n            revert InvalidAccountNonce(owner, current);\n        }\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/interfaces/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},{"file_path":"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing a bytes32 `messageHash` with\n     * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n     * keccak256, although any bytes32 value can be safely used because the final digest will\n     * be re-hashed.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing an arbitrary `message` with\n     * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n        return\n            keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x00` (data with intended validator).\n     *\n     * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n     * `validator` address. Then hashing the result.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n     *\n     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(ptr, hex\"19_01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            digest := keccak256(ptr, 0x42)\n        }\n    }\n}\n"},{"file_path":"contracts/impl/ERC3009.sol","source_code":"// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\n\nabstract contract ERC3009 is ERC20, EIP712 {\n    bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =\n        keccak256(\n            \"TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)\"\n        );\n\n    bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH =\n        keccak256(\n            \"ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)\"\n        );\n\n    bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH =\n        keccak256(\"CancelAuthorization(address authorizer,bytes32 nonce)\");\n\n    /**\n     * @dev authorizer address => nonce => state (true = used / false = unused)\n     */\n    mapping(address => mapping(bytes32 => bool)) internal _authorizationStates;\n\n    event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);\n    event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce);\n\n    string internal constant _INVALID_SIGNATURE_ERROR = \"EIP3009: invalid signature\";\n    string internal constant _AUTHORIZATION_USED_ERROR = \"EIP3009: authorization is used\";\n\n    /**\n     * @notice Returns the state of an authorization\n     * @dev Nonces are randomly generated 32-byte data unique to the authorizer's\n     * address\n     * @param authorizer    Authorizer's address\n     * @param nonce         Nonce of the authorization\n     * @return True if the nonce is used\n     */\n    function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) {\n        return _authorizationStates[authorizer][nonce];\n    }\n\n    /**\n     * @notice Execute a transfer with a signed authorization\n     * @param from          Payer's address (Authorizer)\n     * @param to            Payee's address\n     * @param value         Amount to be transferred\n     * @param validAfter    The time after which this is valid (unix time)\n     * @param validBefore   The time before which this is valid (unix time)\n     * @param nonce         Unique nonce\n     * @param v             v of the signature\n     * @param r             r of the signature\n     * @param s             s of the signature\n     */\n    function transferWithAuthorization(\n        address from,\n        address to,\n        uint256 value,\n        uint256 validAfter,\n        uint256 validBefore,\n        bytes32 nonce,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external {\n        _transferWithAuthorization(\n            TRANSFER_WITH_AUTHORIZATION_TYPEHASH,\n            from,\n            to,\n            value,\n            validAfter,\n            validBefore,\n            nonce,\n            v,\n            r,\n            s\n        );\n    }\n\n    /**\n     * @notice Receive a transfer with a signed authorization from the payer\n     * @dev This has an additional check to ensure that the payee's address matches\n     * the caller of this function to prevent front-running attacks. (See security\n     * considerations)\n     * @param from          Payer's address (Authorizer)\n     * @param to            Payee's address\n     * @param value         Amount to be transferred\n     * @param validAfter    The time after which this is valid (unix time)\n     * @param validBefore   The time before which this is valid (unix time)\n     * @param nonce         Unique nonce\n     * @param v             v of the signature\n     * @param r             r of the signature\n     * @param s             s of the signature\n     */\n    function receiveWithAuthorization(\n        address from,\n        address to,\n        uint256 value,\n        uint256 validAfter,\n        uint256 validBefore,\n        bytes32 nonce,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external {\n        require(to == msg.sender, \"EIP3009: caller must be the payee\");\n\n        _transferWithAuthorization(\n            RECEIVE_WITH_AUTHORIZATION_TYPEHASH,\n            from,\n            to,\n            value,\n            validAfter,\n            validBefore,\n            nonce,\n            v,\n            r,\n            s\n        );\n    }\n\n    /**\n     * @notice Attempt to cancel an authorization\n     * @param authorizer    Authorizer's address\n     * @param nonce         Nonce of the authorization\n     * @param v             v of the signature\n     * @param r             r of the signature\n     * @param s             s of the signature\n     */\n    function cancelAuthorization(address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external {\n        require(!_authorizationStates[authorizer][nonce], _AUTHORIZATION_USED_ERROR);\n\n        bytes memory data = abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce);\n\n        bytes32 hash = _hashTypedDataV4(keccak256(data));\n        require(ECDSA.recover(hash, v, r, s) == authorizer, _INVALID_SIGNATURE_ERROR);\n\n        _authorizationStates[authorizer][nonce] = true;\n        emit AuthorizationCanceled(authorizer, nonce);\n    }\n\n    function _transferWithAuthorization(\n        bytes32 typeHash,\n        address from,\n        address to,\n        uint256 value,\n        uint256 validAfter,\n        uint256 validBefore,\n        bytes32 nonce,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        require(block.timestamp > validAfter, \"EIP3009: authorization is not yet valid\");\n        require(block.timestamp < validBefore, \"EIP3009: authorization is expired\");\n        require(!_authorizationStates[from][nonce], _AUTHORIZATION_USED_ERROR);\n\n        bytes memory data = abi.encode(typeHash, from, to, value, validAfter, validBefore, nonce);\n\n        bytes32 hash = _hashTypedDataV4(keccak256(data));\n\n        require(ECDSA.recover(hash, v, r, s) == from, _INVALID_SIGNATURE_ERROR);\n\n        _authorizationStates[from][nonce] = true;\n        emit AuthorizationUsed(from, nonce);\n\n        _transfer(from, to, value);\n    }\n}\n"},{"file_path":"@openzeppelin/contracts/utils/math/Math.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\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 subtraction of two unsigned integers, with an success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\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 success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\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 success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\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 success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2²⁵⁶ + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 exp;\n        unchecked {\n            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);\n            value >>= exp;\n            result += exp;\n\n            result += SafeCast.toUint(value > 1);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 isGt;\n        unchecked {\n            isGt = SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= isGt * 128;\n            result += isGt * 16;\n\n            isGt = SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= isGt * 64;\n            result += isGt * 8;\n\n            isGt = SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= isGt * 32;\n            result += isGt * 4;\n\n            isGt = SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= isGt * 16;\n            result += isGt * 2;\n\n            result += SafeCast.toUint(value > (1 << 8) - 1);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},{"file_path":"contracts/interface/IReserve.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IReserve is IERC20 {\n    function invest(uint256 amount, uint256 expected) external returns (uint256);\n    function checkQualified(address sender, address[] calldata helpers) external view;\n}\n"},{"file_path":"@openzeppelin/contracts/access/Ownable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},{"file_path":"contracts/MintingHubV2/PositionRoller.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IDecentralizedEURO} from \"../interface/IDecentralizedEURO.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IMintingHubGateway} from \"../gateway/interface/IMintingHubGateway.sol\";\nimport {IMintingHub} from \"./interface/IMintingHub.sol\";\nimport {IPosition} from \"./interface/IPosition.sol\";\nimport {IReserve} from \"../interface/IReserve.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/**\n * @title PositionRoller\n *\n * Helper to roll over a debt from an old position to a new one.\n * Both positions should have the same collateral. Otherwise, it does not make much sense.\n */\ncontract PositionRoller {\n    IDecentralizedEURO private deuro;\n\n    error NotOwner(address pos);\n    error NotPosition(address pos);\n    error Log(uint256, uint256, uint256);\n\n    event Roll(address source, uint256 collWithdraw, uint256 repay, address target, uint256 collDeposit, uint256 mint);\n\n    constructor(address deuro_) {\n        deuro = IDecentralizedEURO(deuro_);\n    }\n\n    /**\n     * Convenience method to roll an old position into a new one.\n     *\n     * Pre-condition: an allowance for the roller to spend the collateral asset on behalf of the caller,\n     * i.e., one should set collateral.approve(roller, collateral.balanceOf(sourcePosition)).\n     *\n     * The following is assumed:\n     * - If the limit of the target position permits, the user wants to roll everything.\n     * - The user does not want to add additional collateral, but excess collateral is returned.\n     * - If not enough can be minted in the new position, it is acceptable for the roller to use dEURO from the msg.sender.\n     */\n    function rollFully(IPosition source, IPosition target) external {\n        rollFullyWithExpiration(source, target, target.expiration());\n    }\n\n    /**\n     * Like rollFully, but with a custom expiration date for the new position.\n     */\n    function rollFullyWithExpiration(IPosition source, IPosition target, uint40 expiration) public {\n        require(source.collateral() == target.collateral());\n        uint256 principal = source.principal();\n        uint256 interest = source.getInterest();\n        uint256 usableMint = source.getUsableMint(principal) + interest; // Roll interest into principal\n        uint256 mintAmount = target.getMintAmount(usableMint);\n        uint256 collateralToWithdraw = IERC20(source.collateral()).balanceOf(address(source));\n        uint256 targetPrice = target.price();\n        uint256 depositAmount = (mintAmount * 10 ** 18 + targetPrice - 1) / targetPrice; // round up\n        if (depositAmount > collateralToWithdraw) {\n            // If we need more collateral than available from the old position, we opt for taking\n            // the missing funds from the caller instead of requiring additional collateral.\n            depositAmount = collateralToWithdraw;\n            mintAmount = (depositAmount * target.price()) / 10 ** 18; // round down, rest will be taken from caller\n        }\n\n        roll(source, principal + interest, collateralToWithdraw, target, mintAmount, depositAmount, expiration);\n    }\n\n    /**\n     * Rolls the source position into the target position using a flash loan.\n     * Both the source and the target position must recognize this roller.\n     * It is the responsibility of the caller to ensure that both positions are valid contracts.\n     *\n     * @param source The source position, must be owned by the msg.sender.\n     * @param repay The amount of principal to repay from the source position using a flash loan, freeing up some or all collateral .\n     * @param collWithdraw Collateral to move from the source position to the msg.sender.\n     * @param target The target position. If not owned by msg.sender or if it does not have the desired expiration,\n     *               it is cloned to create a position owned by the msg.sender.\n     * @param mint The amount to be minted from the target position using collateral from msg.sender.\n     * @param collDeposit The amount of collateral to be sent from msg.sender to the target position.\n     * @param expiration The desired expiration date for the target position.\n     */\n    function roll(\n        IPosition source,\n        uint256 repay,\n        uint256 collWithdraw,\n        IPosition target,\n        uint256 mint,\n        uint256 collDeposit,\n        uint40 expiration\n    ) public valid(source) valid(target) own(source) {\n        deuro.mint(address(this), repay); // take a flash loan\n        uint256 used = source.repay(repay);\n        source.withdrawCollateral(msg.sender, collWithdraw);\n        if (mint > 0) {\n            IERC20 targetCollateral = IERC20(target.collateral());\n            if (Ownable(address(target)).owner() != msg.sender || expiration != target.expiration()) {\n                targetCollateral.transferFrom(msg.sender, address(this), collDeposit); // get the new collateral\n                targetCollateral.approve(target.hub(), collDeposit); // approve the new collateral and clone:\n                target = _cloneTargetPosition(target, source, collDeposit, mint, expiration);\n            } else {\n                // We can roll into the provided existing position.\n                // We do not verify whether the target position was created by the known minting hub in order\n                // to allow positions to be rolled into future versions of the minting hub.\n                targetCollateral.transferFrom(msg.sender, address(target), collDeposit);\n                target.mint(msg.sender, mint);\n            }\n        }\n\n        // Transfer remaining flash loan to caller for repayment\n        if (repay > used) {\n            deuro.transfer(msg.sender, repay - used);\n        }\n\n        deuro.burnFrom(msg.sender, repay); // repay the flash loan\n        emit Roll(address(source), collWithdraw, repay, address(target), collDeposit, mint);\n    }\n\n    /**\n     * Clones the target position and mints the specified amount using the given collateral.\n     */\n    function _cloneTargetPosition (\n        IPosition target,\n        IPosition source,\n        uint256 collDeposit,\n        uint256 mint,\n        uint40 expiration\n    ) internal returns (IPosition) {\n        if (IERC165(target.hub()).supportsInterface(type(IMintingHubGateway).interfaceId)) {\n            bytes32 frontendCode = IMintingHubGateway(target.hub()).GATEWAY().getPositionFrontendCode(\n                address(source)\n            );\n            return IPosition(\n                IMintingHubGateway(target.hub()).clone(\n                    msg.sender,\n                    address(target),\n                    collDeposit,\n                    mint,\n                    expiration,\n                    frontendCode // use the same frontend code\n                )\n            );\n        } else {\n            return IPosition(\n                IMintingHub(target.hub()).clone(msg.sender, address(target), collDeposit, mint, expiration)\n            );\n        }\n    }\n\n    modifier own(IPosition pos) {\n        if (Ownable(address(pos)).owner() != msg.sender) revert NotOwner(address(pos));\n        _;\n    }\n\n    modifier valid(IPosition pos) {\n        if (deuro.getPositionParent(address(pos)) == address(0x0)) revert NotPosition(address(pos));\n        _;\n    }\n}\n"},{"file_path":"contracts/MintingHubV2/interface/IPosition.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IPosition {\n    function hub() external view returns (address);\n\n    function collateral() external view returns (IERC20);\n\n    function minimumCollateral() external view returns (uint256);\n\n    function price() external view returns (uint256);\n\n    function virtualPrice() external view returns (uint256);\n\n    function challengedAmount() external view returns (uint256);\n\n    function original() external view returns (address);\n\n    function expiration() external view returns (uint40);\n\n    function cooldown() external view returns (uint40);\n\n    function limit() external view returns (uint256);\n\n    function challengePeriod() external view returns (uint40);\n\n    function start() external view returns (uint40);\n\n    function riskPremiumPPM() external view returns (uint24);\n\n    function reserveContribution() external view returns (uint24);\n\n    function principal() external view returns (uint256);\n\n    function interest() external view returns (uint256);\n\n    function lastAccrual() external view returns (uint40);\n\n    function initialize(address parent, uint40 _expiration) external;\n\n    function assertCloneable() external;\n\n    function notifyMint(uint256 mint_) external;\n\n    function notifyRepaid(uint256 repaid_) external;\n\n    function availableForClones() external view returns (uint256);\n\n    function availableForMinting() external view returns (uint256);\n\n    function deny(address[] calldata helpers, string calldata message) external;\n\n    function getUsableMint(uint256 totalMint) external view returns (uint256);\n\n    function getMintAmount(uint256 usableMint) external view returns (uint256);\n\n    function adjust(uint256 newMinted, uint256 newCollateral, uint256 newPrice) external;\n\n    function adjustPrice(uint256 newPrice) external;\n\n    function mint(address target, uint256 amount) external;\n\n    function getDebt() external view returns (uint256);\n\n    function getInterest() external view returns (uint256);\n\n    function repay(uint256 amount) external returns (uint256);\n\n    function repayFull() external returns (uint256);\n\n    function forceSale(address buyer, uint256 colAmount, uint256 proceeds) external;\n\n    function withdraw(address token, address target, uint256 amount) external;\n\n    function withdrawCollateral(address target, uint256 amount) external;\n\n    function transferChallengedCollateral(address target, uint256 amount) external;\n\n    function challengeData() external view returns (uint256 liqPrice, uint40 phase);\n\n    function notifyChallengeStarted(uint256 size, uint256 _price) external;\n\n    function notifyChallengeAverted(uint256 size) external;\n\n    function notifyChallengeSucceeded(\n        uint256 _size\n    ) external returns (address, uint256, uint256, uint256, uint32);\n}\n"},{"file_path":"contracts/gateway/SavingsGateway.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IFrontendGateway} from \"./interface/IFrontendGateway.sol\";\nimport {Context} from \"@openzeppelin/contracts/utils/Context.sol\";\nimport {IDecentralizedEURO} from \"../interface/IDecentralizedEURO.sol\";\nimport {Savings} from \"../Savings.sol\";\n\ncontract SavingsGateway is Savings, Context {\n    IFrontendGateway public immutable GATEWAY;\n\n    constructor(IDecentralizedEURO deuro_, uint24 initialRatePPM, address gateway_) Savings(deuro_, initialRatePPM) {\n        GATEWAY = IFrontendGateway(gateway_);\n    }\n\n    function refresh(address accountOwner) internal override returns (Account storage) {\n        Account storage account = savings[accountOwner];\n        uint64 ticks = currentTicks();\n        if (ticks > account.ticks) {\n            uint192 earnedInterest = calculateInterest(account, ticks);\n            if (earnedInterest > 0) {\n                // collect interest as you go and trigger accounting event\n                (IDecentralizedEURO(address(deuro))).distributeProfits(address(this), earnedInterest);\n                account.saved += earnedInterest;\n                GATEWAY.updateSavingRewards(accountOwner, earnedInterest);\n                emit InterestCollected(accountOwner, earnedInterest);\n            }\n            account.ticks = ticks;\n        }\n        return account;\n    }\n\n    function save(uint192 amount, bytes32 frontendCode) public {\n        save(_msgSender(), amount, frontendCode);\n    }\n\n    function save(address owner, uint192 amount, bytes32 frontendCode) public {\n        GATEWAY.updateSavingCode(_msgSender(), frontendCode);\n        save(owner, amount);\n    }\n\n    function adjust(uint192 targetAmount, bytes32 frontendCode) public {\n        GATEWAY.updateSavingCode(_msgSender(), frontendCode);\n        adjust(targetAmount);\n    }\n\n    function withdraw(address target, uint192 amount, bytes32 frontendCode) public returns (uint256) {\n        GATEWAY.updateSavingCode(_msgSender(), frontendCode);\n        return withdraw(target, amount);\n    }\n}\n"}],"certified":false,"conflicting_implementations":null,"abi":[{"inputs":[{"internalType":"address","name":"deuro_","type":"address"},{"internalType":"address","name":"deps_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EquityTooLow","type":"error"},{"inputs":[],"name":"FrontendCodeAlreadyExists","type":"error"},{"inputs":[],"name":"NoOpenChanges","type":"error"},{"inputs":[{"internalType":"uint256","name":"minmumExecutionTime","type":"uint256"}],"name":"NotDoneWaiting","type":"error"},{"inputs":[],"name":"NotFrontendCodeOwner","type":"error"},{"inputs":[],"name":"NotGatewayService","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ProposedChangesToHigh","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"FrontendCodeRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"FrontendCodeRewardsWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"FrontendCodeTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"InvestRewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"position","type":"address"},{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"NewPositionRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"indexed":false,"internalType":"address","name":"position","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"PositionRewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"who","type":"address"},{"indexed":false,"internalType":"uint24","name":"nextFeeRate","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"nextSavingsFeeRate","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"nextMintingFeeRate","type":"uint24"}],"name":"RateChangesExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"who","type":"address"},{"indexed":false,"internalType":"uint24","name":"nextFeeRate","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"nextSavingsFeeRate","type":"uint24"},{"indexed":false,"internalType":"uint24","name":"nextMintingFeeRate","type":"uint24"},{"indexed":false,"internalType":"uint256","name":"nextChange","type":"uint256"}],"name":"RateChangesProposed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RedeemRewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"indexed":false,"internalType":"address","name":"saver","type":"address"},{"indexed":false,"internalType":"uint256","name":"interest","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"SavingsRewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"UnwrapAndSellRewardAdded","type":"event"},{"inputs":[],"name":"DEPS","outputs":[{"internalType":"contract DEPSWrapper","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEURO","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EQUITY","outputs":[{"internalType":"contract Equity","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINTING_HUB","outputs":[{"internalType":"contract IMintingHubGateway","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SAVINGS","outputs":[{"internalType":"contract SavingsGateway","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"changeTimeLock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executeChanges","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"frontendCodes","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"address","name":"owner","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"position","type":"address"}],"name":"getPositionFrontendCode","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"savings","type":"address"},{"internalType":"address","name":"mintingHub","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expectedShares","type":"uint256"},{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"invest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastUsedFrontendCode","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mintingFeeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextFeeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextMintingFeeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextSavingsFeeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint24","name":"newFeeRatePPM_","type":"uint24"},{"internalType":"uint24","name":"newSavingsFeeRatePPM_","type":"uint24"},{"internalType":"uint24","name":"newMintingFeeRatePPM_","type":"uint24"},{"internalType":"address[]","name":"helpers","type":"address[]"}],"name":"proposeChanges","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"expectedProceeds","type":"uint256"},{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"referredPositions","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"registerFrontendCode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"position","type":"address"},{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"registerPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"savingsFeeRate","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"internalType":"address","name":"to","type":"address"}],"name":"transferFrontendCode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"unwrapAndSell","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"position","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"updatePositionRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"savingsOwner","type":"address"},{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"updateSavingCode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"saver","type":"address"},{"internalType":"uint256","name":"interest","type":"uint256"}],"name":"updateSavingRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"frontendCode","type":"bytes32"}],"name":"withdrawRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"frontendCode","type":"bytes32"},{"internalType":"address","name":"to","type":"address"}],"name":"withdrawRewardsTo","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}],"is_changed_bytecode":false,"is_partially_verified":false,"constructor_args":"0x000000000000000000000000ba3f535bbcccca2a154b573ca6c5a49baae0a3ea000000000000000000000000103747924e74708139a9400e4ab4bea79fffa380"}