Forkchoice Ethereum Mainnet

Address Contract Verified

Address 0x0000000A9FaCf0Be270c02DdfeCabD01CC194698
Balance 0 ETH
Nonce 229
Code Size 13613 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

13613 bytes
0x60806040526004361061017b575f3560e01c80636a7942e3116100d1578063b561fd2b1161007c578063e3933ca611610057578063e3933ca61461057b578063f2fde38b146105a9578063f3fef3a3146105c8575f80fd5b8063b561fd2b14610506578063d714312214610525578063e30c397814610551575f80fd5b80638456cb59116100ac5780638456cb59146104965780638da5cb5b146104aa578063ad5c4648146104d3575f80fd5b80636a7942e31461042d578063715018a61461046e57806379ba509714610482575f80fd5b80633f4ba83a116101315780635c975abb1161010c5780635c975abb1461039d57806366811411146103d857806368012a4614610419575f80fd5b80633f4ba83a1461033757806347e7ef241461034b578063481c6a751461036a575f80fd5b8063222fa47c11610161578063222fa47c146102b857806328b564a0146103105780633969dfb414610318575f80fd5b806302d3dcd6146102655780631507594a14610297575f80fd5b36610261573373ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2161461022a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3130303000000000000000000000000000000000000000000000000000000000604082015260600190565b60405180910390fd5b60405134815233907f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258749060200160405180910390a2005b5f80fd5b348015610270575f80fd5b5061028461027f366004613148565b6105e7565b6040519081526020015b60405180910390f35b3480156102a2575f80fd5b506102b66102b136600461318f565b6107fb565b005b3480156102c3575f80fd5b506102eb7f000000000000000000000000ae30397ec5b0589afcfad7a89148f6dee570627081565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200161028e565b6102b6610b6c565b348015610323575f80fd5b506102b6610332366004613211565b610d96565b348015610342575f80fd5b506102b66111c4565b348015610356575f80fd5b506102b6610365366004613228565b6111de565b348015610375575f80fd5b506102eb7f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522881565b3480156103a8575f80fd5b5060015474010000000000000000000000000000000000000000900460ff165b604051901515815260200161028e565b3480156103e3575f80fd5b506102eb6103f2366004613252565b60036020525f908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b348015610424575f80fd5b506102eb61142f565b348015610438575f80fd5b506102eb610447366004613252565b60046020525f908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b348015610479575f80fd5b506102b661178b565b34801561048d575f80fd5b506102b66117ef565b3480156104a1575f80fd5b506102b6611866565b3480156104b5575f80fd5b505f5473ffffffffffffffffffffffffffffffffffffffff166102eb565b3480156104de575f80fd5b506102eb7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b348015610511575f80fd5b506102b661052036600461326d565b61187e565b348015610530575f80fd5b5061054461053f3660046132a1565b611a70565b60405161028e9190613303565b34801561055c575f80fd5b5060015473ffffffffffffffffffffffffffffffffffffffff166102eb565b348015610586575f80fd5b506103c8610595366004613252565b60056020525f908152604090205460ff1681565b3480156105b4575f80fd5b506102b66105c3366004613252565b611e3f565b3480156105d3575f80fd5b506102b66105e2366004613228565b611eee565b5f6105f061228d565b6105f86122ce565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff16610697576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602052604090205473ffffffffffffffffffffffffffffffffffffffff166106c4612323565b6040517f164fe9e200000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8381166004830152898116602483015260448201899052606482018890528615156084830152919091169063164fe9e29060a4016020604051808303815f875af115801561074f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107739190613345565b92508673ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167feb50244d084c4e6812ac1403e3543a45ea6dfa7431e3a3bb233b3d9d1b37f65a85876040516107df9291909182521515602082015260400190565b60405180910390a350506107f36001600255565b949350505050565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff1661089a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b6108a261228d565b6108aa6122ce565b82610913576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303600000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602052604081205473ffffffffffffffffffffffffffffffffffffffff16905b84811015610b08578585828181106109545761095461335c565b61096a9260206040909202019081019150613252565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167f89eca8e65eea211a8ff18b032e5e6314375995a59f0d2fffeb98116f747081228888858181106109ca576109ca61335c565b90506040020160200135876040516109ee9291909182521515602082015260400190565b60405180910390a36109fe612323565b73ffffffffffffffffffffffffffffffffffffffff166352da17a483888885818110610a2c57610a2c61335c565b610a429260206040909202019081019150613252565b898986818110610a5457610a5461335c565b9050604002016020013588610a695786610a6b565b335b60405160e086901b7fffffffff0000000000000000000000000000000000000000000000000000000016815273ffffffffffffffffffffffffffffffffffffffff94851660048201529284166024840152604483019190915290911660648201526084015f604051808303815f87803b158015610ae6575f80fd5b505af1158015610af8573d5f803e3d5ffd5b50506001909201915061093a9050565b5060408051858152841515602082015273ffffffffffffffffffffffffffffffffffffffff8316917ff5a42771b5bdb1f52cf182e7d48779f55539d7176ff119f282e4bae14141b924910160405180910390a250610b666001600255565b50505050565b6040517fb5af090f00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28181166004840152917f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b052289091169063b5af090f90602401602060405180830381865afa158015610c1a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c3e9190613389565b610ca6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303100000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff16610d45576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b610d4d61228d565b610d556122ce565b610d5d6123b6565b610d88307f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2346124d1565b610d926001600255565b5050565b805f8111610e02576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3230303100000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff16610ea1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b610ea961228d565b610eb16122ce565b335f90815260036020526040908190205490517fbeabacc800000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281166004830152306024830152604482018690529091169063beabacc8906064015f604051808303815f87803b158015610f55575f80fd5b505af1158015610f67573d5f803e3d5ffd5b50505050610f7483612632565b5f80610fa07f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2866126f0565b90925090508015611101575f7f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522873ffffffffffffffffffffffffffffffffffffffff1663412753586040518163ffffffff1660e01b8152600401602060405180830381865afa158015611015573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061103991906133a4565b73ffffffffffffffffffffffffffffffffffffffff16826040515f6040518083038185875af1925050503d805f811461108d576040519150601f19603f3d011682016040523d82523d5f602084013e611092565b606091505b50509050806110ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330313600000000000000000000000000000000000000000000000000000000604082015260600190565b505b6040515f90339084908381818185875af1925050503d805f8114611140576040519150601f19603f3d011682016040523d82523d5f602084013e611145565b606091505b50509050806111b2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330313600000000000000000000000000000000000000000000000000000000604082015260600190565b5050506111bf6001600255565b505050565b6111cc612b43565b6111d4612b95565b6111dc612be9565b565b6040517fb5af090f00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff808416600483015283917f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b052289091169063b5af090f90602401602060405180830381865afa15801561126c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112909190613389565b6112f8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303100000000000000000000000000000000000000000000000000000000604082015260600190565b815f8111611364576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3230303100000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff16611403576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b61140b61228d565b6114136122ce565b61141e3386866124d1565b6114286001600255565b5050505050565b5f61143861228d565b6114406122ce565b335f9081526003602052604090205473ffffffffffffffffffffffffffffffffffffffff16156114ce576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3131303100000000000000000000000000000000000000000000000000000000604082015260600190565b3332146115e9576040517fc057058a0000000000000000000000000000000000000000000000000000000081523360048201527f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522873ffffffffffffffffffffffffffffffffffffffff169063c057058a90602401602060405180830381865afa15801561155d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115819190613389565b6115e9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3130303000000000000000000000000000000000000000000000000000000000604082015260600190565b5f6116137f000000000000000000000000ae30397ec5b0589afcfad7a89148f6dee5706270612c66565b60405190915073ffffffffffffffffffffffffffffffffffffffff82169033907f5c5d14cad51dffb582f1aa3263e5f572c849a67d4c391105eacefeb65ad91b8f905f90a373ffffffffffffffffffffffffffffffffffffffff8181165f81815260056020908152604080832080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00166001179055338084526003835281842080547fffffffffffffffffffffffff000000000000000000000000000000000000000090811687179091558585526004938490529382902080549094161790925590517f19ab453c0000000000000000000000000000000000000000000000000000000081527f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b052289093169083015282916319ab453c906024015f604051808303815f87803b158015611764575f80fd5b505af1158015611776573d5f803e3d5ffd5b50939450505050506117886001600255565b90565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3130303000000000000000000000000000000000000000000000000000000000604082015260600190565b600154339073ffffffffffffffffffffffffffffffffffffffff16811461185a576040517f118cdaa700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff82166004820152602401610221565b61186381612cfb565b50565b61186e612b43565b6118766122ce565b6111dc612d2c565b61188661228d565b61188e6122ce565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff1661192d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b335f908152600360205260409081902054905173ffffffffffffffffffffffffffffffffffffffff9182169186169082907f89eca8e65eea211a8ff18b032e5e6314375995a59f0d2fffeb98116f747081229061199890889088909182521515602082015260400190565b60405180910390a36119a8612323565b73ffffffffffffffffffffffffffffffffffffffff166352da17a4828787876119d157856119d3565b335b60405160e086901b7fffffffff0000000000000000000000000000000000000000000000000000000016815273ffffffffffffffffffffffffffffffffffffffff94851660048201529284166024840152604483019190915290911660648201526084015f604051808303815f87803b158015611a4e575f80fd5b505af1158015611a60573d5f803e3d5ffd5b5050505050506111bf6001600255565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff168084526005909252909120546060919060ff16611b13576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b611b1b61228d565b611b236122ce565b83611b8c576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303600000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602052604081205473ffffffffffffffffffffffffffffffffffffffff16908567ffffffffffffffff811115611bcb57611bcb6133bf565b604051908082528060200260200182016040528015611bf4578160200160208202803683370190505b5090505f5b86811015611dd7575f611c0a612323565b73ffffffffffffffffffffffffffffffffffffffff1663164fe9e2858b8b86818110611c3857611c3861335c565b611c4e9260206060909202019081019150613252565b8c8c87818110611c6057611c6061335c565b905060600201602001358d8d88818110611c7c57611c7c61335c565b604080517fffffffff0000000000000000000000000000000000000000000000000000000060e08a901b16815273ffffffffffffffffffffffffffffffffffffffff978816600482015296909516602487015260448601939093525060609091020101356064820152891515608482015260a4016020604051808303815f875af1158015611d0c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d309190613345565b9050888883818110611d4457611d4461335c565b611d5a9260206060909202019081019150613252565b60408051838152891515602082015273ffffffffffffffffffffffffffffffffffffffff928316928716917feb50244d084c4e6812ac1403e3543a45ea6dfa7431e3a3bb233b3d9d1b37f65a910160405180910390a380838381518110611dc357611dc361335c565b602090810291909101015250600101611bf9565b5060408051878152861515602082015273ffffffffffffffffffffffffffffffffffffffff8416917f2ba1c3f4bf4c86645fa669e63d2dedf458f5a90c8fccb699ad6680cd488beaae910160405180910390a2925050611e376001600255565b509392505050565b611e47612b43565b6001805473ffffffffffffffffffffffffffffffffffffffff83167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155611ea95f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b8173ffffffffffffffffffffffffffffffffffffffff8116611f6e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303000000000000000000000000000000000000000000000000000000000604082015260600190565b815f8111611fda576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3230303100000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602090815260408083205473ffffffffffffffffffffffffffffffffffffffff1680845260059092529091205460ff16612079576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330303200000000000000000000000000000000000000000000000000000000604082015260600190565b61208161228d565b6120896122ce565b335f9081526003602052604081205473ffffffffffffffffffffffffffffffffffffffff1690806120ba88886126f0565b909250905080156121f7578273ffffffffffffffffffffffffffffffffffffffff1663beabacc8897f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522873ffffffffffffffffffffffffffffffffffffffff1663412753586040518163ffffffff1660e01b8152600401602060405180830381865afa15801561214b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061216f91906133a4565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e085901b16815273ffffffffffffffffffffffffffffffffffffffff928316600482015291166024820152604481018490526064015f604051808303815f87803b1580156121e0575f80fd5b505af11580156121f2573d5f803e3d5ffd5b505050505b6040517fbeabacc800000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff89811660048301523360248301526044820184905284169063beabacc8906064015f604051808303815f87803b15801561226a575f80fd5b505af115801561227c573d5f803e3d5ffd5b505050505050506114286001600255565b60028054036122c8576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60028055565b60015474010000000000000000000000000000000000000000900460ff16156111dc576040517fd93c066500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f7f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522873ffffffffffffffffffffffffffffffffffffffff1663f0370a266040518163ffffffff1660e01b8152600401602060405180830381865afa15801561238d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123b191906133a4565b905090565b5f3411612421576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3230303100000000000000000000000000000000000000000000000000000000604082015260600190565b604080513381523460208201527ffbf2fb3a48bb99fe4ffc8b9bae0e71300d16b24ab16500ff3497f9a18d66606c910160405180910390a17f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff1663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b1580156124bf575f80fd5b505af1158015611428573d5f803e3d5ffd5b335f9081526003602090815260409182902054915183815273ffffffffffffffffffffffffffffffffffffffff9283169285169183917f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f62910160405180910390a33073ffffffffffffffffffffffffffffffffffffffff8516036125755761257073ffffffffffffffffffffffffffffffffffffffff84168284612d9b565b612597565b61259773ffffffffffffffffffffffffffffffffffffffff8416858385612e1c565b61259f612323565b6040517f5978103400000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff838116600483015285811660248301526044820185905291909116906359781034906064015f604051808303815f87803b158015612616575f80fd5b505af1158015612628573d5f803e3d5ffd5b5050505050505050565b60408051338152602081018390527f8b8e19118fad33218b73e7619c705bac2fd3d6c6430a63bde486acb1b300bf0b910160405180910390a16040517f2e1a7d4d000000000000000000000000000000000000000000000000000000008152600481018290527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff1690632e1a7d4d906024015f604051808303815f87803b1580156124bf575f80fd5b6040517f620bb58400000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff83811660048301525f9182917f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b05228169063620bb58490602401602060405180830381865afa15801561277e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127a29190613389565b61280a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016102219060208082526004908201527f3330373100000000000000000000000000000000000000000000000000000000604082015260600190565b335f9081526003602052604081205473ffffffffffffffffffffffffffffffffffffffff1690612838612323565b6040517fe7c8294a00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8881166004830152919091169063e7c8294a906024016040805180830381865afa1580156128a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128c791906133ec565b91505073ffffffffffffffffffffffffffffffffffffffff81161580159061297d57506040517fa5fdc5de00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff83811660048301525f919083169063a5fdc5de90602401602060405180830381865afa158015612957573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061297b9190613345565b115b15612a185761298a612323565b6040517fcce19f8100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8481166004830152888116602483015260448201889052919091169063cce19f81906064015f604051808303815f87803b158015612a01575f80fd5b505af1158015612a13573d5f803e3d5ffd5b505050505b5f7f0000000000000000000000000000000e44a948ab0c83f2c65d3a2c4a06b0522873ffffffffffffffffffffffffffffffffffffffff16638bc7e8c46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a82573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aa69190613345565b90505f8115612abc57612ab98783612e62565b90505b8773ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fc2b4a290c20fb28939d29f102514fbffd2b73c059ffba8b78250c94161d5fcc68984604051612b24929190918252602082015260400190565b60405180910390a3612b368188613451565b9890975095505050505050565b5f5473ffffffffffffffffffffffffffffffffffffffff1633146111dc576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401610221565b60015474010000000000000000000000000000000000000000900460ff166111dc576040517f8dfc202b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612bf1612b95565b600180547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff1690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390a1565b5f763d602d80600a3d3981f3363d3d373d3d3d363d730000008260601b60e81c175f526e5af43d82803e903d91602b57fd5bf38260781b17602052603760095ff0905073ffffffffffffffffffffffffffffffffffffffff8116612cf6576040517fc2f868f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b919050565b600180547fffffffffffffffffffffffff000000000000000000000000000000000000000016905561186381612eb5565b612d346122ce565b600180547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612c3c3390565b60405173ffffffffffffffffffffffffffffffffffffffff8381166024830152604482018390526111bf91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050612f29565b60405173ffffffffffffffffffffffffffffffffffffffff8481166024830152838116604483015260648201839052610b669186918216906323b872dd90608401612dd5565b5f612710612e708385613464565b612e7a91906134a8565b15612e86576001612e88565b5f5b60ff16612710612e988486613464565b612ea291906134bb565b612eac91906134ce565b90505b92915050565b5f805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f612f4a73ffffffffffffffffffffffffffffffffffffffff841683612fbd565b905080515f14158015612f6e575080806020019051810190612f6c9190613389565b155b156111bf576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff84166004820152602401610221565b6060612eac83835f845f808573ffffffffffffffffffffffffffffffffffffffff168486604051612fee91906134e1565b5f6040518083038185875af1925050503d805f8114613028576040519150601f19603f3d011682016040523d82523d5f602084013e61302d565b606091505b509150915061303d868383613049565b925050505b9392505050565b60608261305e57613059826130d8565b613042565b8151158015613082575073ffffffffffffffffffffffffffffffffffffffff84163b155b156130d1576040517f9996b31500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85166004820152602401610221565b5080613042565b8051156130e85780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff81168114611863575f80fd5b8015158114611863575f80fd5b5f805f806080858703121561315b575f80fd5b84356131668161311a565b9350602085013592506040850135915060608501356131848161313b565b939692955090935050565b5f805f604084860312156131a1575f80fd5b833567ffffffffffffffff8111156131b7575f80fd5b8401601f810186136131c7575f80fd5b803567ffffffffffffffff8111156131dd575f80fd5b8660208260061b84010111156131f1575f80fd5b6020918201945092508401356132068161313b565b809150509250925092565b5f60208284031215613221575f80fd5b5035919050565b5f8060408385031215613239575f80fd5b82356132448161311a565b946020939093013593505050565b5f60208284031215613262575f80fd5b81356130428161311a565b5f805f6060848603121561327f575f80fd5b833561328a8161311a565b92506020840135915060408401356132068161313b565b5f805f604084860312156132b3575f80fd5b833567ffffffffffffffff8111156132c9575f80fd5b8401601f810186136132d9575f80fd5b803567ffffffffffffffff8111156132ef575f80fd5b8660206060830284010111156131f1575f80fd5b602080825282518282018190525f918401906040840190835b8181101561333a57835183526020938401939092019160010161331c565b509095945050505050565b5f60208284031215613355575f80fd5b5051919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f60208284031215613399575f80fd5b81516130428161313b565b5f602082840312156133b4575f80fd5b81516130428161311a565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b5f80604083850312156133fd575f80fd5b82516134088161313b565b60208401519092506134198161311a565b809150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81810381811115612eaf57612eaf613424565b8082028115828204841417612eaf57612eaf613424565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f826134b6576134b661347b565b500690565b5f826134c9576134c961347b565b500490565b80820180821115612eaf57612eaf613424565b5f82518060208501845e5f92019182525091905056fea264697066735822122073701746de80fe38980081a9b31ad62d2d9c01e6536bdb99a817d9dcc746e77064736f6c634300081a0033

Verified Source Code Full Match

Compiler: v0.8.26+commit.8a97fa7a EVM: cancun Optimization: Yes (100000 runs)
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
Ownable2Step.sol 59 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}
Clones.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev A clone instance deployment failed.
     */
    error ERC1167FailedCreateClone();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}
Initializable.sol 228 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Pausable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
ReentrancyGuard.sol 84 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
Holding.sol 200 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import { OperationsLib } from "./libraries/OperationsLib.sol";

import { IHolding } from "./interfaces/core/IHolding.sol";

import { IHoldingManager } from "./interfaces/core/IHoldingManager.sol";
import { IManager } from "./interfaces/core/IManager.sol";
import { IStrategyManagerMin } from "./interfaces/core/IStrategyManagerMin.sol";
/**
 * @title Holding Contract
 *
 * @notice This contract is designed to manage the holding of tokens and allow operations like transferring tokens,
 * approving spenders, making generic calls, and minting Jigsaw Tokens. It is intended to be cloned and initialized to
 * ensure unique instances with specific managers.
 *
 * @dev This contract inherits functionalities from `ReentrancyGuard` and `Initializable`.
 *
 * @author Hovooo (@hovooo), Cosmin Grigore (@gcosmintech).
 *
 * @custom:security-contact [email protected]
 */

contract Holding is IHolding, Initializable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /**
     * @notice The address of the emergency invoker.
     */
    address public override emergencyInvoker;

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     */
    IManager public override manager;

    // --- Constructor ---

    /**
     * @dev To prevent the implementation contract from being used, the _disableInitializers function is invoked
     * in the constructor to automatically lock it when it is deployed.
     */
    constructor() {
        _disableInitializers();
    }

    // --- Initialization ---

    /**
     * @notice This function initializes the contract (instead of a constructor) to be cloned.
     *
     * @notice Requirements:
     * - The contract must not be already initialized.
     * - `_manager` must not be the zero address.
     *
     * @notice Effects:
     * - Sets `_initialized` to true.
     * - Sets `manager` to the provided `_manager` address.
     *
     * @param _manager Contract that holds all the necessary configs of the protocol.
     */
    function init(
        address _manager
    ) public initializer {
        require(_manager != address(0), "3065");
        manager = IManager(_manager);
    }

    // -- User specific methods --

    /**
     * @notice Sets the emergency invoker address for this holding.
     *
     * @notice Requirements:
     * - The caller must be the owner of this holding.
     *
     * @notice Effects:
     * - Updates the emergency invoker address to the provided value.
     * - Emits an event to track the change for off-chain monitoring.
     *
     * @param _emergencyInvoker The address to set as the emergency invoker.
     */
    function setEmergencyInvoker(
        address _emergencyInvoker
    ) external onlyUser {
        address oldInvoker = emergencyInvoker;
        emergencyInvoker = _emergencyInvoker;
        emit EmergencyInvokerSet(oldInvoker, _emergencyInvoker);
    }

    /**
     * @notice Approves an `_amount` of a specified token to be spent on behalf of the `msg.sender` by `_destination`.
     *
     * @notice Requirements:
     * - The caller must be allowed to make this call.
     *
     * @notice Effects:
     * - Safe approves the `_amount` of `_tokenAddress` to `_destination`.
     *
     * @param _tokenAddress Token user to be spent.
     * @param _destination Destination address of the approval.
     * @param _amount Withdrawal amount.
     */
    function approve(address _tokenAddress, address _destination, uint256 _amount) external override onlyAllowed {
        IERC20(_tokenAddress).forceApprove(_destination, _amount);
    }

    /**
     * @notice Transfers `_token` from the holding contract to `_to` address.
     *
     * @notice Requirements:
     * - The caller must be allowed.
     *
     * @notice Effects:
     * - Safe transfers `_amount` of `_token` to `_to`.
     *
     * @param _token Token address.
     * @param _to Address to move token to.
     * @param _amount Transfer amount.
     */
    function transfer(address _token, address _to, uint256 _amount) external override nonReentrant onlyAllowed {
        IERC20(_token).safeTransfer({ to: _to, value: _amount });
    }

    /**
     * @notice Executes generic call on the `contract`.
     *
     * @notice Requirements:
     * - The caller must be allowed.
     *
     * @notice Effects:
     * - Makes a low-level call to the `_contract` with the provided `_call` data.
     *
     * @param _contract The contract address for which the call will be invoked.
     * @param _call Abi.encodeWithSignature data for the call.
     *
     * @return success Indicates if the call was successful.
     * @return result The result returned by the call.
     */
    function genericCall(
        address _contract,
        bytes calldata _call
    ) external payable override nonReentrant onlyAllowed returns (bool success, bytes memory result) {
        (success, result) = _contract.call{ value: msg.value }(_call);
    }

    /**
     * @notice Executes an emergency generic call on the specified contract.
     *
     * @notice Requirements:
     * - The caller must be the designated emergency invoker.
     * - The emergency invoker must be an allowed invoker in the Manager contract.
     * - Protected by nonReentrant modifier to prevent reentrancy attacks.
     *
     * @notice Effects:
     * - Makes a low-level call to the `_contract` with the provided `_call` data.
     * - Forwards any ETH value sent with the transaction.
     *
     * @param _contract The contract address for which the call will be invoked.
     * @param _call Abi.encodeWithSignature data for the call.
     *
     * @return success Indicates if the call was successful.
     * @return result The result returned by the call.
     */
    function emergencyGenericCall(
        address _contract,
        bytes calldata _call
    ) external payable onlyEmergencyInvoker nonReentrant returns (bool success, bytes memory result) {
        (success, result) = _contract.call{ value: msg.value }(_call);
    }

    // -- Modifiers

    modifier onlyAllowed() {
        (,, bool isStrategyWhitelisted) = IStrategyManagerMin(manager.strategyManager()).strategyInfo(msg.sender);

        require(
            msg.sender == manager.holdingManager() || msg.sender == manager.liquidationManager()
                || msg.sender == manager.swapManager() || isStrategyWhitelisted,
            "1000"
        );
        _;
    }

    modifier onlyUser() {
        require(msg.sender == IHoldingManager(manager.holdingManager()).holdingUser(address(this)), "1000");
        _;
    }

    modifier onlyEmergencyInvoker() {
        require(msg.sender == emergencyInvoker && manager.allowedInvokers(msg.sender), "1000");
        _;
    }
}
HoldingManager.sol 614 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import { Holding } from "./Holding.sol";
import { OperationsLib } from "./libraries/OperationsLib.sol";

import { IWETH } from "./interfaces/IWETH.sol";
import { IHolding } from "./interfaces/core/IHolding.sol";
import { IHoldingManager } from "./interfaces/core/IHoldingManager.sol";
import { IManager } from "./interfaces/core/IManager.sol";

import { ISharesRegistry } from "./interfaces/core/ISharesRegistry.sol";
import { IStablesManager } from "./interfaces/core/IStablesManager.sol";

/**
 * @title HoldingManager
 *
 * @notice Manages holding creation, management, and interaction for a more secure and dynamic flow.
 *
 * @dev This contract inherits functionalities from `Ownable2Step`, `Pausable`, and `ReentrancyGuard`.
 *
 * @author Hovooo (@hovooo), Cosmin Grigore (@gcosmintech).
 *
 * @custom:security-contact [email protected]
 */
contract HoldingManager is IHoldingManager, Ownable2Step, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /**
     * @notice Returns holding address associated with the user.
     */
    mapping(address user => address holding) public override userHolding;

    /**
     * @notice Returns user address associated with the holding.
     */
    mapping(address holding => address user) public override holdingUser;

    /**
     * @notice Returns true if provided address is a holding within protocol.
     */
    mapping(address holding => bool exists) public override isHolding;

    /**
     * @notice Returns the address of the holding implementation to be cloned from.
     */
    address public immutable override holdingImplementationReference;

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     */
    IManager public immutable override manager;

    /**
     * @notice Returns the address of the WETH contract to save on `manager.WETH()` calls.
     */
    address public immutable override WETH;

    /**
     * @notice Creates a new HoldingManager Contract.
     * @param _initialOwner The initial owner of the contract
     * @param _manager Contract that holds all the necessary configs of the protocol.
     */
    constructor(address _initialOwner, address _manager) Ownable(_initialOwner) {
        require(_manager != address(0), "3065");
        manager = IManager(_manager);
        holdingImplementationReference = address(new Holding());
        WETH = manager.WETH();
    }

    // -- User specific methods --

    /**
     * @notice Creates holding for the msg.sender.
     *
     * @notice Requirements:
     * - `msg.sender` must not have a holding within the protocol, as only one holding is allowed per address.
     * - Must be called from an EOA or whitelisted contract.
     *
     * @notice Effects:
     * - Clones `holdingImplementationReference`.
     * - Updates `userHolding` and `holdingUser` mappings with newly deployed `newHoldingAddress`.
     * - Initiates the `newHolding`.
     *
     * @notice Emits:
     * - `HoldingCreated` event indicating successful Holding creation.
     *
     * @return The address of the new holding.
     */
    function createHolding() external override nonReentrant whenNotPaused returns (address) {
        require(userHolding[msg.sender] == address(0), "1101");

        if (msg.sender != tx.origin) {
            require(manager.isContractWhitelisted(msg.sender), "1000");
        }

        // Instead of deploying the contract, it is cloned to save on gas.
        address newHoldingAddress = Clones.clone(holdingImplementationReference);
        emit HoldingCreated({ user: msg.sender, holdingAddress: newHoldingAddress });

        isHolding[newHoldingAddress] = true;
        userHolding[msg.sender] = newHoldingAddress;
        holdingUser[newHoldingAddress] = msg.sender;

        Holding newHolding = Holding(newHoldingAddress);
        newHolding.init(address(manager));

        return newHoldingAddress;
    }

    /**
     * @notice Deposits a whitelisted token into the Holding.
     *
     * @notice Requirements:
     * - `_token` must be a whitelisted token.
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     *
     * @param _token Token's address.
     * @param _amount Amount to deposit.
     */
    function deposit(
        address _token,
        uint256 _amount
    )
        external
        override
        validToken(_token)
        validAmount(_amount)
        validHolding(userHolding[msg.sender])
        nonReentrant
        whenNotPaused
    {
        _deposit({ _from: msg.sender, _token: _token, _amount: _amount });
    }

    /**
     * @notice Wraps native coin and deposits WETH into the holding.
     *
     * @dev This function must receive ETH in the transaction.
     *
     * @notice Requirements:
     *  - WETH must be whitelisted within protocol.
     * - `msg.sender` must have a valid holding.
     */
    function wrapAndDeposit()
        external
        payable
        override
        validToken(WETH)
        validHolding(userHolding[msg.sender])
        nonReentrant
        whenNotPaused
    {
        _wrap();
        _deposit({ _from: address(this), _token: WETH, _amount: msg.value });
    }

    /**
     * @notice Withdraws a token from a Holding to a user.
     *
     * @notice Requirements:
     * - `_token` must be a valid address.
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Withdraws the `_amount` of `_token` from the holding.
     * - Transfers the `_amount` of `_token` to `msg.sender`.
     * - Deducts any applicable fees.
     *
     * @param _token Token user wants to withdraw.
     * @param _amount Withdrawal amount.
     */
    function withdraw(
        address _token,
        uint256 _amount
    )
        external
        override
        validAddress(_token)
        validAmount(_amount)
        validHolding(userHolding[msg.sender])
        nonReentrant
        whenNotPaused
    {
        IHolding holding = IHolding(userHolding[msg.sender]);
        (uint256 userAmount, uint256 feeAmount) = _withdraw({ _token: _token, _amount: _amount });

        // Transfer the fee amount to the fee address.
        if (feeAmount > 0) {
            holding.transfer({ _token: _token, _to: manager.feeAddress(), _amount: feeAmount });
        }

        // Transfer the remaining amount to the user.
        holding.transfer({ _token: _token, _to: msg.sender, _amount: userAmount });
    }

    /**
     * @notice Withdraws WETH from holding and unwraps it before sending it to the user.
     *
     * @notice Requirements:
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     * - The low level native coin transfers must succeed.
     *
     * @notice Effects
     * - Transfers WETH from Holding address to address(this).
     * - Unwraps the WETH into native coin.
     * - Withdraws the `_amount` of WETH from the holding.
     * - Deducts any applicable fees.
     * - Transfers the unwrapped amount to `msg.sender`.
     *
     * @param _amount Withdrawal amount.
     */
    function withdrawAndUnwrap(
        uint256 _amount
    ) external override validAmount(_amount) validHolding(userHolding[msg.sender]) nonReentrant whenNotPaused {
        IHolding(userHolding[msg.sender]).transfer({ _token: WETH, _to: address(this), _amount: _amount });
        _unwrap(_amount);
        (uint256 userAmount, uint256 feeAmount) = _withdraw({ _token: WETH, _amount: _amount });

        if (feeAmount > 0) {
            (bool feeSuccess,) = payable(manager.feeAddress()).call{ value: feeAmount }("");
            require(feeSuccess, "3016");
        }

        (bool success,) = payable(msg.sender).call{ value: userAmount }("");
        require(success, "3016");
    }

    /**
     * @notice Borrows jUSD stablecoin to the user or to the holding contract.
     *
     * @dev The _amount does not account for the collateralization ratio and is meant to represent collateral's amount
     * equivalent to jUSD's value the user wants to receive.
     * @dev Ensure that the user will not become insolvent after borrowing before calling this function, as this
     * function will revert ("3009") if the supplied `_amount` does not adhere to the collateralization ratio set in
     * the registry for the specific collateral.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Calls borrow function on `Stables Manager` Contract resulting in minting stablecoin based on the `_amount` of
     * `_token` collateral.
     *
     * @notice Emits:
     * - `Borrowed` event indicating successful borrow operation.
     *
     * @param _token Collateral token.
     * @param _amount The collateral amount equivalent for borrowed jUSD.
     * @param _mintDirectlyToUser If true, mints to user instead of holding.
     * @param _minJUsdAmountOut The minimum amount of jUSD that is expected to be received.
     *
     * @return jUsdMinted The amount of jUSD minted.
     */
    function borrow(
        address _token,
        uint256 _amount,
        uint256 _minJUsdAmountOut,
        bool _mintDirectlyToUser
    ) external override nonReentrant whenNotPaused validHolding(userHolding[msg.sender]) returns (uint256 jUsdMinted) {
        address holding = userHolding[msg.sender];

        jUsdMinted = _getStablesManager().borrow({
            _holding: holding,
            _token: _token,
            _amount: _amount,
            _minJUsdAmountOut: _minJUsdAmountOut,
            _mintDirectlyToUser: _mintDirectlyToUser
        });

        emit Borrowed({ holding: holding, token: _token, jUsdMinted: jUsdMinted, mintToUser: _mintDirectlyToUser });
    }

    /**
     * @notice Borrows jUSD stablecoin to the user or to the holding contract using multiple collaterals.
     *
     * @dev This function will fail if any `amount` supplied in the `_data` does not adhere to the collateralization
     * ratio set in the registry for the specific collateral. For instance, if the collateralization ratio is 200%, the
     * maximum `_amount` that can be used to borrow is half of the user's free collateral, otherwise the user's holding
     * will become insolvent after borrowing.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     * - `_data` must contain at least one entry.
     *
     * @notice Effects:
     * - Mints jUSD stablecoin for each entry in `_data` based on the collateral amounts.
     *
     * @notice Emits:
     * - `Borrowed` event for each entry indicating successful borrow operation.
     * - `BorrowedMultiple` event indicating successful multiple borrow operation.
     *
     * @param _data Struct containing data for each collateral type.
     * @param _mintDirectlyToUser If true, mints to user instead of holding.
     *
     * @return  The amount of jUSD minted for each collateral type.
     */
    function borrowMultiple(
        BorrowData[] calldata _data,
        bool _mintDirectlyToUser
    ) external override validHolding(userHolding[msg.sender]) nonReentrant whenNotPaused returns (uint256[] memory) {
        require(_data.length > 0, "3006");

        address holding = userHolding[msg.sender];

        uint256[] memory jUsdMintedAmounts = new uint256[](_data.length);
        for (uint256 i = 0; i < _data.length; i++) {
            uint256 jUsdMinted = _getStablesManager().borrow({
                _holding: holding,
                _token: _data[i].token,
                _amount: _data[i].amount,
                _minJUsdAmountOut: _data[i].minJUsdAmountOut,
                _mintDirectlyToUser: _mintDirectlyToUser
            });

            emit Borrowed({
                holding: holding,
                token: _data[i].token,
                jUsdMinted: jUsdMinted,
                mintToUser: _mintDirectlyToUser
            });

            jUsdMintedAmounts[i] = jUsdMinted;
        }

        emit BorrowedMultiple({ holding: holding, length: _data.length, mintedToUser: _mintDirectlyToUser });
        return jUsdMintedAmounts;
    }

    /**
     * @notice Repays jUSD stablecoin debt from the user's or to the holding's address and frees up the locked
     * collateral.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Repays `_amount` jUSD stablecoin.
     *
     * @notice Emits:
     * - `Repaid` event indicating successful debt repayment operation.
     *
     * @param _token Collateral token.
     * @param _amount The repaid amount.
     * @param _repayFromUser If true, Stables Manager will burn jUSD from the msg.sender, otherwise user's holding.
     */
    function repay(
        address _token,
        uint256 _amount,
        bool _repayFromUser
    ) external override nonReentrant whenNotPaused validHolding(userHolding[msg.sender]) {
        address holding = userHolding[msg.sender];

        emit Repaid({ holding: holding, token: _token, amount: _amount, repayFromUser: _repayFromUser });
        _getStablesManager().repay({
            _holding: holding,
            _token: _token,
            _amount: _amount,
            _burnFrom: _repayFromUser ? msg.sender : holding
        });
    }

    /**
     * @notice Repays multiple jUSD stablecoin debts from the user's or to the holding's address and frees up the locked
     * collateral assets.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     * - `_data` must contain at least one entry.
     *
     * @notice Effects:
     * - Repays stablecoin for each entry in `_data.
     *
     * @notice Emits:
     * - `Repaid` event indicating successful debt repayment operation.
     * - `RepaidMultiple` event indicating successful multiple repayment operation.
     *
     * @param _data Struct containing data for each collateral type.
     * @param _repayFromUser If true, it will burn from user's wallet, otherwise from user's holding.
     */
    function repayMultiple(
        RepayData[] calldata _data,
        bool _repayFromUser
    ) external override validHolding(userHolding[msg.sender]) nonReentrant whenNotPaused {
        require(_data.length > 0, "3006");

        address holding = userHolding[msg.sender];
        for (uint256 i = 0; i < _data.length; i++) {
            emit Repaid({
                holding: holding,
                token: _data[i].token,
                amount: _data[i].amount,
                repayFromUser: _repayFromUser
            });
            _getStablesManager().repay({
                _holding: holding,
                _token: _data[i].token,
                _amount: _data[i].amount,
                _burnFrom: _repayFromUser ? msg.sender : holding
            });
        }

        emit RepaidMultiple({ holding: holding, length: _data.length, repaidFromUser: _repayFromUser });
    }

    /**
     * @notice Allows the contract to accept incoming Ether transfers.
     * @dev This function is executed when the contract receives Ether with no data in the transaction.
     * @dev Only allows transfers from the WETH contract.
     *
     * @notice Emits:
     * - `Received` event to log the sender's address and the amount received.
     */
    receive() external payable {
        require(msg.sender == WETH, "1000");
        emit Received({ from: msg.sender, amount: msg.value });
    }

    // -- Administration --

    /**
     * @notice Triggers stopped state.
     */
    function pause() external override onlyOwner whenNotPaused {
        _pause();
    }

    /**
     * @notice Returns to normal state.
     */
    function unpause() external override onlyOwner whenPaused {
        _unpause();
    }

    /**
     * @dev Renounce ownership override to avoid losing contract's ownership.
     */
    function renounceOwnership() public pure override {
        revert("1000");
    }

    // -- Private methods --

    /**
     * @notice Returns the stables manager contract.
     * @return The IStablesManager instance.
     */
    function _getStablesManager() private view returns (IStablesManager) {
        return IStablesManager(manager.stablesManager());
    }

    /**
     * @notice Wraps native coin.
     *
     * @notice Requirements:
     * - The transaction must include ETH.
     * - The amount of ETH sent must be greater than zero.
     *
     * @notice Effects:
     * - Converts the sent ETH to WETH.
     *
     * @notice Emits:
     * - `NativeCoinWrapped` event indicating successful native coin's wrapping.
     */
    function _wrap() private {
        require(msg.value > 0, "2001");
        emit NativeCoinWrapped({ user: msg.sender, amount: msg.value });
        IWETH(WETH).deposit{ value: msg.value }();
    }

    /**
     * @notice Unwraps WETH.
     *
     * @notice Requirements:
     * - The contract must have enough WETH to unwrap the specified amount.
     *
     * @notice Effects:
     * - Converts the specified amount of WETH to ETH.
     *
     * @notice Emits:
     * - `NativeCoinUnwrapped` event indicating successful WETH's  unwrapping.
     *
     * @param _amount The amount of WETH to unwrap.
     */
    function _unwrap(
        uint256 _amount
    ) private {
        emit NativeCoinUnwrapped({ user: msg.sender, amount: _amount });
        IWETH(WETH).withdraw(_amount);
    }

    /**
     * @notice Deposits a specified amount of a token into the holding.
     *
     * @notice Requirements:
     * - `_from` must have approved the contract to spend `_amount` of `_token`.
     *
     * @notice Effects:
     * - Transfers `_amount` of `_token` from `_from` to the holding.
     * - Adds `_amount` of `_token` to the collateral in the Stables Manager Contract.
     *
     * @notice Emits:
     * - `Deposit` event indicating successful deposit operation.
     *
     * @param _from The address from which the token is transferred.
     * @param _token The token address.
     * @param _amount The amount to deposit.
     */
    function _deposit(address _from, address _token, uint256 _amount) private {
        address holding = userHolding[msg.sender];

        emit Deposit(holding, _token, _amount);
        if (_from == address(this)) {
            IERC20(_token).safeTransfer({ to: holding, value: _amount });
        } else {
            IERC20(_token).safeTransferFrom({ from: _from, to: holding, value: _amount });
        }

        _getStablesManager().addCollateral({ _holding: holding, _token: _token, _amount: _amount });
    }

    /**
     * @notice Withdraws a specified amount of a token from the holding.
     *
     * @notice Requirements:
     * - The `_token` must be withdrawable.
     * -The holding must remain solvent after withdrawal if the `_token` is used as a collateral.
     *
     * @notice Effects:
     * - Removes `_amount` of `_token` from the collateral in the Stables Manager Contract if the `_token` is used as a
     * collateral.
     * - Calculates any applicable withdrawal fee.
     * @notice Emits:
     * - `Withdrawal` event indicating successful withdrawal operation.
     *
     * @param _token The token address.
     * @param _amount The amount to withdraw.
     *
     * @return The available amount to be withdrawn and the withdrawal fee amount.
     */
    function _withdraw(address _token, uint256 _amount) private returns (uint256, uint256) {
        require(manager.isTokenWithdrawable(_token), "3071");
        address holding = userHolding[msg.sender];

        // Perform the check to see if this is an airdropped token or user actually has collateral for it
        (, address _tokenRegistry) = _getStablesManager().shareRegistryInfo(_token);
        if (_tokenRegistry != address(0) && ISharesRegistry(_tokenRegistry).collateral(holding) > 0) {
            _getStablesManager().removeCollateral({ _holding: holding, _token: _token, _amount: _amount });
        }
        uint256 withdrawalFee = manager.withdrawalFee();
        uint256 withdrawalFeeAmount = 0;
        if (withdrawalFee > 0) withdrawalFeeAmount = OperationsLib.getFeeAbsolute(_amount, withdrawalFee);
        emit Withdrawal({ holding: holding, token: _token, totalAmount: _amount, feeAmount: withdrawalFeeAmount });

        return (_amount - withdrawalFeeAmount, withdrawalFeeAmount);
    }

    // -- Modifiers --

    /**
     * @notice Validates that the address is not zero.
     * @param _address The address to validate.
     */
    modifier validAddress(
        address _address
    ) {
        require(_address != address(0), "3000");
        _;
    }

    /**
     * @notice Validates that the holding exists.
     * @param _holding The address of the holding.
     */
    modifier validHolding(
        address _holding
    ) {
        require(isHolding[_holding], "3002");
        _;
    }

    /**
     * @notice Validates that the amount is greater than zero.
     * @param _amount The amount to validate.
     */
    modifier validAmount(
        uint256 _amount
    ) {
        require(_amount > 0, "2001");
        _;
    }

    /**
     * @notice Validates that the token is whitelisted.
     * @param _token The address of the token.
     */
    modifier validToken(
        address _token
    ) {
        require(manager.isTokenWhitelisted(_token), "3001");
        _;
    }
}
IWETH.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IWETH {
    function deposit() external payable;

    function withdraw(
        uint256
    ) external;
}
IHolding.sol 121 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IManager } from "./IManager.sol";

/**
 * @title IHolding
 * @dev Interface for the Holding Contract.
 */
interface IHolding {
    // -- Events --

    /**
     * @notice Emitted when the emergency invoker is set.
     */
    event EmergencyInvokerSet(address indexed oldInvoker, address indexed newInvoker);

    // -- State variables --

    /**
     * @notice Returns the emergency invoker address.
     * @return The address of the emergency invoker.
     */
    function emergencyInvoker() external view returns (address);

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     */
    function manager() external view returns (IManager);

    // -- User specific methods --

    /**
     * @notice Sets the emergency invoker address for this holding.
     *
     * @notice Requirements:
     * - The caller must be the owner of this holding.
     *
     * @notice Effects:
     * - Updates the emergency invoker address to the provided value.
     * - Emits an event to track the change for off-chain monitoring.
     *
     * @param _emergencyInvoker The address to set as the emergency invoker.
     */
    function setEmergencyInvoker(
        address _emergencyInvoker
    ) external;

    /**
     * @notice Approves an `_amount` of a specified token to be spent on behalf of the `msg.sender` by `_destination`.
     *
     * @notice Requirements:
     * - The caller must be allowed to make this call.
     *
     * @notice Effects:
     * - Safe approves the `_amount` of `_tokenAddress` to `_destination`.
     *
     * @param _tokenAddress Token user to be spent.
     * @param _destination Destination address of the approval.
     * @param _amount Withdrawal amount.
     */
    function approve(address _tokenAddress, address _destination, uint256 _amount) external;

    /**
     * @notice Transfers `_token` from the holding contract to `_to` address.
     *
     * @notice Requirements:
     * - The caller must be allowed.
     *
     * @notice Effects:
     * - Safe transfers `_amount` of `_token` to `_to`.
     *
     * @param _token Token address.
     * @param _to Address to move token to.
     * @param _amount Transfer amount.
     */
    function transfer(address _token, address _to, uint256 _amount) external;

    /**
     * @notice Executes generic call on the `contract`.
     *
     * @notice Requirements:
     * - The caller must be allowed.
     *
     * @notice Effects:
     * - Makes a low-level call to the `_contract` with the provided `_call` data.
     *
     * @param _contract The contract address for which the call will be invoked.
     * @param _call Abi.encodeWithSignature data for the call.
     *
     * @return success Indicates if the call was successful.
     * @return result The result returned by the call.
     */
    function genericCall(
        address _contract,
        bytes calldata _call
    ) external payable returns (bool success, bytes memory result);

    /**
     * @notice Executes an emergency generic call on the specified contract.
     *
     * @notice Requirements:
     * - The caller must be the designated emergency invoker.
     * - The emergency invoker must be an allowed invoker in the Manager contract.
     * - Protected by nonReentrant modifier to prevent reentrancy attacks.
     *
     * @notice Effects:
     * - Makes a low-level call to the `_contract` with the provided `_call` data.
     * - Forwards any ETH value sent with the transaction.
     *
     * @param _contract The contract address for which the call will be invoked.
     * @param _call Abi.encodeWithSignature data for the call.
     *
     * @return success Indicates if the call was successful.
     * @return result The result returned by the call.
     */
    function emergencyGenericCall(
        address _contract,
        bytes calldata _call
    ) external payable returns (bool success, bytes memory result);
}
IHoldingManager.sol 354 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IManager } from "./IManager.sol";

/**
 * @title IHoldingManager
 * @notice Interface for the Holding Manager.
 */
interface IHoldingManager {
    // -- Custom types --

    /**
     * @notice Data used for multiple borrow.
     */
    struct BorrowData {
        address token;
        uint256 amount;
        uint256 minJUsdAmountOut;
    }

    /**
     * @notice Data used for multiple repay.
     */
    struct RepayData {
        address token;
        uint256 amount;
    }

    // -- Events --

    /**
     * @notice Emitted when a new Holding is created.
     * @param user The address of the user.
     * @param holdingAddress The address of the created holding.
     */
    event HoldingCreated(address indexed user, address indexed holdingAddress);

    /**
     * @notice Emitted when a deposit is made.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param amount The amount deposited.
     */
    event Deposit(address indexed holding, address indexed token, uint256 amount);

    /**
     * @notice Emitted when a borrow action is performed.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param jUsdMinted The amount of jUSD minted.
     * @param mintToUser Indicates if the amount is minted directly to the user.
     */
    event Borrowed(address indexed holding, address indexed token, uint256 jUsdMinted, bool mintToUser);

    /**
     * @notice Emitted when a borrow event happens using multiple collateral types.
     * @param holding The address of the holding.
     * @param length The number of borrow operations.
     * @param mintedToUser Indicates if the amounts are minted directly to the users.
     */
    event BorrowedMultiple(address indexed holding, uint256 length, bool mintedToUser);

    /**
     * @notice Emitted when a repay action is performed.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param amount The amount repaid.
     * @param repayFromUser Indicates if the repayment is from the user's wallet.
     */
    event Repaid(address indexed holding, address indexed token, uint256 amount, bool repayFromUser);

    /**
     * @notice Emitted when a multiple repay operation happens.
     * @param holding The address of the holding.
     * @param length The number of repay operations.
     * @param repaidFromUser Indicates if the repayments are from the users' wallets.
     */
    event RepaidMultiple(address indexed holding, uint256 length, bool repaidFromUser);

    /**
     * @notice Emitted when the user wraps native coin.
     * @param user The address of the user.
     * @param amount The amount wrapped.
     */
    event NativeCoinWrapped(address user, uint256 amount);

    /**
     * @notice Emitted when the user unwraps into native coin.
     * @param user The address of the user.
     * @param amount The amount unwrapped.
     */
    event NativeCoinUnwrapped(address user, uint256 amount);

    /**
     * @notice Emitted when tokens are withdrawn from the holding.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param totalAmount The total amount withdrawn.
     * @param feeAmount The fee amount.
     */
    event Withdrawal(address indexed holding, address indexed token, uint256 totalAmount, uint256 feeAmount);

    /**
     * @notice Emitted when the contract receives ETH.
     * @param from The address of the sender.
     * @param amount The amount received.
     */
    event Received(address indexed from, uint256 amount);

    // -- State variables --

    /**
     * @notice Returns the holding for a user.
     * @param _user The address of the user.
     * @return The address of the holding.
     */
    function userHolding(
        address _user
    ) external view returns (address);

    /**
     * @notice Returns the user for a holding.
     * @param holding The address of the holding.
     * @return The address of the user.
     */
    function holdingUser(
        address holding
    ) external view returns (address);

    /**
     * @notice Returns true if the holding was created.
     * @param _holding The address of the holding.
     * @return True if the holding was created, false otherwise.
     */
    function isHolding(
        address _holding
    ) external view returns (bool);

    /**
     * @notice Returns the address of the holding implementation to be cloned from.
     * @return The address of the current holding implementation.
     */
    function holdingImplementationReference() external view returns (address);

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     * @return The manager contract.
     */
    function manager() external view returns (IManager);

    /**
     * @notice Returns the address of the WETH contract to save on `manager.WETH()` calls.
     * @return The address of the WETH contract.
     */
    function WETH() external view returns (address);

    // -- User specific methods --

    /**
     * @notice Creates holding for the msg.sender.
     *
     * @notice Requirements:
     * - `msg.sender` must not have a holding within the protocol, as only one holding is allowed per address.
     * - Must be called from an EOA or whitelisted contract.
     *
     * @notice Effects:
     * - Clones `holdingImplementationReference`.
     * - Updates `userHolding` and `holdingUser` mappings with newly deployed `newHoldingAddress`.
     * - Initiates the `newHolding`.
     *
     * @notice Emits:
     * - `HoldingCreated` event indicating successful Holding creation.
     *
     * @return The address of the new holding.
     */
    function createHolding() external returns (address);

    /**
     * @notice Deposits a whitelisted token into the Holding.
     *
     * @notice Requirements:
     * - `_token` must be a whitelisted token.
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     *
     * @param _token Token's address.
     * @param _amount Amount to deposit.
     */
    function deposit(address _token, uint256 _amount) external;

    /**
     * @notice Wraps native coin and deposits WETH into the holding.
     *
     * @dev This function must receive ETH in the transaction.
     *
     * @notice Requirements:
     *  - WETH must be whitelisted within protocol.
     * - `msg.sender` must have a valid holding.
     */
    function wrapAndDeposit() external payable;

    /**
     * @notice Withdraws a token from a Holding to a user.
     *
     * @notice Requirements:
     * - `_token` must be a valid address.
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Withdraws the `_amount` of `_token` from the holding.
     * - Transfers the `_amount` of `_token` to `msg.sender`.
     * - Deducts any applicable fees.
     *
     * @param _token Token user wants to withdraw.
     * @param _amount Withdrawal amount.
     */
    function withdraw(address _token, uint256 _amount) external;

    /**
     * @notice Withdraws WETH from holding and unwraps it before sending it to the user.
     *
     * @notice Requirements:
     * - `_amount` must be greater than zero.
     * - `msg.sender` must have a valid holding.
     * - The low level native coin transfers must succeed.
     *
     * @notice Effects
     * - Transfers WETH from Holding address to address(this).
     * - Unwraps the WETH into native coin.
     * - Withdraws the `_amount` of WETH from the holding.
     * - Deducts any applicable fees.
     * - Transfers the unwrapped amount to `msg.sender`.
     *
     * @param _amount Withdrawal amount.
     */
    function withdrawAndUnwrap(
        uint256 _amount
    ) external;

    /**
     * @notice Borrows jUSD stablecoin to the user or to the holding contract.
     *
     * @dev The _amount does not account for the collateralization ratio and is meant to represent collateral's amount
     * equivalent to jUSD's value the user wants to receive.
     * @dev Ensure that the user will not become insolvent after borrowing before calling this function, as this
     * function will revert ("3009") if the supplied `_amount` does not adhere to the collateralization ratio set in
     * the registry for the specific collateral.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Calls borrow function on `Stables Manager` Contract resulting in minting stablecoin based on the `_amount` of
     * `_token` collateral.
     *
     * @notice Emits:
     * - `Borrowed` event indicating successful borrow operation.
     *
     * @param _token Collateral token.
     * @param _amount The collateral amount equivalent for borrowed jUSD.
     * @param _mintDirectlyToUser If true, mints to user instead of holding.
     * @param _minJUsdAmountOut The minimum amount of jUSD that is expected to be received.
     *
     * @return jUsdMinted The amount of jUSD minted.
     */
    function borrow(
        address _token,
        uint256 _amount,
        uint256 _minJUsdAmountOut,
        bool _mintDirectlyToUser
    ) external returns (uint256 jUsdMinted);

    /**
     * @notice Borrows jUSD stablecoin to the user or to the holding contract using multiple collaterals.
     *
     * @dev This function will fail if any `amount` supplied in the `_data` does not adhere to the collateralization
     * ratio set in the registry for the specific collateral. For instance, if the collateralization ratio is 200%, the
     * maximum `_amount` that can be used to borrow is half of the user's free collateral, otherwise the user's holding
     * will become insolvent after borrowing.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     * - `_data` must contain at least one entry.
     *
     * @notice Effects:
     * - Mints jUSD stablecoin for each entry in `_data` based on the collateral amounts.
     *
     * @notice Emits:
     * - `Borrowed` event for each entry indicating successful borrow operation.
     * - `BorrowedMultiple` event indicating successful multiple borrow operation.
     *
     * @param _data Struct containing data for each collateral type.
     * @param _mintDirectlyToUser If true, mints to user instead of holding.
     *
     * @return  The amount of jUSD minted for each collateral type.
     */
    function borrowMultiple(
        BorrowData[] calldata _data,
        bool _mintDirectlyToUser
    ) external returns (uint256[] memory);

    /**
     * @notice Repays jUSD stablecoin debt from the user's or to the holding's address and frees up the locked
     * collateral.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     *
     * @notice Effects:
     * - Repays `_amount` jUSD stablecoin.
     *
     * @notice Emits:
     * - `Repaid` event indicating successful debt repayment operation.
     *
     * @param _token Collateral token.
     * @param _amount The repaid amount.
     * @param _repayFromUser If true, Stables Manager will burn jUSD from the msg.sender, otherwise user's holding.
     */
    function repay(address _token, uint256 _amount, bool _repayFromUser) external;

    /**
     * @notice Repays multiple jUSD stablecoin debts from the user's or to the holding's address and frees up the locked
     * collateral assets.
     *
     * @notice Requirements:
     * - `msg.sender` must have a valid holding.
     * - `_data` must contain at least one entry.
     *
     * @notice Effects:
     * - Repays stablecoin for each entry in `_data.
     *
     * @notice Emits:
     * - `Repaid` event indicating successful debt repayment operation.
     * - `RepaidMultiple` event indicating successful multiple repayment operation.
     *
     * @param _data Struct containing data for each collateral type.
     * @param _repayFromUser If true, it will burn from user's wallet, otherwise from user's holding.
     */
    function repayMultiple(RepayData[] calldata _data, bool _repayFromUser) external;

    // -- Administration --

    /**
     * @notice Triggers stopped state.
     */
    function pause() external;

    /**
     * @notice Returns to normal state.
     */
    function unpause() external;
}
IJigsawUSD.sol 86 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { IManager } from "./IManager.sol";

/**
 * @title IJigsawUSD
 * @dev Interface for the Jigsaw Stablecoin Contract.
 */
interface IJigsawUSD is IERC20 {
    /**
     * @notice event emitted when the mint limit is updated
     */
    event MintLimitUpdated(uint256 oldLimit, uint256 newLimit);

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     * @return The manager contract.
     */
    function manager() external view returns (IManager);

    /**
     * @notice Returns the max mint limit.
     */
    function mintLimit() external view returns (uint256);

    /**
     * @notice Sets the maximum mintable amount.
     *
     * @notice Requirements:
     * - Must be called by the contract owner.
     *
     * @notice Effects:
     * - Updates the `mintLimit` state variable.
     *
     * @notice Emits:
     * - `MintLimitUpdated` event indicating mint limit update operation.
     * @param _limit The new mint limit.
     */
    function updateMintLimit(
        uint256 _limit
    ) external;

    /**
     * @notice Mints tokens.
     *
     * @notice Requirements:
     * - Must be called by the Stables Manager Contract
     *  .
     * @notice Effects:
     * - Mints the specified amount of tokens to the given address.
     *
     * @param _to Address of the user receiving minted tokens.
     * @param _amount The amount to be minted.
     */
    function mint(address _to, uint256 _amount) external;

    /**
     * @notice Burns tokens from the `msg.sender`.
     *
     * @notice Requirements:
     * - Must be called by the token holder.
     *
     * @notice Effects:
     * - Burns the specified amount of tokens from the caller's balance.
     *
     * @param _amount The amount of tokens to be burnt.
     */
    function burn(
        uint256 _amount
    ) external;

    /**
     * @notice Burns tokens from an address.
     *
     * - Must be called by the Stables Manager Contract
     *
     * @notice Effects: Burns the specified amount of tokens from the specified address.
     *
     * @param _user The user to burn it from.
     * @param _amount The amount of tokens to be burnt.
     */
    function burnFrom(address _user, uint256 _amount) external;
}
IManager.sol 854 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IOracle } from "../oracle/IOracle.sol";

/**
 * @title IManager.
 * @dev Interface for the Manager Contract.
 */
interface IManager {
    // -- Events --

    /**
     * @notice Emitted when a new contract is whitelisted.
     * @param contractAddress The address of the contract that is whitelisted.
     */
    event ContractWhitelisted(address indexed contractAddress);

    /**
     * @notice Emitted when a contract is removed from the whitelist.
     * @param contractAddress The address of the contract that is removed from the whitelist.
     */
    event ContractBlacklisted(address indexed contractAddress);

    /**
     * @notice Emitted when a new token is whitelisted.
     * @param token The address of the token that is whitelisted.
     */
    event TokenWhitelisted(address indexed token);

    /**
     * @notice Emitted when a new token is removed from the whitelist.
     * @param token The address of the token that is removed from the whitelist.
     */
    event TokenRemoved(address indexed token);

    /**
     * @notice Emitted when a withdrawable token is added.
     * @param token The address of the withdrawable token.
     */
    event WithdrawableTokenAdded(address indexed token);

    /**
     * @notice Emitted when a withdrawable token is removed.
     * @param token The address of the withdrawable token.
     */
    event WithdrawableTokenRemoved(address indexed token);

    /**
     * @notice Emitted when invoker is updated.
     * @param component The address of the invoker component.
     * @param allowed Boolean indicating if the invoker is allowed or not.
     */
    event InvokerUpdated(address indexed component, bool allowed);

    /**
     * @notice Emitted when the holding manager is set.
     * @param oldAddress The previous address of the holding manager.
     * @param newAddress The new address of the holding manager.
     */
    event HoldingManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when a new liquidation manager is requested.
     * @param oldAddress The previous address of the liquidation manager.
     * @param newAddress The new address of the liquidation manager.
     */
    event NewLiquidationManagerRequested(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the liquidation manager is set.
     * @param oldAddress The previous address of the liquidation manager.
     * @param newAddress The new address of the liquidation manager.
     */
    event LiquidationManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the stablecoin manager is set.
     * @param oldAddress The previous address of the stablecoin manager.
     * @param newAddress The new address of the stablecoin manager.
     */
    event StablecoinManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the strategy manager is set.
     * @param oldAddress The previous address of the strategy manager.
     * @param newAddress The new address of the strategy manager.
     */
    event StrategyManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when a new swap manager is requested.
     * @param oldAddress The previous address of the swap manager.
     * @param newAddress The new address of the swap manager.
     */
    event NewSwapManagerRequested(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the swap manager is set.
     * @param oldAddress The previous address of the swap manager.
     * @param newAddress The new address of the swap manager.
     */
    event SwapManagerUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the default fee is updated.
     * @param oldFee The previous fee.
     * @param newFee The new fee.
     */
    event PerformanceFeeUpdated(uint256 indexed oldFee, uint256 indexed newFee);

    /**
     * @notice Emitted when the withdraw fee is updated.
     * @param oldFee The previous withdraw fee.
     * @param newFee The new withdraw fee.
     */
    event WithdrawalFeeUpdated(uint256 indexed oldFee, uint256 indexed newFee);

    /**
     * @notice Emitted when the liquidator's bonus is updated.
     * @param oldAmount The previous amount of the liquidator's bonus.
     * @param newAmount The new amount of the liquidator's bonus.
     */
    event LiquidatorBonusUpdated(uint256 oldAmount, uint256 newAmount);

    /**
     * @notice Emitted when the fee address is changed.
     * @param oldAddress The previous fee address.
     * @param newAddress The new fee address.
     */
    event FeeAddressUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the receipt token factory is updated.
     * @param oldAddress The previous address of the receipt token factory.
     * @param newAddress The new address of the receipt token factory.
     */
    event ReceiptTokenFactoryUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when the liquidity gauge factory is updated.
     * @param oldAddress The previous address of the liquidity gauge factory.
     * @param newAddress The new address of the liquidity gauge factory.
     */
    event LiquidityGaugeFactoryUpdated(address indexed oldAddress, address indexed newAddress);

    /**
     * @notice Emitted when new oracle is requested.
     * @param newOracle The address of the new oracle.
     */
    event NewOracleRequested(address newOracle);

    /**
     * @notice Emitted when the oracle is updated.
     * @param oldOracle The address of the old oracle.
     * @param newOracle The address of the new oracle.
     */
    event OracleUpdated(address indexed oldOracle, address indexed newOracle);

    /**
     * @notice Emitted when oracle data is updated.
     * @param oldData The address of the old oracle data.
     * @param newData The address of the new oracle data.
     */
    event OracleDataUpdated(bytes indexed oldData, bytes indexed newData);

    /**
     * @notice Emitted when a new timelock amount is requested.
     * @param oldVal The previous timelock amount.
     * @param newVal The new timelock amount.
     */
    event TimelockAmountUpdateRequested(uint256 oldVal, uint256 newVal);

    /**
     * @notice Emitted when timelock amount is updated.
     * @param oldVal The previous timelock amount.
     * @param newVal The new timelock amount.
     */
    event TimelockAmountUpdated(uint256 oldVal, uint256 newVal);

    // -- Mappings --

    /**
     * @notice Returns true/false for contracts' whitelist status.
     * @param _contract The address of the contract.
     */
    function isContractWhitelisted(
        address _contract
    ) external view returns (bool);

    /**
     * @notice Returns true if token is whitelisted.
     * @param _token The address of the token.
     */
    function isTokenWhitelisted(
        address _token
    ) external view returns (bool);

    /**
     * @notice Returns true if the token can be withdrawn from a holding.
     * @param _token The address of the token.
     */
    function isTokenWithdrawable(
        address _token
    ) external view returns (bool);

    /**
     * @notice Returns true if caller is allowed invoker.
     * @param _invoker The address of the invoker.
     */
    function allowedInvokers(
        address _invoker
    ) external view returns (bool);

    // -- Essential tokens --

    /**
     * @notice WETH address.
     */
    function WETH() external view returns (address);

    // -- Protocol's stablecoin oracle config --

    /**
     * @notice Oracle contract associated with protocol's stablecoin.
     */
    function jUsdOracle() external view returns (IOracle);

    /**
     * @notice Extra oracle data if needed.
     */
    function oracleData() external view returns (bytes calldata);

    // -- Managers --

    /**
     * @notice Returns the address of the HoldingManager Contract.
     */
    function holdingManager() external view returns (address);

    /**
     * @notice Returns the address of the LiquidationManager Contract.
     */
    function liquidationManager() external view returns (address);

    /**
     * @notice Returns the address of the StablesManager Contract.
     */
    function stablesManager() external view returns (address);

    /**
     * @notice Returns the address of the StrategyManager Contract.
     */
    function strategyManager() external view returns (address);

    /**
     * @notice Returns the address of the SwapManager Contract.
     */
    function swapManager() external view returns (address);

    // -- Fees --

    /**
     * @notice Returns the default performance fee.
     * @dev Uses 2 decimal precision, where 1% is represented as 100.
     */
    function performanceFee() external view returns (uint256);

    /**
     * @notice Returns the maximum performance fee.
     * @dev Uses 2 decimal precision, where 1% is represented as 100.
     */
    function MAX_PERFORMANCE_FEE() external view returns (uint256);

    /**
     * @notice Fee for withdrawing from a holding.
     * @dev Uses 2 decimal precision, where 1% is represented as 100.
     */
    function withdrawalFee() external view returns (uint256);

    /**
     * @notice Returns the maximum withdrawal fee.
     * @dev Uses 2 decimal precision, where 1% is represented as 100.
     */
    function MAX_WITHDRAWAL_FEE() external view returns (uint256);

    /**
     * @notice Returns the fee address, where all the fees are collected.
     */
    function feeAddress() external view returns (address);

    // -- Factories --

    /**
     * @notice Returns the address of the ReceiptTokenFactory.
     */
    function receiptTokenFactory() external view returns (address);

    // -- Utility values --

    /**
     * @notice Minimum allowed jUSD debt amount for a holding to ensure successful liquidation.
     */
    function minDebtAmount() external view returns (uint256);

    /**
     * @notice Returns the collateral rate precision.
     * @dev Should be less than exchange rate precision due to optimization in math.
     */
    function PRECISION() external view returns (uint256);

    /**
     * @notice Returns the exchange rate precision.
     */
    function EXCHANGE_RATE_PRECISION() external view returns (uint256);

    /**
     * @notice Timelock amount in seconds for changing the oracle data.
     */
    function timelockAmount() external view returns (uint256);

    /**
     * @notice Returns the old timelock value for delayed timelock update.
     */
    function oldTimelock() external view returns (uint256);

    /**
     * @notice Returns the new timelock value for delayed timelock update.
     */
    function newTimelock() external view returns (uint256);

    /**
     * @notice Returns the timestamp when the new timelock was requested.
     */
    function newTimelockTimestamp() external view returns (uint256);

    /**
     * @notice Returns the new oracle address for delayed oracle update.
     */
    function newOracle() external view returns (address);

    /**
     * @notice Returns the timestamp when the new oracle was requested.
     */
    function newOracleTimestamp() external view returns (uint256);

    /**
     * @notice Returns the new swap manager address for delayed swap manager update.
     */
    function newSwapManager() external view returns (address);

    /**
     * @notice Returns the timestamp when the new swap manager was requested.
     */
    function newSwapManagerTimestamp() external view returns (uint256);

    /**
     * @notice Returns the new liquidation manager address for delayed liquidation manager update.
     */
    function newLiquidationManager() external view returns (address);

    /**
     * @notice Returns the timestamp when the new liquidation manager was requested.
     */
    function newLiquidationManagerTimestamp() external view returns (uint256);

    // -- Setters --

    /**
     * @notice Whitelists a contract.
     *
     * @notice Requirements:
     * - `_contract` must not be whitelisted.
     *
     * @notice Effects:
     * - Updates the `isContractWhitelisted` mapping.
     *
     * @notice Emits:
     * - `ContractWhitelisted` event indicating successful contract whitelist operation.
     *
     * @param _contract The address of the contract to be whitelisted.
     */
    function whitelistContract(
        address _contract
    ) external;

    /**
     * @notice Blacklists a contract.
     *
     * @notice Requirements:
     * - `_contract` must be whitelisted.
     *
     * @notice Effects:
     * - Updates the `isContractWhitelisted` mapping.
     *
     * @notice Emits:
     * - `ContractBlacklisted` event indicating successful contract blacklist operation.
     *
     * @param _contract The address of the contract to be blacklisted.
     */
    function blacklistContract(
        address _contract
    ) external;

    /**
     * @notice Whitelists a token.
     *
     * @notice Requirements:
     * - `_token` must not be whitelisted.
     *
     * @notice Effects:
     * - Updates the `isTokenWhitelisted` mapping.
     *
     * @notice Emits:
     * - `TokenWhitelisted` event indicating successful token whitelist operation.
     *
     * @param _token The address of the token to be whitelisted.
     */
    function whitelistToken(
        address _token
    ) external;

    /**
     * @notice Removes a token from whitelist.
     *
     * @notice Requirements:
     * - `_token` must be whitelisted.
     *
     * @notice Effects:
     * - Updates the `isTokenWhitelisted` mapping.
     *
     * @notice Emits:
     * - `TokenRemoved` event indicating successful token removal operation.
     *
     * @param _token The address of the token to be whitelisted.
     */
    function removeToken(
        address _token
    ) external;

    /**
     * @notice Registers the `_token` as withdrawable.
     *
     * @notice Requirements:
     * - `msg.sender` must be owner or `strategyManager`.
     * - `_token` must not be withdrawable.
     *
     * @notice Effects:
     * - Updates the `isTokenWithdrawable` mapping.
     *
     * @notice Emits:
     * - `WithdrawableTokenAdded` event indicating successful withdrawable token addition operation.
     *
     * @param _token The address of the token to be added as withdrawable.
     */
    function addWithdrawableToken(
        address _token
    ) external;

    /**
     * @notice Unregisters the `_token` as withdrawable.
     *
     * @notice Requirements:
     * - `_token` must be withdrawable.
     *
     * @notice Effects:
     * - Updates the `isTokenWithdrawable` mapping.
     *
     * @notice Emits:
     * - `WithdrawableTokenRemoved` event indicating successful withdrawable token removal operation.
     *
     * @param _token The address of the token to be removed as withdrawable.
     */
    function removeWithdrawableToken(
        address _token
    ) external;

    /**
     * @notice Sets invoker as allowed or forbidden.
     *
     * @notice Effects:
     * - Updates the `allowedInvokers` mapping.
     *
     * @notice Emits:
     * - `InvokerUpdated` event indicating successful invoker update operation.
     *
     * @param _component Invoker's address.
     * @param _allowed True/false.
     */
    function updateInvoker(address _component, bool _allowed) external;

    /**
     * @notice Sets the Holding Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `holdingManager` address.
     *
     * @notice Effects:
     * - Updates the `holdingManager` state variable.
     *
     * @notice Emits:
     * - `HoldingManagerUpdated` event indicating the successful setting of the Holding Manager's address.
     *
     * @param _val The holding manager's address.
     */
    function setHoldingManager(
        address _val
    ) external;

    /**
     * @notice Sets the Liquidation Manager Contract's address.
     *
     * @notice Requirements:
     * - Can only be called once.
     * - `_val` must be non-zero address.
     *
     * @notice Effects:
     * - Updates the `liquidationManager` state variable.
     *
     * @notice Emits:
     * - `LiquidationManagerUpdated` event indicating the successful setting of the Liquidation Manager's address.
     *
     * @param _val The liquidation manager's address.
     */
    function setLiquidationManager(
        address _val
    ) external;

    /**
     * @notice Initiates the process to update the Liquidation Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be non-zero address.
     * - `_val` must be different from previous `liquidationManager` address.
     *
     * @notice Effects:
     * - Updates the the `_newLiquidationManager` state variable.
     * - Updates the the `_newLiquidationManagerTimestamp` state variable.
     *
     * @notice Emits:
     * - `LiquidationManagerUpdateRequested` event indicating successful liquidation manager change request.
     *
     * @param _val The new liquidation manager's address.
     */
    function requestNewLiquidationManager(
        address _val
    ) external;

    /**
     * @notice Sets the Liquidation Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `liquidationManager` address.
     * - Timelock must expire.
     *
     * @notice Effects:
     * - Updates the `liquidationManager` state variable.
     * - Updates the the `_newLiquidationManager` state variable.
     * - Updates the the `_newLiquidationManagerTimestamp` state variable.
     *
     * @notice Emits:
     * - `LiquidationManagerUpdated` event indicating the successful setting of the Liquidation Manager's address.
     */
    function acceptNewLiquidationManager() external;

    /**
     * @notice Sets the Stablecoin Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `stablesManager` address.
     *
     * @notice Effects:
     * - Updates the `stablesManager` state variable.
     *
     * @notice Emits:
     * - `StablecoinManagerUpdated` event indicating the successful setting of the Stablecoin Manager's address.
     *
     * @param _val The Stablecoin manager's address.
     */
    function setStablecoinManager(
        address _val
    ) external;

    /**
     * @notice Sets the Strategy Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `strategyManager` address.
     *
     * @notice Effects:
     * - Updates the `strategyManager` state variable.
     *
     * @notice Emits:
     * - `StrategyManagerUpdated` event indicating the successful setting of the Strategy Manager's address.
     *
     * @param _val The Strategy manager's address.
     */
    function setStrategyManager(
        address _val
    ) external;

    /**
     * @notice Sets the Swap Manager Contract's address.
     *
     * @notice Requirements:
     * - Can only be called once.
     * - `_val` must be non-zero address.
     *
     * @notice Effects:
     * - Updates the `swapManager` state variable.
     *
     * @notice Emits:
     * - `SwapManagerUpdated` event indicating the successful setting of the Swap Manager's address.
     *
     * @param _val The Swap manager's address.
     */
    function setSwapManager(
        address _val
    ) external;

    /**
     * @notice Initiates the process to update the Swap Manager Contract's address.
     *
     * @notice Requirements:
     * - `_val` must be non-zero address.
     * - `_val` must be different from previous `swapManager` address.
     *
     * @notice Effects:
     * - Updates the the `_newSwapManager` state variable.
     * - Updates the the `_newSwapManagerTimestamp` state variable.
     *
     * @notice Emits:
     * - `NewSwapManagerRequested` event indicating successful swap manager change request.
     *
     * @param _val The new swap manager's address.
     */
    function requestNewSwapManager(
        address _val
    ) external;

    /**
     * @notice Updates the Swap Manager Contract    .
     *
     * @notice Requirements:
     * - Timelock must expire.
     *
     * @notice Effects:
     * - Updates the `swapManager` state variable.
     * - Resets `_newSwapManager` to address(0).
     * - Resets `_newSwapManagerTimestamp` to 0.
     *
     * @notice Emits:
     * - `SwapManagerUpdated` event indicating the successful setting of the Swap Manager's address.
     */
    function acceptNewSwapManager() external;

    /**
     * @notice Sets the performance fee.
     *
     * @notice Requirements:
     * - `_val` must be smaller than `FEE_FACTOR` to avoid wrong computations.
     *
     * @notice Effects:
     * - Updates the `performanceFee` state variable.
     *
     * @notice Emits:
     * - `PerformanceFeeUpdated` event indicating successful performance fee update operation.
     *
     * @dev `_val` uses 2 decimal precision, where 1% is represented as 100.
     *
     * @param _val The new performance fee value.
     */
    function setPerformanceFee(
        uint256 _val
    ) external;

    /**
     * @notice Sets the withdrawal fee.
     *
     * @notice Requirements:
     * - `_val` must be smaller than `FEE_FACTOR` to avoid wrong computations.
     *
     * @notice Effects:
     * - Updates the `withdrawalFee` state variable.
     *
     * @notice Emits:
     * - `WithdrawalFeeUpdated` event indicating successful withdrawal fee update operation.
     *
     * @dev `_val` uses 2 decimal precision, where 1% is represented as 100.
     *
     * @param _val The new withdrawal fee value.
     */
    function setWithdrawalFee(
        uint256 _val
    ) external;

    /**
     * @notice Sets the global fee address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `holdingManager` address.
     *
     * @notice Effects:
     * - Updates the `feeAddress` state variable.
     *
     * @notice Emits:
     * - `FeeAddressUpdated` event indicating successful setting of the global fee address.
     *
     * @param _val The new fee address.
     */
    function setFeeAddress(
        address _val
    ) external;

    /**
     * @notice Sets the receipt token factory's address.
     *
     * @notice Requirements:
     * - `_val` must be different from previous `receiptTokenFactory` address.
     *
     * @notice Effects:
     * - Updates the `receiptTokenFactory` state variable.
     *
     * @notice Emits:
     * - `ReceiptTokenFactoryUpdated` event indicating successful setting of the `receiptTokenFactory` address.
     *
     * @param _factory Receipt token factory's address.
     */
    function setReceiptTokenFactory(
        address _factory
    ) external;

    /**
     * @notice Registers jUSD's oracle change request.
     *
     * @notice Requirements:
     * - Contract must not be in active change.
     *
     * @notice Effects:
     * - Updates the the `_isActiveChange` state variable.
     * - Updates the the `_newOracle` state variable.
     * - Updates the the `_newOracleTimestamp` state variable.
     *
     * @notice Emits:
     * - `NewOracleRequested` event indicating successful jUSD's oracle change request.
     *
     * @param _oracle Liquidity gauge factory's address.
     */
    function requestNewJUsdOracle(
        address _oracle
    ) external;

    /**
     * @notice Updates jUSD's oracle.
     *
     * @notice Requirements:
     * - Contract must be in active change.
     * - Timelock must expire.
     *
     * @notice Effects:
     * - Updates the the `jUsdOracle` state variable.
     * - Updates the the `_isActiveChange` state variable.
     * - Updates the the `_newOracle` state variable.
     * - Updates the the `_newOracleTimestamp` state variable.
     *
     * @notice Emits:
     * - `OracleUpdated` event indicating successful jUSD's oracle change.
     */
    function acceptNewJUsdOracle() external;

    /**
     * @notice Updates the jUSD's oracle data.
     *
     * @notice Requirements:
     * - `_newOracleData` must be different from previous `oracleData`.
     *
     * @notice Effects:
     * - Updates the `oracleData` state variable.
     *
     * @notice Emits:
     * - `OracleDataUpdated` event indicating successful update of the oracle Data.
     *
     * @param _newOracleData New data used for jUSD's oracle data.
     */
    function setJUsdOracleData(
        bytes calldata _newOracleData
    ) external;

    /**
     * @notice Sets the minimum debt amount.
     *
     * @notice Requirements:
     * - `_minDebtAmount` must be greater than zero.
     * - `_minDebtAmount` must be different from previous `minDebtAmount`.
     *
     * @param _minDebtAmount The new minimum debt amount.
     */
    function setMinDebtAmount(
        uint256 _minDebtAmount
    ) external;

    /**
     * @notice Registers timelock change request.
     *
     * @notice Requirements:
     * - `_oldTimelock` must be set zero.
     * - `_newVal` must be greater than zero.
     *
     * @notice Effects:
     * - Updates the the `_oldTimelock` state variable.
     * - Updates the the `_newTimelock` state variable.
     * - Updates the the `_newTimelockTimestamp` state variable.
     *
     * @notice Emits:
     * - `TimelockAmountUpdateRequested` event indicating successful timelock change request.
     *
     * @param _newVal The new timelock value in seconds.
     */
    function requestNewTimelock(
        uint256 _newVal
    ) external;

    /**
     * @notice Updates the timelock amount.
     *
     * @notice Requirements:
     * - Contract must be in active change.
     * - `_newTimelock` must be greater than zero.
     * - The old timelock must expire.
     *
     * @notice Effects:
     * - Updates the the `timelockAmount` state variable.
     * - Updates the the `_oldTimelock` state variable.
     * - Updates the the `_newTimelock` state variable.
     * - Updates the the `_newTimelockTimestamp` state variable.
     *
     * @notice Emits:
     * - `TimelockAmountUpdated` event indicating successful timelock amount change.
     */
    function acceptNewTimelock() external;

    // -- Getters --

    /**
     * @notice Returns the up to date exchange rate of the protocol's stablecoin jUSD.
     *
     * @notice Requirements:
     * - Oracle must have updated rate.
     * - Rate must be a non zero positive value.
     *
     * @return The current exchange rate.
     */
    function getJUsdExchangeRate() external view returns (uint256);
}
ISharesRegistry.sol 355 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IOracle } from "../oracle/IOracle.sol";
import { IManager } from "./IManager.sol";

/**
 * @title ISharesRegistry
 * @dev Interface for the Shares Registry Contract.
 * @dev Based on MIM CauldraonV2 contract.
 */
interface ISharesRegistry {
    /**
     * @notice Configuration struct for registry parameters.
     * @dev Used to store key parameters that control collateral and liquidation behavior.
     *
     * @param collateralizationRate The minimum collateral ratio required, expressed as a percentage with precision.
     * @param liquidationBuffer Is a value, that represents the buffer between the collateralization rate and the
     * liquidation threshold, upon which the liquidation is allowed.
     * @param liquidatorBonus The bonus percentage given to liquidators as incentive, expressed with precision.
     */
    struct RegistryConfig {
        uint256 collateralizationRate;
        uint256 liquidationBuffer;
        uint256 liquidatorBonus;
    }

    /**
     * @notice Event emitted when borrowed amount is set.
     * @param _holding The address of the holding.
     * @param oldVal The old value.
     * @param newVal The new value.
     */
    event BorrowedSet(address indexed _holding, uint256 oldVal, uint256 newVal);

    /**
     * @notice Event emitted when collateral is registered.
     * @param user The address of the user.
     * @param share The amount of shares.
     */
    event CollateralAdded(address indexed user, uint256 share);

    /**
     * @notice Event emitted when collateral was unregistered.
     * @param user The address of the user.
     * @param share The amount of shares.
     */
    event CollateralRemoved(address indexed user, uint256 share);

    /**
     * @notice Event emitted when the collateralization rate is updated.
     * @param oldVal The old value.
     * @param newVal The new value.
     */
    event CollateralizationRateUpdated(uint256 oldVal, uint256 newVal);

    /**
     * @notice Event emitted when a new oracle is requested.
     * @param newOracle The new oracle address.
     */
    event NewOracleRequested(address newOracle);

    /**
     * @notice Event emitted when the oracle is updated.
     */
    event OracleUpdated();

    /**
     * @notice Event emitted when new oracle data is requested.
     * @param newData The new data.
     */
    event NewOracleDataRequested(bytes newData);

    /**
     * @notice Event emitted when oracle data is updated.
     */
    event OracleDataUpdated();

    /**
     * @notice Event emitted when a new timelock amount is requested.
     * @param oldVal The old value.
     * @param newVal The new value.
     */
    event TimelockAmountUpdateRequested(uint256 oldVal, uint256 newVal);

    /**
     * @notice Event emitted when timelock amount is updated.
     * @param oldVal The old value.
     * @param newVal The new value.
     */
    event TimelockAmountUpdated(uint256 oldVal, uint256 newVal);

    /**
     * @notice Event emitted when the config is updated.
     * @param token The token address.
     * @param oldVal The old config.
     * @param newVal The new config.
     */
    event ConfigUpdated(address indexed token, RegistryConfig oldVal, RegistryConfig newVal);

    /**
     * @notice Returns holding's borrowed amount.
     * @param _holding The address of the holding.
     * @return The borrowed amount.
     */
    function borrowed(
        address _holding
    ) external view returns (uint256);

    /**
     * @notice Returns holding's available collateral amount.
     * @param _holding The address of the holding.
     * @return The collateral amount.
     */
    function collateral(
        address _holding
    ) external view returns (uint256);

    /**
     * @notice Returns the token address for which this registry was created.
     * @return The token address.
     */
    function token() external view returns (address);

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     * @return The manager contract.
     */
    function manager() external view returns (IManager);

    /**
     * @notice Oracle contract associated with this share registry.
     * @return The oracle contract.
     */
    function oracle() external view returns (IOracle);

    /**
     * @notice Extra oracle data if needed.
     * @return The oracle data.
     */
    function oracleData() external view returns (bytes calldata);

    /**
     * @notice Current timelock amount.
     * @return The timelock amount.
     */
    function timelockAmount() external view returns (uint256);

    // -- User specific methods --

    /**
     * @notice Updates `_holding`'s borrowed amount.
     *
     * @notice Requirements:
     * - `msg.sender` must be the Stables Manager Contract.
     * - `_newVal` must be greater than or equal to the minimum debt amount.
     *
     * @notice Effects:
     * - Updates `borrowed` mapping.
     *
     * @notice Emits:
     * - `BorrowedSet` indicating holding's borrowed amount update operation.
     *
     * @param _holding The address of the user's holding.
     * @param _newVal The new borrowed amount.
     */
    function setBorrowed(address _holding, uint256 _newVal) external;

    /**
     * @notice Registers collateral for user's `_holding`.
     *
     * @notice Requirements:
     * - `msg.sender` must be the Stables Manager Contract.
     *
     * @notice Effects:
     * - Updates `collateral` mapping.
     *
     * @notice Emits:
     * - `CollateralAdded` event indicating collateral addition operation.
     *
     * @param _holding The address of the user's holding.
     * @param _share The new collateral shares.
     */
    function registerCollateral(address _holding, uint256 _share) external;

    /**
     * @notice Registers a collateral removal operation for user's `_holding`.
     *
     * @notice Requirements:
     * - `msg.sender` must be the Stables Manager Contract.
     *
     * @notice Effects:
     * - Updates `collateral` mapping.
     *
     * @notice Emits:
     * - `CollateralRemoved` event indicating collateral removal operation.
     *
     * @param _holding The address of the user's holding.
     * @param _share The new collateral shares.
     */
    function unregisterCollateral(address _holding, uint256 _share) external;

    // -- Administration --

    /**
     * @notice Updates the registry configuration parameters.
     *
     * @notice Effects:
     * - Updates `config` state variable.
     *
     * @notice Emits:
     * - `ConfigUpdated` event indicating config update operation.
     *
     * @param _newConfig The new configuration parameters.
     */
    function updateConfig(
        RegistryConfig memory _newConfig
    ) external;

    /**
     * @notice Requests a change for the oracle address.
     *
     * @notice Requirements:
     * - Previous oracle change request must have expired or been accepted.
     * - No timelock or oracle data change requests should be active.
     * - `_oracle` must not be the zero address.
     *
     * @notice Effects:
     * - Updates `_isOracleActiveChange` state variable.
     * - Updates `_newOracle` state variable.
     * - Updates `_newOracleTimestamp` state variable.
     *
     * @notice Emits:
     * - `NewOracleRequested` event indicating new oracle request.
     *
     * @param _oracle The new oracle address.
     */
    function requestNewOracle(
        address _oracle
    ) external;

    /**
     * @notice Updates the oracle.
     *
     * @notice Requirements:
     * - Oracle change must have been requested and the timelock must have passed.
     *
     * @notice Effects:
     * - Updates `oracle` state variable.
     * - Updates `_isOracleActiveChange` state variable.
     * - Updates `_newOracle` state variable.
     * - Updates `_newOracleTimestamp` state variable.
     *
     * @notice Emits:
     * - `OracleUpdated` event indicating oracle update.
     */
    function setOracle() external;

    /**
     * @notice Requests a change for oracle data.
     *
     * @notice Requirements:
     * - Previous oracle data change request must have expired or been accepted.
     * - No timelock or oracle change requests should be active.
     *
     * @notice Effects:
     * - Updates `_isOracleDataActiveChange` state variable.
     * - Updates `_newOracleData` state variable.
     * - Updates `_newOracleDataTimestamp` state variable.
     *
     * @notice Emits:
     * - `NewOracleDataRequested` event indicating new oracle data request.
     *
     * @param _data The new oracle data.
     */
    function requestNewOracleData(
        bytes calldata _data
    ) external;

    /**
     * @notice Updates the oracle data.
     *
     * @notice Requirements:
     * - Oracle data change must have been requested and the timelock must have passed.
     *
     * @notice Effects:
     * - Updates `oracleData` state variable.
     * - Updates `_isOracleDataActiveChange` state variable.
     * - Updates `_newOracleData` state variable.
     * - Updates `_newOracleDataTimestamp` state variable.
     *
     * @notice Emits:
     * - `OracleDataUpdated` event indicating oracle data update.
     */
    function setOracleData() external;

    /**
     * @notice Requests a timelock update.
     *
     * @notice Requirements:
     * - `_newVal` must not be zero.
     * - Previous timelock change request must have expired or been accepted.
     * - No oracle or oracle data change requests should be active.
     *
     * @notice Effects:
     * - Updates `_isTimelockActiveChange` state variable.
     * - Updates `_oldTimelock` state variable.
     * - Updates `_newTimelock` state variable.
     * - Updates `_newTimelockTimestamp` state variable.
     *
     * @notice Emits:
     * - `TimelockAmountUpdateRequested` event indicating timelock change request.
     *
     * @param _newVal The new value in seconds.
     */
    function requestTimelockAmountChange(
        uint256 _newVal
    ) external;

    /**
     * @notice Updates the timelock amount.
     *
     * @notice Requirements:
     * - Timelock change must have been requested and the timelock must have passed.
     * - The timelock for timelock change must have already expired.
     *
     * @notice Effects:
     * - Updates `timelockAmount` state variable.
     * - Updates `_oldTimelock` state variable.
     * - Updates `_newTimelock` state variable.
     * - Updates `_newTimelockTimestamp` state variable.
     *
     * @notice Emits:
     * - `TimelockAmountUpdated` event indicating timelock amount change operation.
     */
    function acceptTimelockAmountChange() external;

    // -- Getters --

    /**
     * @notice Returns the up to date exchange rate of the `token`.
     *
     * @notice Requirements:
     * - Oracle must provide an updated rate.
     *
     * @return The updated exchange rate.
     */
    function getExchangeRate() external view returns (uint256);

    /**
     * @notice Returns the configuration parameters for the registry.
     * @return The RegistryConfig struct containing the parameters.
     */
    function getConfig() external view returns (RegistryConfig memory);
}
IStablesManager.sol 298 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IJigsawUSD } from "../core/IJigsawUSD.sol";
import { ISharesRegistry } from "../core/ISharesRegistry.sol";
import { IManager } from "./IManager.sol";

/**
 * @title IStablesManager
 * @notice Interface for the Stables Manager.
 */
interface IStablesManager {
    // -- Custom types --

    /**
     * @notice Structure to store state and deployment address for a share registry
     */
    struct ShareRegistryInfo {
        bool active; // Flag indicating if the registry is active
        address deployedAt; // Address where the registry is deployed
    }

    /**
     * @notice Temporary struct used to store data during borrow operations to avoid stack too deep errors.
     * @dev This struct helps organize variables used in the borrow function.
     * @param registry The shares registry contract for the collateral token
     * @param exchangeRatePrecision The precision used for exchange rate calculations
     * @param amount The normalized amount (18 decimals) of collateral being borrowed against
     * @param amountValue The USD value of the collateral amount
     */
    struct BorrowTempData {
        ISharesRegistry registry;
        uint256 exchangeRatePrecision;
        uint256 amount;
        uint256 amountValue;
    }

    // -- Events --

    /**
     * @notice Emitted when collateral is registered.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param amount The amount of collateral.
     */
    event AddedCollateral(address indexed holding, address indexed token, uint256 amount);

    /**
     * @notice Emitted when collateral is unregistered.
     * @param holding The address of the holding.
     * @param token The address of the token.
     * @param amount The amount of collateral.
     */
    event RemovedCollateral(address indexed holding, address indexed token, uint256 amount);

    /**
     * @notice Emitted when a borrow action is performed.
     * @param holding The address of the holding.
     * @param jUsdMinted The amount of jUSD minted.
     * @param mintToUser Boolean indicating if the amount is minted directly to the user.
     */
    event Borrowed(address indexed holding, uint256 jUsdMinted, bool mintToUser);

    /**
     * @notice Emitted when a repay action is performed.
     * @param holding The address of the holding.
     * @param amount The amount repaid.
     * @param burnFrom The address to burn from.
     */
    event Repaid(address indexed holding, uint256 amount, address indexed burnFrom);

    /**
     * @notice Emitted when a registry is added.
     * @param token The address of the token.
     * @param registry The address of the registry.
     */
    event RegistryAdded(address indexed token, address indexed registry);

    /**
     * @notice Emitted when a registry is updated.
     * @param token The address of the token.
     * @param registry The address of the registry.
     */
    event RegistryUpdated(address indexed token, address indexed registry);

    /**
     * @notice Returns total borrowed jUSD amount using `token`.
     * @param _token The address of the token.
     * @return The total borrowed amount.
     */
    function totalBorrowed(
        address _token
    ) external view returns (uint256);

    /**
     * @notice Returns config info for each token.
     * @param _token The address of the token to get registry info for.
     * @return Boolean indicating if the registry is active and the address of the registry.
     */
    function shareRegistryInfo(
        address _token
    ) external view returns (bool, address);

    /**
     * @notice Returns protocol's stablecoin address.
     * @return The address of the Jigsaw stablecoin.
     */
    function jUSD() external view returns (IJigsawUSD);

    /**
     * @notice Contract that contains all the necessary configs of the protocol.
     * @return The manager contract.
     */
    function manager() external view returns (IManager);

    // -- User specific methods --

    /**
     * @notice Registers new collateral.
     *
     * @dev The amount will be transformed to shares.
     *
     * @notice Requirements:
     * - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
     * - The `_token` must be whitelisted.
     * - The `_token`'s registry must be active.
     *
     * @notice Effects:
     * - Adds collateral for the holding.
     *
     * @notice Emits:
     * - `AddedCollateral` event indicating successful collateral addition operation.
     *
     * @param _holding The holding for which collateral is added.
     * @param _token Collateral token.
     * @param _amount Amount of tokens to be added as collateral.
     */
    function addCollateral(address _holding, address _token, uint256 _amount) external;

    /**
     * @notice Unregisters collateral.
     *
     * @notice Requirements:
     * - The contract must not be paused.
     * - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
     * - The token's registry must be active.
     * - `_holding` must stay solvent after collateral removal.
     *
     * @notice Effects:
     * - Removes collateral for the holding.
     *
     * @notice Emits:
     * - `RemovedCollateral` event indicating successful collateral removal operation.
     *
     * @param _holding The holding for which collateral is removed.
     * @param _token Collateral token.
     * @param _amount Amount of collateral.
     */
    function removeCollateral(address _holding, address _token, uint256 _amount) external;

    /**
     * @notice Unregisters collateral.
     *
     * @notice Requirements:
     * - The caller must be the LiquidationManager.
     * - The token's registry must be active.
     *
     * @notice Effects:
     * - Force removes collateral from the `_holding` in case of liquidation, without checking if user is solvent after
     * collateral removal.
     *
     * @notice Emits:
     * - `RemovedCollateral` event indicating successful collateral removal operation.
     *
     * @param _holding The holding for which collateral is added.
     * @param _token Collateral token.
     * @param _amount Amount of collateral.
     */
    function forceRemoveCollateral(address _holding, address _token, uint256 _amount) external;

    /**
     * @notice Mints stablecoin to the user.
     *
     * @notice Requirements:
     * - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
     * - The token's registry must be active.
     * - `_amount` must be greater than zero.
     *
     * @notice Effects:
     * - Mints stablecoin based on the collateral amount.
     * - Updates the total borrowed jUSD amount for `_token`, used for borrowing.
     * - Updates `_holdings`'s borrowed amount in `token`'s registry contract.
     * - Ensures the holding remains solvent.
     *
     * @notice Emits:
     * - `Borrowed`.
     *
     * @param _holding The holding for which collateral is added.
     * @param _token Collateral token.
     * @param _amount The collateral amount equivalent for borrowed jUSD.
     * @param _minJUsdAmountOut The minimum amount of jUSD that is expected to be received.
     * @param _mintDirectlyToUser If true, mints to user instead of holding.
     *
     * @return jUsdMintAmount The amount of jUSD minted.
     */
    function borrow(
        address _holding,
        address _token,
        uint256 _amount,
        uint256 _minJUsdAmountOut,
        bool _mintDirectlyToUser
    ) external returns (uint256 jUsdMintAmount);

    /**
     * @notice Repays debt.
     *
     * @notice Requirements:
     * - The caller must be allowed to perform this action directly. If user - use Holding Manager Contract.
     * - The token's registry must be active.
     * - The holding must have a positive borrowed amount.
     * - `_amount` must not exceed `holding`'s borrowed amount.
     * - `_amount` must be greater than zero.
     * - `_burnFrom` must not be the zero address.
     *
     * @notice Effects:
     * - Updates the total borrowed jUSD amount for `_token`, used for borrowing.
     * - Updates `_holdings`'s borrowed amount in `token`'s registry contract.
     * - Burns `_amount` jUSD tokens from `_burnFrom` address
     *
     * @notice Emits:
     * - `Repaid` event indicating successful repay operation.
     *
     * @param _holding The holding for which repay is performed.
     * @param _token Collateral token.
     * @param _amount The repaid jUSD amount.
     * @param _burnFrom The address to burn from.
     */
    function repay(address _holding, address _token, uint256 _amount, address _burnFrom) external;

    // -- Administration --

    /**
     * @notice Triggers stopped state.
     */
    function pause() external;

    /**
     * @notice Returns to normal state.
     */
    function unpause() external;

    // -- Getters --

    /**
     * @notice Returns true if user is solvent for the specified token.
     *
     * @dev The method reverts if block.timestamp - _maxTimeRange > exchangeRateUpdatedAt.
     *
     * @notice Requirements:
     * - `_holding` must not be the zero address.
     * - There must be registry for `_token`.
     *
     * @param _token The token for which the check is done.
     * @param _holding The user address.
     *
     * @return flag indicating whether `holding` is solvent.
     */
    function isSolvent(address _token, address _holding) external view returns (bool);

    /**
     * @notice Checks if a holding can be liquidated for a specific token.
     *
     * @notice Requirements:
     * - `_holding` must not be the zero address.
     * - There must be registry for `_token`.
     *
     * @param _token The token for which the check is done.
     * @param _holding The user address.
     *
     * @return flag indicating whether `holding` is liquidatable.
     */
    function isLiquidatable(address _token, address _holding) external view returns (bool);

    /**
     * @notice Computes the solvency ratio.
     *
     * @dev Solvency ratio is calculated based on the used collateral type, its collateralization and exchange rates,
     * and `_holding`'s borrowed amount.
     *
     * @param _holding The holding address to check for.
     * @param registry The Shares Registry Contract for the token.
     * @param rate The rate to compute ratio for (either collateralization rate for `isSolvent` or liquidation
     * threshold for `isLiquidatable`).
     *
     * @return The calculated solvency ratio.
     */
    function getRatio(address _holding, ISharesRegistry registry, uint256 rate) external view returns (uint256);
}
IStrategyManagerMin.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IStrategyManagerMin {
    /**
     * @notice Returns the strategy info.
     */
    function strategyInfo(
        address _strategy
    ) external view returns (uint256, bool, bool);
}
IOracle.sol 35 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IOracle {
    // -- State variables --

    /**
     * @notice Returns the address of the token the oracle is for.
     */
    function underlying() external view returns (address);

    // -- Functions --

    /**
     * @notice Returns a human readable name of the underlying of the oracle.
     */
    function name() external view returns (string memory);

    /**
     * @notice Returns a human readable symbol of the underlying of the oracle.
     */
    function symbol() external view returns (string memory);

    /**
     * @notice Check the last exchange rate without any state changes.
     *
     * @param data Implementation specific data that contains information and arguments to & about the oracle.
     *
     * @return success If no valid (recent) rate is available, returns false else true.
     * @return rate The rate of the requested asset / pair / pool.
     */
    function peek(
        bytes calldata data
    ) external view returns (bool success, uint256 rate);
}
OperationsLib.sol 27 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/**
 * @title Operations Library
 * @notice A library containing common mathematical operations used throughout the protocol
 */
library OperationsLib {
    /**
     * @notice The denominator used for fee calculations (10,000 = 100%)
     * @dev Fees are expressed in basis points, where 1 basis point = 0.01%
     *      For example, 100 = 1%, 500 = 5%, 1000 = 10%
     */
    uint256 internal constant FEE_FACTOR = 10_000;

    /**
     * @notice Calculates the absolute fee amount based on the input amount and fee rate
     * @dev The calculation rounds up to ensure the protocol always collects the full fee
     * @param amount The base amount on which the fee is calculated
     * @param fee The fee rate in basis points (e.g., 100 = 1%)
     * @return The absolute fee amount, rounded up if there's any remainder
     */
    function getFeeAbsolute(uint256 amount, uint256 fee) internal pure returns (uint256) {
        // Calculate fee amount with rounding up to avoid precision loss
        return (amount * fee) / FEE_FACTOR + (amount * fee % FEE_FACTOR == 0 ? 0 : 1);
    }
}

Read Contract

WETH 0xad5c4648 → address
holdingImplementationReference 0x222fa47c → address
holdingUser 0x6a7942e3 → address
isHolding 0xe3933ca6 → bool
manager 0x481c6a75 → address
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
pendingOwner 0xe30c3978 → address
renounceOwnership 0x715018a6
userHolding 0x66811411 → address

Write Contract 13 functions

These functions modify contract state and require a wallet transaction to execute.

acceptOwnership 0x79ba5097
No parameters
borrow 0x02d3dcd6
address _token
uint256 _amount
uint256 _minJUsdAmountOut
bool _mintDirectlyToUser
returns: uint256
borrowMultiple 0x1a117b57
tuple[] _data
bool _mintDirectlyToUser
returns: uint256[]
createHolding 0x68012a46
No parameters
returns: address
deposit 0x47e7ef24
address _token
uint256 _amount
pause 0x8456cb59
No parameters
repay 0xb561fd2b
address _token
uint256 _amount
bool _repayFromUser
repayMultiple 0xb6f081b1
tuple[] _data
bool _repayFromUser
transferOwnership 0xf2fde38b
address newOwner
unpause 0x3f4ba83a
No parameters
withdraw 0xf3fef3a3
address _token
uint256 _amount
withdrawAndUnwrap 0x3969dfb4
uint256 _amount
wrapAndDeposit 0x28b564a0
No parameters

Recent Transactions

No transactions found for this address