Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x2a20f2cE3f99a3C6D89Af0734325FD371b59BEc8
Balance 0 ETH
Nonce 1
Code Size 23355 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

23355 bytes
0x608060405260043610610432575f3560e01c80638152cd1811610227578063b460af9411610134578063d905777e116100b3578063ef8b30f711610078578063ef8b30f714610bd4578063f2fde38b14610cc9578063f4ad878814610ce8578063fa559a3514610cfd578063ffa1ad7414610d1c575f80fd5b8063d905777e14610c31578063d9f9027f14610c50578063dd62ed3e14610c64578063e3ea7c6a14610c83578063ed14d17e14610cb5575f80fd5b8063c63d75b6116100f9578063c63d75b614610b95578063c69bebe414610bb5578063c6e6f59214610bd4578063ce96cb7714610bf3578063d48bfca714610c12575f80fd5b8063b460af9414610af1578063ba08765214610b10578063ba8bfa2a14610b2f578063bf6590a414610b4e578063c0587a9514610b62575f80fd5b80639c5861b6116101c0578063ad35530b11610185578063ad35530b14610a4a578063b046a44914610a69578063b0caa89114610a88578063b2db983a14610ab3578063b3d7f6b914610ad2575f80fd5b80639c5861b6146109b85780639e65741e146109d7578063a7b73254146109eb578063a9059cbb14610a0a578063aa6ca80814610a29575f80fd5b80638152cd18146108ce5780638322fff2146108ed5780638456cb591461091457806388bb4f60146109285780638da5cb5b1461094957806394bf804d1461095d57806395d89b411461097c57806398e1862c146109905780639c016ffd146109a4575f80fd5b8063340691571161033f5780634b59b82e116102be5780636e553f65116102835780636e553f651461083e57806370a082311461085d578063715018a61461087c5780637a825e07146108905780637f6c81b7146108af575f80fd5b80634b59b82e146107cd5780634cdad506146104d9578063596384ae146107ec5780635c975abb1461080b5780635fa7b5841461081f575f80fd5b80633e9491a2116103045780633e9491a2146107125780633f4ba83a14610726578063402d267d1461073a578063439fab91146107595780634a8c110a14610778575f80fd5b8063340691571461067657806338d52e0f146106955780633b0426db146106b65780633bfaa7e3146106ca5780633c5280e4146106f3575f80fd5b8063175188e8116103cb578063266f8dc911610390578063266f8dc9146105ea57806329c23e4a146106095780632de10fab14610628578063313ce5671461063d57806332507a5f14610663575f80fd5b8063175188e81461056557806318160ddd1461058457806323b872dd146105985780632489f7f7146105b757806325bd4142146105cb575f80fd5b806301c704ba1461043d57806301e1d1141461045e578063030d624a1461048557806306fdde03146104a4578063079c3b88146104c557806307a2d13a146104d9578063095ea7b3146104f85780630a28a47714610527578063107703ab14610546575f80fd5b3661043957005b5f80fd5b348015610448575f80fd5b5061045c6104573660046141ca565b610d4a565b005b348015610469575f80fd5b50610472610dbb565b6040519081526020015b60405180910390f35b348015610490575f80fd5b5061045c61049f3660046141e3565b610e32565b3480156104af575f80fd5b506104b8610e9d565b60405161047c9190614228565b3480156104d0575f80fd5b50610472610f3b565b3480156104e4575f80fd5b506104726104f33660046141e3565b6110e1565b348015610503575f80fd5b5061051761051236600461423a565b6110f2565b604051901515815260200161047c565b348015610532575f80fd5b506104726105413660046141e3565b611109565b348015610551575f80fd5b5061045c610560366004614262565b611115565b348015610570575f80fd5b5061045c61057f3660046141ca565b611211565b34801561058f575f80fd5b506104726112fa565b3480156105a3575f80fd5b506105176105b236600461428c565b611310565b3480156105c2575f80fd5b50610472611335565b3480156105d6575f80fd5b5061045c6105e53660046141e3565b61133f565b3480156105f5575f80fd5b5061045c6106043660046141e3565b6113aa565b348015610614575f80fd5b506104726106233660046141e3565b611416565b348015610633575f80fd5b5061047260175481565b348015610648575f80fd5b50610651611433565b60405160ff909116815260200161047c565b6104726106713660046142c5565b61145c565b348015610681575f80fd5b5061045c6106903660046141e3565b61151d565b3480156106a0575f80fd5b506106a961158a565b60405161047c919061430f565b3480156106c1575f80fd5b506104726115a4565b3480156106d5575f80fd5b506106de6115d7565b6040805192835260208301919091520161047c565b3480156106fe575f80fd5b5061045c61070d3660046141e3565b61188d565b34801561071d575f80fd5b50601254610472565b348015610731575f80fd5b5061045c6118fa565b348015610745575f80fd5b506104726107543660046141ca565b61190c565b348015610764575f80fd5b5061045c610773366004614367565b611922565b348015610783575f80fd5b5061078c611ddb565b60405161047c91905f60a082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015292915050565b3480156107d8575f80fd5b506106a96107e73660046141e3565b611e3d565b3480156107f7575f80fd5b5061045c6108063660046141e3565b611e48565b348015610816575f80fd5b50610517611ea2565b34801561082a575f80fd5b5061045c6108393660046141ca565b611eb6565b348015610849575f80fd5b50610472610858366004614262565b611ef9565b348015610868575f80fd5b506104726108773660046141ca565b611f9b565b348015610887575f80fd5b5061045c611fc4565b34801561089b575f80fd5b5061045c6108aa3660046141ca565b611fd5565b3480156108ba575f80fd5b5061045c6108c93660046141e3565b61206d565b3480156108d9575f80fd5b5061045c6108e83660046143a5565b6120d8565b3480156108f8575f80fd5b506106a973eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b34801561091f575f80fd5b5061045c612186565b348015610933575f80fd5b5061093c6121e0565b60405161047c91906143c5565b348015610954575f80fd5b506106a961242a565b348015610968575f80fd5b50610472610977366004614262565b612452565b348015610987575f80fd5b506104b861246d565b34801561099b575f80fd5b50601154610472565b3480156109af575f80fd5b5061045c612489565b3480156109c3575f80fd5b5061045c6109d23660046141e3565b612573565b3480156109e2575f80fd5b50601054610472565b3480156109f6575f80fd5b50610472610a053660046144cf565b6125ed565b348015610a15575f80fd5b50610517610a2436600461423a565b6127df565b348015610a34575f80fd5b50610a3d6127ec565b60405161047c9190614522565b348015610a55575f80fd5b5061045c610a6436600461456e565b6127f8565b348015610a74575f80fd5b5061045c610a833660046141ca565b6128cc565b348015610a93575f80fd5b50610472610aa23660046141ca565b60026020525f908152604090205481565b348015610abe575f80fd5b50610472610acd3660046141e3565b612967565b348015610add575f80fd5b50610472610aec3660046141e3565b6129d2565b348015610afc575f80fd5b50610472610b0b3660046145c3565b6129de565b348015610b1b575f80fd5b50610472610b2a3660046145c3565b612a04565b348015610b3a575f80fd5b5061045c610b493660046145fc565b612a20565b348015610b59575f80fd5b50610472612d44565b348015610b6d575f80fd5b507f4995646f72fa9a270ffc094641ab616ce576b2e3eab25eaf05c15caa4f0e595d5c610472565b348015610ba0575f80fd5b50610472610baf3660046141ca565b505f1990565b348015610bc0575f80fd5b5061045c610bcf3660046141ca565b612df9565b348015610bdf575f80fd5b50610472610bee3660046141e3565b612e91565b348015610bfe575f80fd5b50610472610c0d3660046141ca565b612e9c565b348015610c1d575f80fd5b5061045c610c2c3660046141ca565b612eaf565b348015610c3c575f80fd5b50610472610c4b3660046141ca565b612f19565b348015610c5b575f80fd5b50610a3d612f23565b348015610c6f575f80fd5b50610472610c7e36600461462c565b612f2e565b348015610c8e575f80fd5b507f0000000000000000000000000000000000000000000000000de0b6b3a7640000610472565b348015610cc0575f80fd5b5061045c612f68565b348015610cd4575f80fd5b5061045c610ce33660046141ca565b612feb565b348015610cf3575f80fd5b5061047261271081565b348015610d08575f80fd5b506018546106a9906001600160a01b031681565b348015610d27575f80fd5b506104b8604051806040016040528060038152602001620312e360ec1b81525081565b610d52613025565b6018546040517f65c8da338cfcbb5abedd2f9099bb2a2bdf31ffc65d130e715901eeb06b205cdf91610d91916001600160a01b03909116908490614654565b60405180910390a1601880546001600160a01b0319166001600160a01b0392909216919091179055565b6009546014545f9190610dce9042614682565b1115610ded57604051631f4bcb2b60e01b815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000de0b6b3a7640000610e166112fa565b601054610e239190614695565b610e2d91906146c0565b905090565b610e3a613025565b6004811115610e5c576040516309aa66eb60e01b815260040160405180910390fd5b60075460408051918252602082018390527f29b9d7a7d8a7a3ac22c295e4517723bc4e386eea60173e59e6da1dbd460cb409910160405180910390a1600755565b60605f610ea8613057565b9050806003018054610eb9906146d3565b80601f0160208091040260200160405190810160405280929190818152602001828054610ee5906146d3565b8015610f305780601f10610f0757610100808354040283529160200191610f30565b820191905f5260205f20905b815481529060010190602001808311610f1357829003601f168201915b505050505091505090565b5f805f80610f47611433565b90505f5b610f55601561307b565b8110156110b457610f67601582613084565b92505f836001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610f96919061430f565b602060405180830381865afa158015610fb1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fd5919061470b565b90505f846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611014573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110389190614722565b90508360ff168160ff16111561106e576110528482614742565b61105d90600a61483b565b61106790836146c0565b915061109e565b8360ff168160ff16101561109e576110868185614742565b61109190600a61483b565b61109b9083614695565b91505b6110a88287614849565b95505050600101610f4b565b505f6110be612d44565b6012549091506110ce8583614849565b6110d89190614682565b94505050505090565b5f6110ec825f61308f565b92915050565b5f336110ff8185856130cc565b5060019392505050565b5f6110ec8260016130de565b61111d613112565b61112561315c565b815f0361114557604051637ea773a960e01b815260040160405180910390fd5b600f5461115d9033906001600160a01b031684613182565b600f546040516336c69b5d60e11b81526001600160a01b0390911690636d8d36ba9061118f903390869060040161485c565b5f604051808303815f87803b1580156111a6575f80fd5b505af11580156111b8573d5f803e3d5ffd5b505060408051338152602081018690526001600160a01b0385168183015290517ff9fd31dd1a61b95c600dd5aa1a6330f6c5cbe70a39a660edc081daf217db3cfb9350908190036060019150a161120d6131df565b5050565b611219613025565b5f816001600160a01b03166308bb5fb06040518163ffffffff1660e01b81526004016020604051808303815f875af1158015611257573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127b919061470b565b111561129a5760405163e9ec812960e01b815260040160405180910390fd5b6112a45f82613205565b506001600160a01b0381165f9081526002602052604080822091909155517fd3281a40d50ae838fe77dc627744037b8f0fc6a5711d66119a9b670c5cde41af906112ef90839061430f565b60405180910390a150565b5f601754611306613219565b610e2d9190614682565b5f3361131d85828561322d565b611328858585613182565b60019150505b9392505050565b5f610e2d5f61307b565b611347613025565b60788111156113695760405163f4d1caab60e01b815260040160405180910390fd5b600b5460408051918252602082018390527f394967f6fe403cda0905b23e81b928c5ca79107000b1404c6b3185442f05213c910160405180910390a1600b55565b6113b2613025565b6105dc8111156113d557604051630674143f60e01b815260040160405180910390fd5b600a5460408051918252602082018390527f63058ed61801434ac6bfe39e74400bed7f3ba09b7cb6294092974450727eb753910160405180910390a1600a55565b600b545f90612710906114299084614695565b6110ec91906146c0565b5f8061143d61327d565b90505f81546114569190600160a01b900460ff16614875565b91505090565b5f611465613112565b61146d61315c565b61147561158a565b6001600160a01b0316856001600160a01b0316146114a6576040516317dc37cb60e11b815260040160405180910390fd5b6114b084846132a1565b604080513381526001600160a01b038089166020830152918101879052818616606082015290841660808201529091507f308d36d8f61bd4393536b6557142f55554c34d4ea2a3dbf54fe782b98889dfb29060a00160405180910390a16115156131df565b949350505050565b611525613025565b621275008111156115495760405163e88d3ecb60e01b815260040160405180910390fd5b60095460408051918252602082018390527fcc5a4a7c466fc20af4119a7a26048791fdb55cbd401aff36ef2bfc639662b2e2910160405180910390a1600955565b5f8061159461327d565b546001600160a01b031692915050565b6014545f9081906115b59042614682565b905080600360060154116115c9575f611456565b600954611456908290614682565b600d545f9081906001600160a01b031633146116065760405163bd72e29160e01b815260040160405180910390fd5b601054611634907f4995646f72fa9a270ffc094641ab616ce576b2e3eab25eaf05c15caa4f0e595d906132ed565b426014555f6116416112fa565b9050805f036116595750506010546012549091509091565b5f611662610f3b565b90508161168f7f0000000000000000000000000000000000000000000000000de0b6b3a764000083614695565b61169991906146c0565b6011549094508411156117db576011545f036116c357505050601181905560108190556012549091565b5f7f0000000000000000000000000000000000000000000000000de0b6b3a7640000836010600101546116f69190614695565b61170091906146c0565b61170a9083614682565b600a549091506127109061171e9083614695565b61172891906146c0565b93508360106002015f82825461173e9190614849565b9091555050601054837f0000000000000000000000000000000000000000000000000de0b6b3a76400006117728786614682565b61177c9190614695565b61178691906146c0565b601055612710611797606483614695565b6117a191906146c0565b6010546117af908390614682565b11156117ce57604051630508c93960e41b815260040160405180910390fd5b505060105460115561184e565b5f8460105f0154116117f9576010546117f49086614682565b611807565b601054611807908690614682565b9050612710606460105f015461181d9190614695565b61182791906146c0565b81111561184757604051630508c93960e41b815260040160405180910390fd5b5060108490555b60408051858152602081018590527f83d2ad38a3d31bbc70811535dd8943b0140df344c23e6e167ee1ca32f9a1a459910160405180910390a150509091565b611895613025565b62093a808110156118b957604051632011727b60e11b815260040160405180910390fd5b60085460408051918252602082018390527fcdbf56e2a82365307f9691ad933e9762726485d202543fe224f47447d79feaf0910160405180910390a1600855565b611902613025565b61190a6132f4565b565b5f611915610dbb565b6006546110ec9190614682565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b03165f811580156119665750825b90505f826001600160401b031660011480156119815750303b155b90508115801561198f575080155b156119ad5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156119d757845460ff60401b1916600160401b1785555b5f806119e5888a018a6149e9565b915091506119f161333f565b6119f961334f565b611a0b8260200151836040015161335f565b81516001600160a01b0316611a33576040516317dc37cb60e11b815260040160405180910390fd5b6101408201516001600160a01b0316611a62576040516001626bbab960e11b0319815260040160405180910390fd5b6101208201516001600160a01b0316611a8e57604051630b5eba9f60e41b815260040160405180910390fd5b6101608201516001600160a01b0316611aba57604051633480121760e21b815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000de0b6b3a764000082606001511015611aff57604051633240d18160e21b815260040160405180910390fd5b600482608001511115611b25576040516309aa66eb60e01b815260040160405180910390fd5b62093a808260a001511015611b4d57604051632011727b60e11b815260040160405180910390fd5b621275008260c001511115611b755760405163e88d3ecb60e01b815260040160405180910390fd5b6105dc8260e001511115611b9c57604051630674143f60e01b815260040160405180910390fd5b60788261010001511115611bc35760405163f4d1caab60e01b815260040160405180910390fd5b611bd1826101200151613371565b8151611bdc90613382565b4260138190556014557f0000000000000000000000000000000000000000000000000de0b6b3a76400006010558151600380546001600160a01b0319166001600160a01b039092169190911781556020830151839190600490611c3f9082614b73565b5060408201516002820190611c549082614b73565b50606082015160038201556080820151600482015560a0820151600582015560c0820151600682015560e0820151600782015561010082015160088201556101208201516009820180546001600160a01b03199081166001600160a01b0393841617909155610140840151600a840180548316918416919091179055610160840151600b84018054831691841691909117905561018090930151600c909201805490931691161790555f5b8151811015611d89575f6001600160a01b0316828281518110611d2457611d24614c32565b60200260200101516001600160a01b031603611d53576040516317dc37cb60e11b815260040160405180910390fd5b611d80828281518110611d6857611d68614c32565b6020026020010151601561339390919063ffffffff16565b50600101611cff565b5050508315611dd257845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b611e086040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b506040805160a08101825260105481526011546020820152601254918101919091526013546060820152601454608082015290565b5f6110ec8183613084565b6018546001600160a01b03163314611e7357604051632f771b3d60e11b815260040160405180910390fd5b8060175f828254611e849190614849565b9091555050601854611e9f906001600160a01b0316826133a7565b50565b5f80611eac6133db565b5460ff1692915050565b611ebe613025565b611ec9601582613205565b507f4eb129c82dcd3eedb52df2b0e6fb4cfa41ac64ee9d63ff081acbb1877e85d79b816040516112ef919061430f565b5f611f02613112565b611f0a61315c565b5f198303611f8757611f1a61158a565b6001600160a01b03166370a08231336040518263ffffffff1660e01b8152600401611f45919061430f565b602060405180830381865afa158015611f60573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f84919061470b565b92505b611f9183836132a1565b90506110ec6131df565b5f80611fa5613057565b6001600160a01b039093165f9081526020939093525050604090205490565b611fcc613025565b61190a5f6133ff565b611fdd613025565b6001600160a01b0381166120045760405163d214a59760e01b815260040160405180910390fd5b600f546040517fe74dd8b1f5f3d5328df682e649c08b085f09c2ce77b68e54329e8d30e2642f7891612043916001600160a01b03909116908490614654565b60405180910390a1600f80546001600160a01b0319166001600160a01b0392909216919091179055565b612075613025565b60065481116120975760405163e9ec812960e01b815260040160405180910390fd5b60065460408051918252602082018390527f7f3306669f28a6aa13d0f709be2bd4f3e21d2f37aee9358846a50e1988ee4832910160405180910390a1600655565b6120e0613025565b8015806120ee575061271081115b1561210c5760405163e55fb50960e01b815260040160405180910390fd5b5f6121178184613084565b6001600160a01b0381165f908152600260209081526040918290205482519081529081018590529192507f7cd01dd3533c6dc08821cd303814de60aba1901f1531c3cbcd95d26ed924e9cf910160405180910390a16001600160a01b03165f9081526002602052604090205550565b61218e61242a565b6001600160a01b0316336001600160a01b0316141580156121ba5750600d546001600160a01b03163314155b156121d85760405163e9ec812960e01b815260040160405180910390fd5b61190a61346f565b61226d604051806101a001604052805f6001600160a01b0316815260200160608152602001606081526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681525090565b604080516101a08101909152600380546001600160a01b031682526004805460208401919061229b906146d3565b80601f01602080910402602001604051908101604052809291908181526020018280546122c7906146d3565b80156123125780601f106122e957610100808354040283529160200191612312565b820191905f5260205f20905b8154815290600101906020018083116122f557829003601f168201915b5050505050815260200160028201805461232b906146d3565b80601f0160208091040260200160405190810160405280929190818152602001828054612357906146d3565b80156123a25780601f10612379576101008083540402835291602001916123a2565b820191905f5260205f20905b81548152906001019060200180831161238557829003601f168201915b505050918352505060038201546020820152600482015460408201526005820154606082015260068201546080820152600782015460a0820152600882015460c082015260098201546001600160a01b0390811660e0830152600a8301548116610100830152600b8301548116610120830152600c9092015490911661014090910152919050565b5f807f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300611594565b5f61245b613112565b61246361315c565b611f9183836134b5565b60605f612478613057565b9050806004018054610eb9906146d3565b600e546001600160a01b031633146124b457604051633480121760e21b815260040160405180910390fd5b6008546013544291906124c79083614682565b10156124e657604051631221b97b60e01b815260040160405180910390fd5b60138190556007545f90612710906124fc610dbb565b6125069190614695565b61251091906146c0565b600e5490915061253c906001600160a01b03168261252c61158a565b6001600160a01b031691906134d0565b6040518181527f55ce6141cc7099e5baac44c64543a6d7fc4e37ebba0fcaa65fa1f2a9996ec5a59060200160405180910390a15050565b6018546001600160a01b0316331461259e57604051632f771b3d60e11b815260040160405180910390fd5b6017548111156125c157604051636edcc52360e01b815260040160405180910390fd5b8060175f8282546125d29190614682565b9091555050601854611e9f906001600160a01b031682613528565b5f6125f6613112565b6125fe61315c565b61260960158761355c565b61262657604051636448d6e960e11b815260040160405180910390fd5b600f546001600160a01b031633146126515760405163e9ec812960e01b815260040160405180910390fd5b601454421461267357604051631f4bcb2b60e01b815260040160405180910390fd5b5f19850361268b5761268482612f19565b94506126e8565b61269482612f19565b8511156126e85760405162461bcd60e51b815260206004820152601d60248201527f455243343632363a2072656465656d206d6f7265207468616e206d617800000060448201526064015b60405180910390fd5b336001600160a01b038316146127035761270382338761322d565b5f6127467f0000000000000000000000000000000000000000000000000de0b6b3a76400006127328782614682565b61273c9089614695565b6104f391906146c0565b90506127528387613528565b61275b81611416565b6127659082614682565b915061277b6001600160a01b03881685846134d0565b604080516001600160a01b03898116825260208201899052868116828401528516606082015290517f4e19afb1df46d77083cc4e520735afa0cdc2d763d6bc5d710661c3dbb35f4c4d9181900360800190a1506127d66131df565b95945050505050565b5f336110ff818585613182565b6060610e2d601561357d565b612800613025565b80158061280e575061271081115b1561282c5760405163e55fb50960e01b815260040160405180910390fd5b5f8433858560405161283d906141a2565b61284a9493929190614c46565b604051809103905ff080158015612863573d5f803e3d5ffd5b506001600160a01b0381165f90815260026020526040812084905590915061288b9082613393565b507f0803371633b57311f58d10924711080d2dae75ab17c5c0c262af3887cfca00bb81866040516128bd929190614654565b60405180910390a15050505050565b6128d4613025565b6001600160a01b0381166128fe576040516001626bbab960e11b0319815260040160405180910390fd5b600d546040517fe2eeab472f89ac267be30e463da684fb96f56cc8e947839361fdf45bf6a3458e9161293d916001600160a01b03909116908490614654565b60405180910390a1600d80546001600160a01b0319166001600160a01b0392909216919091179055565b5f6129728183613084565b6001600160a01b03166308bb5fb06040518163ffffffff1660e01b81526004016020604051808303815f875af11580156129ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110ec919061470b565b5f6110ec82600161308f565b5f6129e7613112565b6129ef61315c565b6129fa848484613589565b905061132e6131df565b5f612a0d613112565b612a1561315c565b6129fa8484846135d6565b335f829003612a8357612a3161242a565b6001600160a01b0316816001600160a01b031614158015612a605750600d546001600160a01b03828116911614155b15612a7e5760405163ccea9e6f60e01b815260040160405180910390fd5b612abc565b612a8b61242a565b6001600160a01b0316816001600160a01b031614612abc5760405163ccea9e6f60e01b815260040160405180910390fd5b5f612ac683611e3d565b6001600160a01b0381165f818152600260209081526040808320548151628bb5fb60e41b81529151959650949293926308bb5fb092600480840193919291829003018187875af1158015612b1c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b40919061470b565b90505f612b4b611433565b90505f886001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b8a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bae9190614722565b90508760ff8084169083161115612be557612bc98383614742565b612bd490600a61483b565b612bde908a6146c0565b9050612c15565b8260ff168260ff161015612c1557612bfd8284614742565b612c0890600a61483b565b612c12908a614695565b90505b61271085612c21610dbb565b612c2b9190614695565b612c3591906146c0565b612c3f8286614849565b1115612c5e5760405163e55fb50960e01b815260040160405180910390fd5b612c726001600160a01b038b16878b613623565b6040516356f4edaf60e01b81526001600160a01b038716906356f4edaf90612ca0908d908d9060040161485c565b6020604051808303815f875af1158015612cbc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ce09190614c90565b612cfd57604051630508c93960e41b815260040160405180910390fd5b7f921f9e77ef648025190d46d8b7f3d22a5546367ff7aaa883b1f39ffd2a2d325d8a8a8a604051612d3093929190614caf565b60405180910390a150505050505050505050565b5f80612d4e611335565b90505f612d59612f23565b90505f5b82811015612df357818181518110612d7757612d77614c32565b60200260200101516001600160a01b03166308bb5fb06040518163ffffffff1660e01b81526004016020604051808303815f875af1158015612dbb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ddf919061470b565b612de99085614849565b9350600101612d5d565b50505090565b612e01613025565b6001600160a01b038116612e2857604051633480121760e21b815260040160405180910390fd5b600e546040517f2861448678f0be67f11bfb5481b3e3b4cfeb3acc6126ad60a05f95bfc653066691612e67916001600160a01b03909116908490614654565b60405180910390a1600e80546001600160a01b0319166001600160a01b0392909216919091179055565b5f6110ec825f6130de565b5f6110ec612ea983611f9b565b5f61308f565b612eb7613025565b6001600160a01b038116612ede576040516317dc37cb60e11b815260040160405180910390fd5b612ee9601582613393565b507fe473c74f34be27c1464d6624f14a0d7fd4e301cbfa29c3eba425d378c8a7ebe0816040516112ef919061430f565b5f6110ec82611f9b565b6060610e2d5f61357d565b5f80612f38613057565b6001600160a01b039485165f90815260019190910160209081526040808320959096168252939093525050205490565b600e546001600160a01b03163314612f9357604051633480121760e21b815260040160405180910390fd5b600e54601254612faf916001600160a01b03169061252c61158a565b6012546040519081527f8a2034f45f83800eed1750a670ad845ceee6add62106ca5326598842cfbd6ea79060200160405180910390a15f601255565b612ff3613025565b6001600160a01b03811661301c575f604051631e4fbdf760e01b81526004016126df919061430f565b611e9f816133ff565b3361302e61242a565b6001600160a01b03161461190a573360405163118cdaa760e01b81526004016126df919061430f565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0090565b5f6110ec825490565b5f61132e83836136a8565b5f61132e61309b610dbb565b6130a6906001614849565b6130b15f600a61483b565b6130b96112fa565b6130c39190614849565b859190856136ce565b6130d9838383600161371b565b505050565b5f61132e6130ed82600a61483b565b6130f56112fa565b6130ff9190614849565b613107610dbb565b6130c3906001614849565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0080546001190161315657604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b613164611ea2565b1561190a5760405163d93c066560e01b815260040160405180910390fd5b6001600160a01b0383166131ab575f604051634b637e8f60e11b81526004016126df919061430f565b6001600160a01b0382166131d4575f60405163ec442f0560e01b81526004016126df919061430f565b6130d98383836137fc565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b5f61132e836001600160a01b03841661391f565b5f80613223613057565b6002015492915050565b5f6132388484612f2e565b90505f198114613277578181101561326957828183604051637dc7a0d960e11b81526004016126df93929190614caf565b61327784848484035f61371b565b50505050565b7f0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e0090565b5f806132ac8361190c565b9050808411156132d557828482604051633c8097d960e11b81526004016126df93929190614caf565b5f6132df85612e91565b905061151533858784613a02565b80825d5050565b6132fc613a7d565b5f6133056133db565b805460ff1916815590507f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516112ef919061430f565b613347613aa2565b61190a613aeb565b613357613aa2565b61190a613b07565b613367613aa2565b61120d8282613b0f565b613379613aa2565b611e9f81613b3f565b61338a613aa2565b611e9f81613b47565b5f61132e836001600160a01b038416613bb4565b6001600160a01b0382166133d0575f60405163ec442f0560e01b81526004016126df919061430f565b61120d5f83836137fc565b7fcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f0330090565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b61347761315c565b5f6134806133db565b805460ff1916600117815590507f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586133323390565b5f5f195f6134c2856129d2565b905061151533858388613a02565b6130d983846001600160a01b031663a9059cbb85856040516024016134f692919061485c565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613c00565b6001600160a01b038216613551575f604051634b637e8f60e11b81526004016126df919061430f565b61120d825f836137fc565b6001600160a01b0381165f908152600183016020526040812054151561132e565b60605f61132e83613c58565b5f8061359483612e9c565b9050808511156135bd57828582604051633fa733bb60e21b81526004016126df93929190614caf565b5f6135c786611109565b90506127d63386868985613cb1565b5f806135e183612f19565b90508085111561360a57828582604051632e52afbb60e21b81526004016126df93929190614caf565b5f613614866110e1565b90506127d6338686848a613cb1565b604051636eb1769f60e11b81525f906001600160a01b0385169063dd62ed3e906136539030908790600401614654565b602060405180830381865afa15801561366e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613692919061470b565b905061327784846136a38585614849565b613d68565b5f825f0182815481106136bd576136bd614c32565b905f5260205f200154905092915050565b5f806136db868686613df8565b90506136e683613eb7565b801561370157505f84806136fc576136fc6146ac565b868809115b156127d657613711600182614849565b9695505050505050565b5f613724613057565b90506001600160a01b03851661374f575f60405163e602df0560e01b81526004016126df919061430f565b6001600160a01b038416613778575f604051634a1406b160e11b81526004016126df919061430f565b6001600160a01b038086165f908152600183016020908152604080832093881683529290522083905581156137f557836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040516137ec91815260200190565b60405180910390a35b5050505050565b5f613805613057565b90506001600160a01b0384166138335781816002015f8282546138289190614849565b909155506138909050565b6001600160a01b0384165f90815260208290526040902054828110156138725784818460405163391434e360e21b81526004016126df93929190614caf565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b0383166138ae5760028101805483900390556138cc565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161391191815260200190565b60405180910390a350505050565b5f81815260018301602052604081205480156139f9575f613941600183614682565b85549091505f9061395490600190614682565b90508082146139b3575f865f01828154811061397257613972614c32565b905f5260205f200154905080875f01848154811061399257613992614c32565b5f918252602080832090910192909255918252600188019052604090208390555b85548690806139c4576139c4614cd0565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f9055600193505050506110ec565b5f9150506110ec565b5f613a0b61327d565b8054909150613a25906001600160a01b0316863086613ee3565b613a2f84836133a7565b836001600160a01b0316856001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d785856040516137ec929190918252602082015260400190565b613a85611ea2565b61190a57604051638dfc202b60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff1661190a57604051631afcd79f60e31b815260040160405180910390fd5b613af3613aa2565b5f613afc6133db565b805460ff1916905550565b6131df613aa2565b613b17613aa2565b5f613b20613057565b905060038101613b308482614b73565b50600481016132778382614b73565b612ff3613aa2565b613b4f613aa2565b5f613b5861327d565b90505f80613b6584613f1c565b9150915081613b75576012613b77565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b5f818152600183016020526040812054613bf957508154600181810184555f8481526020808220909301849055845484825282860190935260409020919091556110ec565b505f6110ec565b5f613c146001600160a01b03841683613ff2565b905080515f14158015613c38575080806020019051810190613c369190614c90565b155b156130d95782604051635274afe760e01b81526004016126df919061430f565b6060815f01805480602002602001604051908101604052809291908181526020018280548015613ca557602002820191905f5260205f20905b815481526020019060010190808311613c91575b50505050509050919050565b5f613cba61327d565b9050836001600160a01b0316866001600160a01b031614613ce057613ce084878461322d565b613cea8483613528565b8054613d00906001600160a01b031686856134d0565b836001600160a01b0316856001600160a01b0316876001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8686604051613d58929190918252602082015260400190565b60405180910390a4505050505050565b5f836001600160a01b031663095ea7b38484604051602401613d8b92919061485c565b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050509050613dc48482613fff565b61327757613dee84856001600160a01b031663095ea7b3865f6040516024016134f692919061485c565b6132778482613c00565b5f838302815f1985870982811083820303915050805f03613e2c57838281613e2257613e226146ac565b049250505061132e565b808411613e4c5760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f6002826003811115613ecc57613ecc614ce4565b613ed69190614cf8565b60ff166001149050919050565b6040516001600160a01b0384811660248301528381166044830152606482018390526132779186918216906323b872dd906084016134f6565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b03871691613f6291614d19565b5f60405180830381855afa9150503d805f8114613f9a576040519150601f19603f3d011682016040523d82523d5f602084013e613f9f565b606091505b5091509150818015613fb357506020815110155b15613fe6575f81806020019051810190613fcd919061470b565b905060ff8111613fe4576001969095509350505050565b505b505f9485945092505050565b606061132e83835f61409c565b5f805f846001600160a01b03168460405161401a9190614d19565b5f604051808303815f865af19150503d805f8114614053576040519150601f19603f3d011682016040523d82523d5f602084013e614058565b606091505b50915091508180156140825750805115806140825750808060200190518101906140829190614c90565b80156127d65750505050506001600160a01b03163b151590565b6060814710156140c1573060405163cd78605960e01b81526004016126df919061430f565b5f80856001600160a01b031684866040516140dc9190614d19565b5f6040518083038185875af1925050503d805f8114614116576040519150601f19603f3d011682016040523d82523d5f602084013e61411b565b606091505b509150915061371186838360608261413b5761413682614179565b61132e565b815115801561415257506001600160a01b0384163b155b156141725783604051639996b31560e01b81526004016126df919061430f565b508061132e565b8051156141895780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b610dd680614d3083390190565b80356001600160a01b03811681146141c5575f80fd5b919050565b5f602082840312156141da575f80fd5b61132e826141af565b5f602082840312156141f3575f80fd5b5035919050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f61132e60208301846141fa565b5f806040838503121561424b575f80fd5b614254836141af565b946020939093013593505050565b5f8060408385031215614273575f80fd5b82359150614283602084016141af565b90509250929050565b5f805f6060848603121561429e575f80fd5b6142a7846141af565b92506142b5602085016141af565b9150604084013590509250925092565b5f805f80608085870312156142d8575f80fd5b6142e1856141af565b9350602085013592506142f6604086016141af565b9150614304606086016141af565b905092959194509250565b6001600160a01b0391909116815260200190565b5f8083601f840112614333575f80fd5b5081356001600160401b03811115614349575f80fd5b602083019150836020828501011115614360575f80fd5b9250929050565b5f8060208385031215614378575f80fd5b82356001600160401b0381111561438d575f80fd5b61439985828601614323565b90969095509350505050565b5f80604083850312156143b6575f80fd5b50508035926020909101359150565b602081526143df6020820183516001600160a01b03169052565b5f60208301516101a08060408501526143fc6101c08501836141fa565b91506040850151601f1985840301606086015261441983826141fa565b92505060608501516080850152608085015160a085015260a085015160c085015260c085015160e085015260e085015161010081818701528087015191505061012081818701528087015191505061014061447e818701836001600160a01b03169052565b860151905061016061449a868201836001600160a01b03169052565b86015190506101806144b6868201836001600160a01b03169052565b909501516001600160a01b031693019290925250919050565b5f805f805f60a086880312156144e3575f80fd5b6144ec866141af565b94506020860135935060408601359250614508606087016141af565b9150614516608087016141af565b90509295509295909350565b602080825282518282018190525f9190848201906040850190845b818110156145625783516001600160a01b03168352928401929184019160010161453d565b50909695505050505050565b5f805f8060608587031215614581575f80fd5b61458a856141af565b935060208501356001600160401b038111156145a4575f80fd5b6145b087828801614323565b9598909750949560400135949350505050565b5f805f606084860312156145d5575f80fd5b833592506145e5602085016141af565b91506145f3604085016141af565b90509250925092565b5f805f6060848603121561460e575f80fd5b614617846141af565b95602085013595506040909401359392505050565b5f806040838503121561463d575f80fd5b614646836141af565b9150614283602084016141af565b6001600160a01b0392831681529116602082015260400190565b634e487b7160e01b5f52601160045260245ffd5b818103818111156110ec576110ec61466e565b80820281158282048414176110ec576110ec61466e565b634e487b7160e01b5f52601260045260245ffd5b5f826146ce576146ce6146ac565b500490565b600181811c908216806146e757607f821691505b60208210810361470557634e487b7160e01b5f52602260045260245ffd5b50919050565b5f6020828403121561471b575f80fd5b5051919050565b5f60208284031215614732575f80fd5b815160ff8116811461132e575f80fd5b60ff82811682821603908111156110ec576110ec61466e565b600181815b8085111561479557815f190482111561477b5761477b61466e565b8085161561478857918102915b93841c9390800290614760565b509250929050565b5f826147ab575060016110ec565b816147b757505f6110ec565b81600181146147cd57600281146147d7576147f3565b60019150506110ec565b60ff8411156147e8576147e861466e565b50506001821b6110ec565b5060208310610133831016604e8410600b8410161715614816575081810a6110ec565b614820838361475b565b805f19048211156148335761483361466e565b029392505050565b5f61132e60ff84168361479d565b808201808211156110ec576110ec61466e565b6001600160a01b03929092168252602082015260400190565b60ff81811683821601908111156110ec576110ec61466e565b634e487b7160e01b5f52604160045260245ffd5b6040516101a081016001600160401b03811182821017156148c5576148c561488e565b60405290565b604051601f8201601f191681016001600160401b03811182821017156148f3576148f361488e565b604052919050565b5f82601f83011261490a575f80fd5b81356001600160401b038111156149235761492361488e565b614936601f8201601f19166020016148cb565b81815284602083860101111561494a575f80fd5b816020850160208301375f918101602001919091529392505050565b5f82601f830112614975575f80fd5b813560206001600160401b038211156149905761499061488e565b8160051b61499f8282016148cb565b92835284810182019282810190878511156149b8575f80fd5b83870192505b848310156149de576149cf836141af565b825291830191908301906149be565b979650505050505050565b5f80604083850312156149fa575f80fd5b82356001600160401b0380821115614a10575f80fd5b908401906101a08287031215614a24575f80fd5b614a2c6148a2565b614a35836141af565b8152602083013582811115614a48575f80fd5b614a54888286016148fb565b602083015250604083013582811115614a6b575f80fd5b614a77888286016148fb565b604083015250606083013560608201526080830135608082015260a083013560a082015260c083013560c082015260e083013560e0820152610100808401358183015250610120614ac98185016141af565b90820152610140614adb8482016141af565b90820152610160614aed8482016141af565b90820152610180614aff8482016141af565b9082015293506020850135915080821115614b18575f80fd5b50614b2585828601614966565b9150509250929050565b601f8211156130d957805f5260205f20601f840160051c81016020851015614b545750805b601f840160051c820191505b818110156137f5575f8155600101614b60565b81516001600160401b03811115614b8c57614b8c61488e565b614ba081614b9a84546146d3565b84614b2f565b602080601f831160018114614bd3575f8415614bbc5750858301515b5f19600386901b1c1916600185901b178555614c2a565b5f85815260208120601f198616915b82811015614c0157888601518255948401946001909101908401614be2565b5085821015614c1e57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b634e487b7160e01b5f52603260045260245ffd5b6001600160a01b0385811682528416602082015260606040820181905281018290525f828460808401375f608084840101526080601f19601f850116830101905095945050505050565b5f60208284031215614ca0575f80fd5b8151801515811461132e575f80fd5b6001600160a01b039390931683526020830191909152604082015260600190565b634e487b7160e01b5f52603160045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b5f60ff831680614d0a57614d0a6146ac565b8060ff84160691505092915050565b5f82518060208501845e5f92019182525091905056fe60a0604052604051610dd6380380610dd68339810160408190526100229161036a565b828161002e828261008c565b50508160405161003d9061032e565b6001600160a01b039091168152602001604051809103905ff080158015610066573d5f803e3d5ffd5b506001600160a01b031660805261008461007f60805190565b6100ea565b50505061044b565b61009582610157565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156100de576100d982826101d5565b505050565b6100e6610248565b5050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6101295f80516020610db6833981519152546001600160a01b031690565b604080516001600160a01b03928316815291841660208301520160405180910390a161015481610269565b50565b806001600160a01b03163b5f0361019157604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5b80546001600160a01b0319166001600160a01b039290921691909117905550565b60605f80846001600160a01b0316846040516101f19190610435565b5f60405180830381855af49150503d805f8114610229576040519150601f19603f3d011682016040523d82523d5f602084013e61022e565b606091505b50909250905061023f8583836102a6565b95945050505050565b34156102675760405163b398979f60e01b815260040160405180910390fd5b565b6001600160a01b03811661029257604051633173bdd160e11b81525f6004820152602401610188565b805f80516020610db68339815191526101b4565b6060826102bb576102b682610305565b6102fe565b81511580156102d257506001600160a01b0384163b155b156102fb57604051639996b31560e01b81526001600160a01b0385166004820152602401610188565b50805b9392505050565b8051156103155780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b610501806108b583390190565b80516001600160a01b0381168114610351575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b5f805f6060848603121561037c575f80fd5b6103858461033b565b92506103936020850161033b565b60408501519092506001600160401b03808211156103af575f80fd5b818601915086601f8301126103c2575f80fd5b8151818111156103d4576103d4610356565b604051601f8201601f19908116603f011681019083821181831017156103fc576103fc610356565b81604052828152896020848701011115610414575f80fd5b8260208601602083015e5f6020848301015280955050505050509250925092565b5f82518060208501845e5f920191825250919050565b6080516104536104625f395f601001526104535ff3fe608060405261000c61000e565b005b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330361007a575f356001600160e01b03191663278f794360e11b14610070576040516334ad5dbb60e21b815260040160405180910390fd5b610078610082565b565b6100786100b0565b5f806100913660048184610303565b81019061009e919061033e565b915091506100ac82826100c0565b5050565b6100786100bb61011a565b610151565b6100c98261016f565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156101125761010d82826101ea565b505050565b6100ac61025c565b5f61014c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b365f80375f80365f845af43d5f803e80801561016b573d5ff35b3d5ffd5b806001600160a01b03163b5f036101a957604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f80846001600160a01b0316846040516102069190610407565b5f60405180830381855af49150503d805f811461023e576040519150601f19603f3d011682016040523d82523d5f602084013e610243565b606091505b509150915061025385838361027b565b95945050505050565b34156100785760405163b398979f60e01b815260040160405180910390fd5b6060826102905761028b826102da565b6102d3565b81511580156102a757506001600160a01b0384163b155b156102d057604051639996b31560e01b81526001600160a01b03851660048201526024016101a0565b50805b9392505050565b8051156102ea5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f8085851115610311575f80fd5b8386111561031d575f80fd5b5050820193919092039150565b634e487b7160e01b5f52604160045260245ffd5b5f806040838503121561034f575f80fd5b82356001600160a01b0381168114610365575f80fd5b9150602083013567ffffffffffffffff80821115610381575f80fd5b818501915085601f830112610394575f80fd5b8135818111156103a6576103a661032a565b604051601f8201601f19908116603f011681019083821181831017156103ce576103ce61032a565b816040528281528860208487010111156103e6575f80fd5b826020860160208301375f6020848301015280955050505050509250929050565b5f82518060208501845e5f92019182525091905056fea2646970667358221220117f216494c9098d12bbff87c8d584f4d545471f7a95c3c910c20d7f0d1a105964736f6c63430008190033608060405234801561000f575f80fd5b5060405161050138038061050183398101604081905261002e916100bb565b806001600160a01b03811661005c57604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b6100658161006c565b50506100e8565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f602082840312156100cb575f80fd5b81516001600160a01b03811681146100e1575f80fd5b9392505050565b61040c806100f55f395ff3fe608060405260043610610049575f3560e01c8063715018a61461004d5780638da5cb5b146100635780639623609d14610090578063ad3cb1cc146100a3578063f2fde38b146100e0575b5f80fd5b348015610058575f80fd5b506100616100ff565b005b34801561006e575f80fd5b505f546001600160a01b0316604051610087919061023e565b60405180910390f35b61006161009e36600461027a565b610112565b3480156100ae575f80fd5b506100d3604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516100879190610377565b3480156100eb575f80fd5b506100616100fa366004610390565b61017d565b6101076101c3565b6101105f6101ef565b565b61011a6101c3565b60405163278f794360e11b81526001600160a01b03841690634f1ef28690349061014a90869086906004016103ab565b5f604051808303818588803b158015610161575f80fd5b505af1158015610173573d5f803e3d5ffd5b5050505050505050565b6101856101c3565b6001600160a01b0381166101b7575f604051631e4fbdf760e01b81526004016101ae919061023e565b60405180910390fd5b6101c0816101ef565b50565b5f546001600160a01b03163314610110573360405163118cdaa760e01b81526004016101ae919061023e565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b0391909116815260200190565b6001600160a01b03811681146101c0575f80fd5b634e487b7160e01b5f52604160045260245ffd5b5f805f6060848603121561028c575f80fd5b833561029781610252565b925060208401356102a781610252565b9150604084013567ffffffffffffffff808211156102c3575f80fd5b818601915086601f8301126102d6575f80fd5b8135818111156102e8576102e8610266565b604051601f8201601f19908116603f0116810190838211818310171561031057610310610266565b81604052828152896020848701011115610328575f80fd5b826020860160208301375f6020848301015280955050505050509250925092565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6103896020830184610349565b9392505050565b5f602082840312156103a0575f80fd5b813561038981610252565b6001600160a01b03831681526040602082018190525f906103ce90830184610349565b94935050505056fea2646970667358221220497e1225d21503b2c0e72feef0d5216fe1525afb4c43c9fa065eef75c65856e264736f6c63430008190033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103a2646970667358221220155a5ca05628b57b285498571c338a9178796b0ddbba081a083a9c1cb93ceca164736f6c63430008190033

Verified Source Code Full Match

Compiler: v0.8.25+commit.b61c2a91 EVM: cancun Optimization: Yes (100 runs)
OwnableUpgradeable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
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
        }
    }
}
ERC20Upgradeable.sol 341 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}
ERC4626Upgradeable.sol 311 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * [CAUTION]
 * ====
 * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
 * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
 * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
 * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
 * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
 * verifying the amount received is as expected, using a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
 * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
 * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
 * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
 * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
 * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
 * expensive than it is profitable. More details about the underlying math can be found
 * xref:erc4626.adoc#inflation-attack[here].
 *
 * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
 * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
 * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
 * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
 * `_convertToShares` and `_convertToAssets` functions.
 *
 * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
 * ====
 */
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
    using Math for uint256;

    /// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
    struct ERC4626Storage {
        IERC20 _asset;
        uint8 _underlyingDecimals;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;

    function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
        assembly {
            $.slot := ERC4626StorageLocation
        }
    }

    /**
     * @dev Attempted to deposit more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);

    /**
     * @dev Attempted to mint more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);

    /**
     * @dev Attempted to withdraw more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);

    /**
     * @dev Attempted to redeem more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
     */
    function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
        __ERC4626_init_unchained(asset_);
    }

    function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
        ERC4626Storage storage $ = _getERC4626Storage();
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        $._underlyingDecimals = success ? assetDecimals : 18;
        $._asset = asset_;
    }

    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
        (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
            abi.encodeCall(IERC20Metadata.decimals, ())
        );
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /**
     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
     * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
     *
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return $._underlyingDecimals + _decimalsOffset();
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual returns (address) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return address($._asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual returns (uint256) {
        ERC4626Storage storage $ = _getERC4626Storage();
        return $._asset.balanceOf(address(this));
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Ceil);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Ceil);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
        uint256 maxAssets = maxDeposit(receiver);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
        }

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}.
     *
     * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
     * In this case, the shares will be minted without requiring any assets to be deposited.
     */
    function mint(uint256 shares, address receiver) public virtual returns (uint256) {
        uint256 maxShares = maxMint(receiver);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
        }

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxAssets = maxWithdraw(owner);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
        }

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxShares = maxRedeem(owner);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
        }

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
        ERC4626Storage storage $ = _getERC4626Storage();
        // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom($._asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        ERC4626Storage storage $ = _getERC4626Storage();
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer($._asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _decimalsOffset() internal view virtual returns (uint8) {
        return 0;
    }
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}
PausableUpgradeable.sol 140 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._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) {
        PausableStorage storage $ = _getPausableStorage();
        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 {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // 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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // 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) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}
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);
    }
}
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
IERC1967.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}
IERC4626.sol 230 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
IBeacon.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}
ERC1967Proxy.sol 40 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)

pragma solidity ^0.8.20;

import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    constructor(address implementation, bytes memory _data) payable {
        ERC1967Utils.upgradeToAndCall(implementation, _data);
    }

    /**
     * @dev Returns the current implementation address.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }
}
ERC1967Utils.sol 193 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}
Proxy.sol 69 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}
ProxyAdmin.sol 45 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)

pragma solidity ^0.8.20;

import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol";
import {Ownable} from "../../access/Ownable.sol";

/**
 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
 */
contract ProxyAdmin is Ownable {
    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`
     * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev Sets the initial owner who can perform upgrades.
     */
    constructor(address initialOwner) Ownable(initialOwner) {}

    /**
     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
     * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     * - If `data` is empty, `msg.value` must be zero.
     */
    function upgradeAndCall(
        ITransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
    }
}
TransparentUpgradeableProxy.sol 116 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)

pragma solidity ^0.8.20;

import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {ProxyAdmin} from "./ProxyAdmin.sol";

/**
 * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
 * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
 * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
 * include them in the ABI so this interface must be used to interact with it.
 */
interface ITransparentUpgradeableProxy is IERC1967 {
    function upgradeToAndCall(address, bytes calldata) external payable;
}

/**
 * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
 *
 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
 * clashing], which can potentially be used in an attack, this contract uses the
 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
 * things that go hand in hand:
 *
 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
 * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
 * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to
 * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
 * the proxy admin cannot fallback to the target implementation.
 *
 * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
 * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
 * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
 * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
 * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
 *
 * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
 * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
 * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
 * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
 * implementation.
 *
 * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
 * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
 *
 * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
 * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
 * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
 * undesirable state where the admin slot is different from the actual admin.
 *
 * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
 * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
 * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
 * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
 */
contract TransparentUpgradeableProxy is ERC1967Proxy {
    // An immutable address for the admin to avoid unnecessary SLOADs before each call
    // at the expense of removing the ability to change the admin once it's set.
    // This is acceptable if the admin is always a ProxyAdmin instance or similar contract
    // with its own ability to transfer the permissions to another account.
    address private immutable _admin;

    /**
     * @dev The proxy caller is the current admin, and can't fallback to the proxy target.
     */
    error ProxyDeniedAdminAccess();

    /**
     * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
     * {ERC1967Proxy-constructor}.
     */
    constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
        _admin = address(new ProxyAdmin(initialOwner));
        // Set the storage value and emit an event for ERC-1967 compatibility
        ERC1967Utils.changeAdmin(_proxyAdmin());
    }

    /**
     * @dev Returns the admin of this proxy.
     */
    function _proxyAdmin() internal virtual returns (address) {
        return _admin;
    }

    /**
     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
     */
    function _fallback() internal virtual override {
        if (msg.sender == _proxyAdmin()) {
            if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                revert ProxyDeniedAdminAccess();
            } else {
                _dispatchUpgradeToAndCall();
            }
        } else {
            super._fallback();
        }
    }

    /**
     * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    function _dispatchUpgradeToAndCall() private {
        (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
        ERC1967Utils.upgradeToAndCall(newImplementation, data);
    }
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
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);
}
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);
}
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;
    }
}
Math.sol 415 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
StorageSlot.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}
EnumerableSet.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
IRedeemOperator.sol 21 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

interface IRedeemOperator {
    // Events for logging actions
    event RegisterWithdrawal(address indexed user, uint256 shares);
    event ConfirmWithdrawal(address[] users, uint256[] amounts);
    event UpdateOperator(address oldOperator, address newOperator);
    event UpdateFeeReceiver(address oldFeeReceiver, address newFeeReceiver);
    event Sweep(address token);

    function registerWithdrawal(address _user, uint256 _shares) external;

    function pendingWithdrawersCount() external view returns (uint256);

    function pendingWithdrawers(uint256 _limit, uint256 _offset) external view returns (address[] memory result_);

    function allPendingWithdrawers() external view returns (address[] memory);

    function confirmWithdrawal(address[] calldata _Users, uint256 _totalGasTokenAmount) external;
}
IStrategy.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

interface IStrategy {
    function getNetAssets() external returns (uint256);

    function onTransferIn(address token, uint256 amount) external returns (bool);
}
IVault.sol 97 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

interface IVault {
    event UpdateMarketCapacity(uint256 oldCapacityLimit, uint256 newCapacityLimit);
    event UpdateManagementFee(uint256 oldManagementFee, uint256 newManagementFee);
    event UpdateManagementFeeClaimPeriod(uint256 oldManagementFeeClaimPeriod, uint256 newManagementFeeClaimPeriod);
    event UpdateMaxPriceUpdatePeriod(uint256 oldMaxPriceUpdatePeriod, uint256 newMaxPriceUpdatePeriod);
    event UpdateRevenueRate(uint256 oldRevenueRate, uint256 newRevenueRate);
    event UpdateExitFeeRate(uint256 oldExitFeeRate, uint256 newExitFeeRate);
    event UpdateRebalancer(address oldRebalancer, address newRebalancer);
    event UpdateUnbackedMinter(address oldUnbackedMinter, address newUnbackedMinter);
    event UpdateFeeReceiver(address oldFeeReceiver, address newFeeReceiver);
    event UpdateRedeemOperator(address oldRedeemOperator, address newRedeemOperator);
    event UpdateExchangePrice(uint256 newExchangePrice, uint256 newRevenue);
    event TransferToStrategy(address token, uint256 amount, uint256 strategyIndex);
    event OptionalDeposit(address caller, address token, uint256 assets, address receiver, address referral);
    event OptionalRedeem(address token, uint256 shares, address receiver, address owner);
    event RequestRedeem(address user, uint256 shares, address token);
    event CollectManagementFee(uint256 assets);
    event CollectRevenue(uint256 revenue);
    event AddToken(address token);
    event RemoveToken(address token);

    /**
     * @dev Parameters for initializing the vault contract.
     * @param underlyingToken The address of the underlying token for the vault.
     * @param name The name of the vault token.
     * @param symbol The symbol of the vault token.
     * @param marketCapacity The maximum market capacity of the vault.
     * @param managementFeeRate The rate of the management fee.
     * @param managementFeeClaimPeriod The period for claiming the management fee.
     * @param maxPriceUpdatePeriod The maximum allowed price update period.
     * @param revenueRate The rate of the revenue fee.
     * @param exitFeeRate The rate of the exit fee.
     * @param admin The address of the administrator.
     * @param rebalancer The address responsible for rebalancing the vault.
     * @param feeReceiver The address that will receive the fees.
     * @param redeemOperator The address of the operator responsible for redeeming shares
     */
    struct VaultParams {
        address underlyingToken;
        string name;
        string symbol;
        uint256 marketCapacity;
        uint256 managementFeeRate;
        uint256 managementFeeClaimPeriod;
        uint256 maxPriceUpdatePeriod;
        uint256 revenueRate;
        uint256 exitFeeRate;
        address admin;
        address rebalancer;
        address feeReceiver;
        address redeemOperator;
    }

    /**
     * @dev
     * @param exchangePrice The exchange rate used during user deposit and withdrawal operations.
     * @param revenueExchangePrice The exchange rate used when calculating performance fees,Performance fees will be recorded when the real exchange rate exceeds this rate.
     * @param revenue Collected revenue, stored in pegged ETH.
     * @param lastClaimMngFeeTime The last time the management fees were charged.
     * @param lastUpdatePriceTime The last time the exchange price was updated.
     */
    struct VaultState {
        uint256 exchangePrice;
        uint256 revenueExchangePrice;
        uint256 revenue;
        uint256 lastClaimMngFeeTime;
        uint256 lastUpdatePriceTime;
    }

    function optionalRedeem(address _token, uint256 _shares, uint256 _cutPercentage, address _receiver, address _owner)
        external
        returns (uint256 assetsAfterFee_);

    function getWithdrawFee(uint256 _amount) external view returns (uint256 amount_);

    function exchangePrice() external view returns (uint256);

    function revenueExchangePrice() external view returns (uint256);

    function revenue() external view returns (uint256);

    function lastExchangePrice() external view returns (uint256);

    function getPrecison() external view returns (uint256);

    function burnUnbacked(uint256 _amount) external;

    function mintUnbacked(uint256 _amount) external;

    function optionalDeposit(address _token, uint256 _assets, address _receiver, address _referral)
        external
        payable
        returns (uint256 shares_);
}
Constants.sol 6 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

abstract contract Constants {
    address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
Errors.sol 64 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

library Errors {
    // Revert Errors:
    error CallerNotOperator(); // 0xa5523ee5
    error CallerNotRebalancer(); // 0xbd72e291
    error CallerNotVault(); // 0xedd7338f
    error CallerNotMinter(); // 0x5eee367a
    error ExitFeeRateTooHigh(); // 0xf4d1caab
    error FlashloanInProgress(); // 0x772ac4e8
    error IncorrectState(); // 0x508c9390
    error InfoExpired(); // 0x4ddf4a65
    error InvalidAccount(); // 0x6d187b28
    error InvalidAdapter(); // 0xfbf66df1
    error InvalidAdmin(); // 0xb5eba9f0
    error InvalidAsset(); // 0xc891add2
    error InvalidCaller(); // 0x48f5c3ed
    error InvalidClaimTime(); // 0x1221b97b
    error InvalidFeeReceiver(); // 0xd200485c
    error InvalidFlashloanCall(); // 0xd2208d52
    error InvalidFlashloanHelper(); // 0x8690f016
    error InvalidFlashloanProvider(); // 0xb6b48551
    error InvalidGasLimit(); // 0x98bdb2e0
    error InvalidInitiator(); // 0xbfda1f28
    error InvalidLength(); // 0x947d5a84
    error InvalidLimit(); // 0xe55fb509
    error InvalidManagementFeeClaimPeriod(); // 0x4022e4f6
    error InvalidManagementFeeRate(); // 0x09aa66eb
    error InvalidMarketCapacity(); // 0xc9034604
    error InvalidNetAssets(); // 0x6da79d69
    error InvalidNewOperator(); // 0xba0cdec5
    error InvalidOperator(); // 0xccea9e6f
    error InvalidRebalancer(); // 0xff288a8e
    error InvalidRedeemOperator(); // 0xd214a597
    error InvalidSafeProtocolRatio(); // 0x7c6b23d6
    error InvalidShares(); // 0x6edcc523
    error InvalidTarget(); // 0x82d5d76a
    error InvalidToken(); // 0xc1ab6dc1
    error InvalidTokenId(); // 0x3f6cc768
    error InvalidUnderlyingToken(); // 0x2fb86f96
    error InvalidVault(); // 0xd03a6320
    error InvalidWithdrawalUser(); // 0x36c17319
    error ManagementFeeRateTooHigh(); // 0x09aa66eb
    error ManagementFeeClaimPeriodTooShort(); // 0x4022e4f6
    error MarketCapacityTooLow(); // 0xc9034604
    error NotSupportedYet(); // 0xfb89ba2a
    error PriceNotUpdated(); // 0x1f4bcb2b
    error PriceUpdatePeriodTooLong(); // 0xe88d3ecb
    error RatioOutOfRange(); // 0x9179cbfa
    error RevenueFeeRateTooHigh(); // 0x0674143f
    error UnSupportedOperation(); // 0xe9ec8129
    error UnsupportedToken(); // 0x6a172882
    error WithdrawZero(); // 0x7ea773a9

    // for 1inch swap
    error OneInchInvalidReceiver(); // 0xd540519e
    error OneInchInvalidToken(); // 0x8e7ad912
    error OneInchInvalidInputAmount(); // 0x672b500f
    error OneInchInvalidFunctionSignature(); // 0x247f51aa
    error OneInchUnexpectedSpentAmount(); // 0x295ada05
    error OneInchUnexpectedReturnAmount(); // 0x05e64ca8
    error OneInchNotSupported(); // 0x04b2de78
}
StorageSlot.sol 330 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.25;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * Since version 5.1, this library also support writing and reading value types to and from transient storage.
 *
 *  * Example using transient storage:
 * ```solidity
 * contract Lock {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlotType.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlotType) {
        return AddressSlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlotType.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlotType) {
        return BooleanSlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32SlotType.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32SlotType) {
        return Bytes32SlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256SlotType.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256SlotType) {
        return Uint256SlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256SlotType.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256SlotType) {
        return Int256SlotType.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlotType slot) internal view returns (address value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlotType slot, address value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlotType slot) internal view returns (bool value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlotType slot, bool value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32SlotType slot) internal view returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32SlotType slot, bytes32 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256SlotType slot) internal view returns (uint256 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256SlotType slot, uint256 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256SlotType slot) internal view returns (int256 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256SlotType slot, int256 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }
}
Vault.sol 26 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

import "./common/Constants.sol";
import "./vault/VaultYieldBasic.sol";

/**
 * @title Vault contract
 * @author Naturelab
 * @dev This contract is the logical implementation of the vault,
 * and its main purpose is to provide users with a gateway for depositing
 * and withdrawing funds and to manage user shares.
 */
contract Vault is VaultYieldBasic, Constants {
    string public constant VERSION = "1.0";

    constructor(uint256 _minMarketCapacity) VaultYieldBasic(1e18, _minMarketCapacity) {}

    function redeem(uint256 _shares, address _receiver, address _owner) public nonReentrant whenNotPaused override returns(uint256) {
        return ERC4626Upgradeable.redeem(_shares, _receiver, _owner);
    }

    function withdraw(uint256 _shares, address _receiver, address _owner) public nonReentrant whenNotPaused override returns(uint256) {
        return ERC4626Upgradeable.withdraw(_shares, _receiver, _owner);
    }
}
StrategyFactory.sol 121 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "../../interfaces/IRedeemOperator.sol";
import "../../interfaces/IStrategy.sol";
import "../libraries/Errors.sol";

/**
 * @title StrategyFactory contract
 * @author Naturelab
 * @dev This contract is responsible for managing strategies in a vault.
 * It allows the owner to create, remove, and interact with different strategies.
 */
abstract contract StrategyFactory is OwnableUpgradeable {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;

    uint256 public constant MAX_POSITION_LIMIT = 10000; // 10000/10000 = 100%

    // Set to keep track of the addresses of strategies
    EnumerableSet.AddressSet private _strategies;
    // This mapping is used to set position limits for various strategies.
    // The key is the strategy ID, and the value is the maximum percentage of the entire position
    // that the strategy is allowed to occupy. 1000 = 10%
    mapping(address => uint256) public positionLimit;

    // Events for logging actions
    event CreateStrategy(address strategy, address impl);
    event RemoveStrategy(address strategy);
    event UpdateOperator(address oldOperator, address newOperator);
    event UpdateStrategyLimit(uint256 oldLimit, uint256 newLimit);

    /**
     * @dev Returns the number of strategies in the set.
     * @return The number of strategies.
     */
    function strategiesCount() public view returns (uint256) {
        return _strategies.length();
    }

    /**
     * @dev Returns an array of all strategy addresses.
     * @return An array of strategy addresses.
     */
    function strategies() public view returns (address[] memory) {
        return _strategies.values();
    }

    /**
     * @dev Returns the address of a strategy at a specific index.
     * @param _offset The index of the strategy.
     * @return The address of the strategy.
     */
    function strategyAddress(uint256 _offset) public view returns (address) {
        return _strategies.at(_offset);
    }

    /**
     * @dev Returns the total assets managed by a specific strategy.
     * @param _offset The index of the strategy.
     * @return totalAssets_ The total assets managed by the strategy.
     */
    function strategyAssets(uint256 _offset) public returns (uint256 totalAssets_) {
        totalAssets_ = IStrategy(_strategies.at(_offset)).getNetAssets();
    }

    /**
     * @dev Returns the total assets managed by all strategies combined.
     * @return totalAssets_ The total assets managed by all strategies.
     */
    function totalStrategiesAssets() public returns (uint256 totalAssets_) {
        uint256 length_ = strategiesCount();
        address[] memory strategies_ = strategies();
        for (uint256 i = 0; i < length_; ++i) {
            totalAssets_ += IStrategy(strategies_[i]).getNetAssets();
        }
    }

    /**
     * @dev Allows the owner to create a new strategy.
     * @param _impl The implementation address of the strategy.
     * @param _initBytes The initialization parameters for the strategy.
     */
    function createStrategy(address _impl, bytes calldata _initBytes, uint256 _positionLimit) external onlyOwner {
        if (_positionLimit == 0 || _positionLimit > MAX_POSITION_LIMIT) revert Errors.InvalidLimit();
        address newStrategy_ = address(new TransparentUpgradeableProxy(_impl, msg.sender, _initBytes));
        positionLimit[newStrategy_] = _positionLimit;
        _strategies.add(newStrategy_);

        emit CreateStrategy(newStrategy_, _impl);
    }

    /**
     * @dev Allows the owner to remove a strategy from the set.
     * @param _strategy The address of the strategy to be removed.
     */
    function removeStrategy(address _strategy) external onlyOwner {
        if (IStrategy(_strategy).getNetAssets() > 0) revert Errors.UnSupportedOperation();
        _strategies.remove(_strategy);
        positionLimit[_strategy] = 0;

        emit RemoveStrategy(_strategy);
    }

    /**
     * @dev Update the temporary address of shares when users redeem.
     * @param _newPositionLimit The new redeem operator address.
     */
    function updateStrategyLimit(uint256 _offset, uint256 _newPositionLimit) external onlyOwner {
        if (_newPositionLimit == 0 || _newPositionLimit > MAX_POSITION_LIMIT) revert Errors.InvalidLimit();
        address strategyAddress_ = _strategies.at(_offset);
        emit UpdateStrategyLimit(positionLimit[strategyAddress_], _newPositionLimit);
        positionLimit[strategyAddress_] = _newPositionLimit;
    }
}
VaultYieldBasic.sol 631 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.25;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import "../../interfaces/IRedeemOperator.sol";
import "../../interfaces/IStrategy.sol";
import "../../interfaces/IVault.sol";
import "../libraries/StorageSlot.sol";
import "../libraries/Errors.sol";
import "./StrategyFactory.sol";

/**
 * @title VaultYieldBasic contract
 * @author Naturelab
 * @dev This contract is the logical implementation of the vault,
 * and its main purpose is to provide users with a gateway for depositing
 * and withdrawing funds and to manage user shares.
 */
contract VaultYieldBasic is
    IVault,
    StrategyFactory,
    ERC4626Upgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable
{
    using SafeERC20 for IERC20;
    using StorageSlot for *;
    using EnumerableSet for EnumerableSet.AddressSet;

    // Use EIP-1153 to temporarily store prices for calculation.
    bytes32 internal constant EXCHANGE_PRICE_CACHE = keccak256("EXCHANGE_PRICE_CACHE");

    // Define a constant variable representing the fee denominator, 10000 (used for percentage calculations)
    uint256 internal constant FEE_DENOMINATOR = 1e4;

    // Up to 0.04% can be charged as a management fee in each cycle (4 / 10000)
    uint256 internal constant MAX_MANAGEMENT_FEE_RATE = 4;

    // The shortest cycle for charging the management fee is 7 days
    uint256 internal constant MIN_MANAGEMENT_FEE_CLAIM_PERIOD = 7 days;

    // The maximum interval for price updates. If prices are not updated for a long time,
    // deposits will be temporarily unavailable.
    uint256 internal constant MAX_PRICE_UPDATED_PERIOD = 14 days;

    // The maximum fee for withdrawing from the idle treasury is 1.2% (120 / 10000)
    uint256 internal constant MAX_EXIT_FEE_RATE = 120;

    // The maximum revenue fee rate is 15% (1500 / 10000)
    uint256 internal constant MAX_REVENUE_FEE_RATE = 1500;

    // Prevents erroneous price fluctuations. (100 / 10000)
    uint256 internal constant MAX_PRICE_CHANGE_RATE = 100;

    // Units of measurement used for precise calculations.
    uint256 internal immutable PRECISION;

    // Used to determine the initial exchange price.
    uint256 internal immutable INIT_EXCHANGE_PRICE;

    // Used to limit the minimum initial price.
    uint256 internal immutable MIN_MARKET_CAPACITY;

    // Vault parameters, encapsulating the configuration of the vault
    VaultParams internal vaultParams;

    // Vault state, encapsulating the state of the vault
    VaultState internal vaultState;

    // Used to manage tokens allowed to be deposited.
    EnumerableSet.AddressSet internal tokens;

    // The amount of unbacked minted shares
    uint256 public unbackedMintedAmount;

    // The allowed contract to mint unbacked shares
    address public unbackedMinter;

    /**
     * @dev  Ensure that this method is only called by authorized portfolio managers.
     */
    modifier onlyRebalancer() {
        if (msg.sender != vaultParams.rebalancer) revert Errors.CallerNotRebalancer();
        _;
    }

    /**
     * @dev Ensure that this method is only called by the unbacked minter.
     */
    modifier onlyUnbackedMinter() {
        if (msg.sender != unbackedMinter) revert Errors.CallerNotMinter();
        _;
    }

    constructor(uint256 _precision, uint256 _minMarketCapacity) {
        PRECISION = _precision;
        INIT_EXCHANGE_PRICE = _precision;
        MIN_MARKET_CAPACITY = _minMarketCapacity;
    }

    /**
     * @dev Initialize various parameters of the Vault contract.
     * @param _initBytes The encoded initialization parameters.
     */
    function initialize(bytes calldata _initBytes) external initializer {
        (VaultParams memory params_, address[] memory tokens_) = abi.decode(_initBytes, (IVault.VaultParams, address[]));

        __Pausable_init();
        __ReentrancyGuard_init();
        __ERC20_init(params_.name, params_.symbol);

        if (params_.underlyingToken == address(0)) revert Errors.InvalidUnderlyingToken();
        if (params_.rebalancer == address(0)) revert Errors.InvalidRebalancer();
        if (params_.admin == address(0)) revert Errors.InvalidAdmin();
        if (params_.feeReceiver == address(0)) revert Errors.InvalidFeeReceiver();
        if (params_.marketCapacity < MIN_MARKET_CAPACITY) revert Errors.MarketCapacityTooLow();
        if (params_.managementFeeRate > MAX_MANAGEMENT_FEE_RATE) revert Errors.ManagementFeeRateTooHigh();
        if (params_.managementFeeClaimPeriod < MIN_MANAGEMENT_FEE_CLAIM_PERIOD) {
            revert Errors.ManagementFeeClaimPeriodTooShort();
        }
        if (params_.maxPriceUpdatePeriod > MAX_PRICE_UPDATED_PERIOD) revert Errors.PriceUpdatePeriodTooLong();
        if (params_.revenueRate > MAX_REVENUE_FEE_RATE) revert Errors.RevenueFeeRateTooHigh();
        if (params_.exitFeeRate > MAX_EXIT_FEE_RATE) revert Errors.ExitFeeRateTooHigh();
        __Ownable_init(params_.admin);
        __ERC4626_init(IERC20(params_.underlyingToken));
        vaultState.lastClaimMngFeeTime = block.timestamp;
        vaultState.lastUpdatePriceTime = block.timestamp;
        vaultState.exchangePrice = INIT_EXCHANGE_PRICE;
        vaultParams = params_;

        for (uint256 i; i < tokens_.length; i++) {
            if (tokens_[i] == address(0)) revert Errors.InvalidUnderlyingToken();
            tokens.add(tokens_[i]);
        }
    }

    /**
     * @dev Returns the vault parameters.
     * @return A struct containing the vault parameters.
     */
    function getVaultParams() public view returns (VaultParams memory) {
        return vaultParams;
    }

    /**
     * @dev Returns the vault state.
     * @return A struct containing the vault state.
     */
    function getVaultState() public view returns (VaultState memory) {
        return vaultState;
    }

    function getPrecison() public view returns (uint256) {
        return PRECISION;
    }

    function getTokens() public view returns (address[] memory) {
        return tokens.values();
    }

    /**
     * @dev Update the size of the pool's capacity.
     * @param _newCapacityLimit The new size of the capacity.
     */
    function updateMarketCapacity(uint256 _newCapacityLimit) external onlyOwner {
        if (_newCapacityLimit <= vaultParams.marketCapacity) revert Errors.UnSupportedOperation();
        emit UpdateMarketCapacity(vaultParams.marketCapacity, _newCapacityLimit);
        vaultParams.marketCapacity = _newCapacityLimit;
    }

    /**
     * @dev Update the management fee rate.
     * @param _newManagementFeeRate The new rate.
     */
    function updateManagementFee(uint256 _newManagementFeeRate) external onlyOwner {
        if (_newManagementFeeRate > MAX_MANAGEMENT_FEE_RATE) revert Errors.ManagementFeeRateTooHigh();
        emit UpdateManagementFee(vaultParams.managementFeeRate, _newManagementFeeRate);
        vaultParams.managementFeeRate = _newManagementFeeRate;
    }

    /**
     * @dev Update the collection cycle of management fees.
     * @param _newmanagementFeeClaimPeriod The new management fee claim period.
     */
    function updateManagementFeeClaimPeriod(uint256 _newmanagementFeeClaimPeriod) external onlyOwner {
        if (_newmanagementFeeClaimPeriod < MIN_MANAGEMENT_FEE_CLAIM_PERIOD) {
            revert Errors.ManagementFeeClaimPeriodTooShort();
        }
        emit UpdateManagementFeeClaimPeriod(vaultParams.managementFeeClaimPeriod, _newmanagementFeeClaimPeriod);
        vaultParams.managementFeeClaimPeriod = _newmanagementFeeClaimPeriod;
    }

    /**
     * @dev Update the maximum allowed price update period.
     * @param _newMaxPriceUpdatePeriod The new period.
     */
    function updateMaxPriceUpdatePeriod(uint256 _newMaxPriceUpdatePeriod) external onlyOwner {
        if (_newMaxPriceUpdatePeriod > MAX_PRICE_UPDATED_PERIOD) revert Errors.PriceUpdatePeriodTooLong();
        emit UpdateMaxPriceUpdatePeriod(vaultParams.maxPriceUpdatePeriod, _newMaxPriceUpdatePeriod);
        vaultParams.maxPriceUpdatePeriod = _newMaxPriceUpdatePeriod;
    }

    /**
     * @dev Update the revenue fee rate.
     * @param _newRevenueRate The new rate.
     */
    function updateRevenueRate(uint256 _newRevenueRate) external onlyOwner {
        if (_newRevenueRate > MAX_REVENUE_FEE_RATE) revert Errors.RevenueFeeRateTooHigh();
        emit UpdateRevenueRate(vaultParams.revenueRate, _newRevenueRate);
        vaultParams.revenueRate = _newRevenueRate;
    }

    /**
     * @dev Update the exit fee rate.
     * @param _newExitFeeRate The new rate.
     */
    function updateExitFeeRate(uint256 _newExitFeeRate) external onlyOwner {
        if (_newExitFeeRate > MAX_EXIT_FEE_RATE) revert Errors.ExitFeeRateTooHigh();
        emit UpdateExitFeeRate(vaultParams.exitFeeRate, _newExitFeeRate);
        vaultParams.exitFeeRate = _newExitFeeRate;
    }

    /**
     * @dev Add a new address to the position adjustment whitelist.
     * @param _newRebalancer The new address to be added.
     */
    function updateRebalancer(address _newRebalancer) external onlyOwner {
        if (_newRebalancer == address(0)) revert Errors.InvalidRebalancer();
        emit UpdateRebalancer(vaultParams.rebalancer, _newRebalancer);
        vaultParams.rebalancer = _newRebalancer;
    }

    /**
     * @dev Update the address of the unbacked minter.
     * @param _newUnbackedMinter The new address of the unbacked minter.
     */
    function updateUnbackedMinter(address _newUnbackedMinter) external onlyOwner {
        emit UpdateUnbackedMinter(unbackedMinter, _newUnbackedMinter);
        unbackedMinter = _newUnbackedMinter;
    }

    /**
     * @dev Update the address of the recipient for management fees.
     * @param _newFeeReceiver The new address of the recipient for management fees.
     */
    function updateFeeReceiver(address _newFeeReceiver) external onlyOwner {
        if (_newFeeReceiver == address(0)) revert Errors.InvalidFeeReceiver();
        emit UpdateFeeReceiver(vaultParams.feeReceiver, _newFeeReceiver);
        vaultParams.feeReceiver = _newFeeReceiver;
    }

    /**
     * @dev Update the temporary address of shares when users redeem.
     * @param _newRedeemOperator The new redeem operator address.
     */
    function updateRedeemOperator(address _newRedeemOperator) external onlyOwner {
        if (_newRedeemOperator == address(0)) revert Errors.InvalidRedeemOperator();
        emit UpdateRedeemOperator(vaultParams.redeemOperator, _newRedeemOperator);
        vaultParams.redeemOperator = _newRedeemOperator;
    }

    function addToken(address _newToken) external onlyOwner {
        if (_newToken == address(0)) revert Errors.InvalidUnderlyingToken();
        tokens.add(_newToken);

        emit AddToken(_newToken);
    }

    function removeToken(address _token) external onlyOwner {
        tokens.remove(_token);

        emit RemoveToken(_token);
    }

    /*
     * @return newExchangePrice The new exercise price
     * @return newRevenue The new realized profit.
     */
    function updateExchangePrice() external onlyRebalancer returns (uint256 newExchangePrice, uint256 newRevenue) {
        EXCHANGE_PRICE_CACHE.asUint256().tstore(vaultState.exchangePrice);
        vaultState.lastUpdatePriceTime = block.timestamp;
        uint256 totalSupply_ = totalSupply();
        if (totalSupply_ == 0) {
            return (vaultState.exchangePrice, vaultState.revenue);
        }
        uint256 currentNetAssets_ = underlyingTvl();
        newExchangePrice = currentNetAssets_ * PRECISION / totalSupply_;
        if (newExchangePrice > vaultState.revenueExchangePrice) {
            if (vaultState.revenueExchangePrice == 0) {
                vaultState.revenueExchangePrice = newExchangePrice;
                vaultState.exchangePrice = newExchangePrice;
                return (vaultState.exchangePrice, vaultState.revenue);
            }
            uint256 newProfit_ = currentNetAssets_ - ((vaultState.revenueExchangePrice * totalSupply_) / PRECISION);
            newRevenue = (newProfit_ * vaultParams.revenueRate) / FEE_DENOMINATOR;
            vaultState.revenue += newRevenue;
            uint256 oldExchangePrice_ = vaultState.exchangePrice;
            vaultState.exchangePrice = ((currentNetAssets_ - newRevenue) * PRECISION) / totalSupply_;
            if (vaultState.exchangePrice - oldExchangePrice_ > oldExchangePrice_ * MAX_PRICE_CHANGE_RATE / 1e4) {
                revert Errors.IncorrectState();
            }
            vaultState.revenueExchangePrice = vaultState.exchangePrice;
        } else {
            uint256 diffExchangePrice_ = vaultState.exchangePrice > newExchangePrice
                ? vaultState.exchangePrice - newExchangePrice
                : newExchangePrice - vaultState.exchangePrice;
            if (diffExchangePrice_ > vaultState.exchangePrice * MAX_PRICE_CHANGE_RATE / 1e4) {
                revert Errors.IncorrectState();
            }
            vaultState.exchangePrice = newExchangePrice;
        }

        emit UpdateExchangePrice(newExchangePrice, newRevenue);
    }

    /**
     * @dev Transfer tokens to a strategy.
     * @param _token The address of the token to transfer.
     * @param _amount The amount of tokens to transfer.
     * @param _strategyIndex The index of the strategy to transfer to.
     */
    function transferToStrategy(address _token, uint256 _amount, uint256 _strategyIndex) external {
        address caller_ = msg.sender;
        if (_strategyIndex == 0) {
            if (caller_ != owner() && caller_ != vaultParams.rebalancer) revert Errors.InvalidOperator();
        } else {
            if (caller_ != owner()) revert Errors.InvalidOperator();
        }
        address strategyAddress_ = strategyAddress(_strategyIndex);
        uint256 positionLimit_ = positionLimit[strategyAddress_];
        uint256 nowAssets_ = IStrategy(strategyAddress_).getNetAssets();
        uint8 coreDecimals_ = decimals();
        uint8 tokenDecimals_ = IERC20Metadata(_token).decimals();
        uint256 transferAsset_ = _amount;
        if (tokenDecimals_ > coreDecimals_) {
            transferAsset_ = _amount / (10 ** (tokenDecimals_ - coreDecimals_));
        } else if (tokenDecimals_ < coreDecimals_) {
            transferAsset_ = _amount * (10 ** (coreDecimals_ - tokenDecimals_));
        }
        if ((nowAssets_ + transferAsset_) > (totalAssets() * positionLimit_ / 1e4)) revert Errors.InvalidLimit();
        IERC20(_token).safeIncreaseAllowance(strategyAddress_, _amount);
        if (!IStrategy(strategyAddress_).onTransferIn(_token, _amount)) revert Errors.IncorrectState();

        emit TransferToStrategy(_token, _amount, _strategyIndex);
    }

    /**
     * @dev Retrieve the amount of the exit fee.
     * @param _assetAmount The amount of asset to be withdrawn.
     * @return withdrawFee_ The exit fee to be deducted.
     */
    function getWithdrawFee(uint256 _assetAmount) public view returns (uint256 withdrawFee_) {
        withdrawFee_ = _assetAmount * vaultParams.exitFeeRate / FEE_DENOMINATOR;
    }

    /**
     * @dev Retrieve the total value locked (TVL) in underlying assets.
     * @return The total value locked in underlying assets.
     */
    function underlyingTvl() public virtual returns (uint256) {
        uint256 totalBal_;
        address token_;
        uint8 coreDecimals = decimals();

        for (uint256 i = 0; i < tokens.length(); i++) {
            token_ = tokens.at(i);

            uint256 tokenBal_ = IERC20(token_).balanceOf(address(this));
            uint8 tokenDecimals = IERC20Metadata(token_).decimals();

            // Adjust balance based on the difference in decimals
            if (tokenDecimals > coreDecimals) {
                // If tokenDecimals is greater than core asset decimals, scale down to match core asset
                tokenBal_ = tokenBal_ / (10 ** (tokenDecimals - coreDecimals));
            } else if (tokenDecimals < coreDecimals) {
                // If tokenDecimals is less than core asset decimals, scale up to match core asset
                tokenBal_ = tokenBal_ * (10 ** (coreDecimals - tokenDecimals));
            }

            totalBal_ += tokenBal_;
        }

        uint256 totalStrategy_ = totalStrategiesAssets();
        return totalStrategy_ + totalBal_ - vaultState.revenue;
    }

    /**
     * @dev Retrieve the amount of the actual shares in the vault.
     * @return The total amount of shares in the vault.
     */
    function totalSupply() public view override(ERC20Upgradeable, IERC20) returns (uint256) {
        return ERC20Upgradeable.totalSupply() - unbackedMintedAmount;
    }

    /**
     * @dev Retrieve the amount of assets in the strategy pool.
     * @return The total assets in the strategy pool.
     */
    function totalAssets() public view override returns (uint256) {
        if (block.timestamp - vaultState.lastUpdatePriceTime > vaultParams.maxPriceUpdatePeriod) {
            revert Errors.PriceNotUpdated();
        }

        return vaultState.exchangePrice * totalSupply() / PRECISION;
    }

    /**
     * @return Actual LP price during the user's deposit phase.
     */
    function exchangePrice() public view override returns (uint256) {
        return vaultState.exchangePrice;
    }

    /**
     * @dev When the actual LP price exceeds this price, performance fee settlement can be conducted.
     * @return LP price for settling performance fees.
     */
    function revenueExchangePrice() public view override returns (uint256) {
        return vaultState.revenueExchangePrice;
    }

    /**
     * @return Currently accumulated performance fees.
     */
    function revenue() public view override returns (uint256) {
        return vaultState.revenue;
    }

    /**
     * @return The remaining time. If it is 0, deposits are currently not allowed.
     * @dev If it is not 0, the admin needs to update the price within this period.
     */
    function remainingUpdateTime() public view returns (uint256) {
        uint256 timeDiff_ = block.timestamp - vaultState.lastUpdatePriceTime;
        return vaultParams.maxPriceUpdatePeriod > timeDiff_ ? (vaultParams.maxPriceUpdatePeriod - timeDiff_) : 0;
    }

    /**
     * @dev Retrieve the maximum amount that can be deposited by an address.
     * @return maxAssets_ The maximum deposit amount.
     */
    function maxDeposit(address) public view override returns (uint256 maxAssets_) {
        maxAssets_ = vaultParams.marketCapacity - totalAssets();
    }

    /**
     * @return The actual LP price before the last update.
     * @dev If it is lower than current price, there might be a withdrawal rebalancing loss,
     * which the user needs to bear. This usually does not happen.
     */
    function lastExchangePrice() public view override returns (uint256) {
        return EXCHANGE_PRICE_CACHE.asUint256().tload();
    }

    /**
     * @dev Optional deposit function allowing deposits in different token types.
     * @param _token The address of the token to deposit.
     * @param _assets The amount of assets to deposit.
     * @param _receiver The address of the receiver of the shares.
     * @param _referral  Address of the referrer.
     * @return shares_ The amount of shares issued.
     */
    function optionalDeposit(address _token, uint256 _assets, address _receiver, address _referral)
        public
        payable
        virtual
        nonReentrant
        whenNotPaused
        returns (uint256 shares_)
    {
        if (_token != asset()) revert Errors.InvalidUnderlyingToken();
        shares_ = super.deposit(_assets, _receiver);

        emit OptionalDeposit(msg.sender, _token, _assets, _receiver, _referral);
    }

    /**
     * @dev Redemption operation executed by the redeemOperator. Currently, only rsETH redemptions are supported.
     * @param _token The address of the token to be redeemed.
     * @param _shares The amount of share tokens to be redeemed.
     * @param _cutPercentage The percentage of the rebalancing loss incurred.
     * @param _receiver The address of the receiver of the assets.
     * @param _owner The owner address of the shares.
     * @return assetsAfterFee_ The amount of assets obtained.
     */
    function optionalRedeem(address _token, uint256 _shares, uint256 _cutPercentage, address _receiver, address _owner)
        public
        override
        nonReentrant
        whenNotPaused
        returns (uint256 assetsAfterFee_)
    {
        if (!tokens.contains(_token)) revert Errors.InvalidAsset();
        if (msg.sender != vaultParams.redeemOperator) revert Errors.UnSupportedOperation();
        if (vaultState.lastUpdatePriceTime != block.timestamp) revert Errors.PriceNotUpdated();

        if (_shares == type(uint256).max) {
            _shares = maxRedeem(_owner);
        } else {
            require(_shares <= maxRedeem(_owner), "ERC4626: redeem more than max");
        }

        if (msg.sender != _owner) {
            _spendAllowance(_owner, msg.sender, _shares);
        }

        uint256 assets_ = previewRedeem(_shares * (PRECISION - _cutPercentage) / PRECISION);
        _burn(_owner, _shares);
        assetsAfterFee_ = assets_ - getWithdrawFee(assets_);

        IERC20(_token).safeTransfer(_receiver, assetsAfterFee_);

        emit OptionalRedeem(_token, _shares, _receiver, _owner);
    }

    /**
     * @dev The deposit method of ERC4626, with the parameter being the amount of assets.
     * @param _assets The amount of asset being deposited.
     * @param _receiver The recipient of the share tokens.
     * @return shares_ The amount of share tokens obtained.
     */
    function deposit(uint256 _assets, address _receiver)
        public
        override
        nonReentrant
        whenNotPaused
        returns (uint256 shares_)
    {
        if (_assets == type(uint256).max) {
            _assets = IERC20(asset()).balanceOf(msg.sender);
        }
        shares_ = super.deposit(_assets, _receiver);
    }

    /**
     * @dev The deposit method of ERC4626, with the parameter being the amount of share tokens.
     * @param _shares The amount of share tokens to be minted.
     * @param _receiver The recipient of the share tokens.
     * @return assets_ The amount of assets consumed.
     */
    function mint(uint256 _shares, address _receiver)
        public
        override
        nonReentrant
        whenNotPaused
        returns (uint256 assets_)
    {
        assets_ = super.mint(_shares, _receiver);
    }

    function withdraw(uint256, address, address) public virtual override returns (uint256) {
        // Only delayed withdrawals are supported
        revert Errors.NotSupportedYet();
    }

    function redeem(uint256, address, address) public virtual override returns (uint256) {
        // Only delayed withdrawals are supported
        revert Errors.NotSupportedYet();
    }

    /**
     * @dev Burn unbacked minted shares.
     */
    function burnUnbacked(uint256 _amount) external onlyUnbackedMinter {
        if (_amount > unbackedMintedAmount) revert Errors.InvalidShares();
        unbackedMintedAmount -= _amount;
        _burn(unbackedMinter, _amount);
    }

    /**
     * @dev Mint unbacked minted shares, for providing liquidity on L2.
     */
    function mintUnbacked(uint256 _amount) external onlyUnbackedMinter {
        unbackedMintedAmount += _amount;
        _mint(unbackedMinter, _amount);
    }

    /**
     * @dev When a user applies for redemption, his share will be
     * transferred to the RedeemOperator address.
     * @param _shares The amount of share tokens to be redeemed.
     * @param _token The address of the token to redeem.
     */
    function requestRedeem(uint256 _shares, address _token) external virtual nonReentrant whenNotPaused {
        if (_shares == 0) revert Errors.WithdrawZero();
        _transfer(msg.sender, vaultParams.redeemOperator, _shares);
        IRedeemOperator(vaultParams.redeemOperator).registerWithdrawal(msg.sender, _shares);

        emit RequestRedeem(msg.sender, _shares, _token);
    }

    /**
     * @dev Collect management fee.
     */
    function collectManagementFee() external {
        if (msg.sender != vaultParams.feeReceiver) revert Errors.InvalidFeeReceiver();
        uint256 nowTime_ = block.timestamp;
        if (nowTime_ - vaultState.lastClaimMngFeeTime < vaultParams.managementFeeClaimPeriod) {
            revert Errors.InvalidClaimTime();
        }
        vaultState.lastClaimMngFeeTime = nowTime_;
        uint256 assets_ = totalAssets() * vaultParams.managementFeeRate / FEE_DENOMINATOR;
        IERC20(asset()).safeTransfer(vaultParams.feeReceiver, assets_);

        emit CollectManagementFee(assets_);
    }

    /**
     * @dev Collect performance fees to the recipient address.
     */
    function collectRevenue() external {
        if (msg.sender != vaultParams.feeReceiver) revert Errors.InvalidFeeReceiver();
        IERC20(asset()).safeTransfer(vaultParams.feeReceiver, vaultState.revenue);
        emit CollectRevenue(vaultState.revenue);
        vaultState.revenue = 0;
    }

    function pause() external {
        if (msg.sender != owner() && msg.sender != vaultParams.rebalancer) revert Errors.UnSupportedOperation();
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    receive() external payable {}
}

Read Contract

ETH 0x8322fff2 → address
MAX_POSITION_LIMIT 0xf4ad8788 → uint256
VERSION 0xffa1ad74 → string
allowance 0xdd62ed3e → uint256
asset 0x38d52e0f → address
balanceOf 0x70a08231 → uint256
convertToAssets 0x07a2d13a → uint256
convertToShares 0xc6e6f592 → uint256
decimals 0x313ce567 → uint8
exchangePrice 0x9e65741e → uint256
getPrecison 0xe3ea7c6a → uint256
getTokens 0xaa6ca808 → address[]
getVaultParams 0x88bb4f60 → tuple
getVaultState 0x4a8c110a → tuple
getWithdrawFee 0x29c23e4a → uint256
lastExchangePrice 0xc0587a95 → uint256
maxDeposit 0x402d267d → uint256
maxMint 0xc63d75b6 → uint256
maxRedeem 0xd905777e → uint256
maxWithdraw 0xce96cb77 → uint256
name 0x06fdde03 → string
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
positionLimit 0xb0caa891 → uint256
previewDeposit 0xef8b30f7 → uint256
previewMint 0xb3d7f6b9 → uint256
previewRedeem 0x4cdad506 → uint256
previewWithdraw 0x0a28a477 → uint256
remainingUpdateTime 0x3b0426db → uint256
revenue 0x3e9491a2 → uint256
revenueExchangePrice 0x98e1862c → uint256
strategies 0xd9f9027f → address[]
strategiesCount 0x2489f7f7 → uint256
strategyAddress 0x4b59b82e → address
symbol 0x95d89b41 → string
totalAssets 0x01e1d114 → uint256
totalSupply 0x18160ddd → uint256
unbackedMintedAmount 0x2de10fab → uint256
unbackedMinter 0xfa559a35 → address

Write Contract 39 functions

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

addToken 0xd48bfca7
address _newToken
approve 0x095ea7b3
address spender
uint256 value
returns: bool
burnUnbacked 0x9c5861b6
uint256 _amount
collectManagementFee 0x9c016ffd
No parameters
collectRevenue 0xed14d17e
No parameters
createStrategy 0xad35530b
address _impl
bytes _initBytes
uint256 _positionLimit
deposit 0x6e553f65
uint256 _assets
address _receiver
returns: uint256
initialize 0x439fab91
bytes _initBytes
mint 0x94bf804d
uint256 _shares
address _receiver
returns: uint256
mintUnbacked 0x596384ae
uint256 _amount
optionalDeposit 0x32507a5f
address _token
uint256 _assets
address _receiver
address _referral
returns: uint256
optionalRedeem 0xa7b73254
address _token
uint256 _shares
uint256 _cutPercentage
address _receiver
address _owner
returns: uint256
pause 0x8456cb59
No parameters
redeem 0xba087652
uint256 _shares
address _receiver
address _owner
returns: uint256
removeStrategy 0x175188e8
address _strategy
removeToken 0x5fa7b584
address _token
renounceOwnership 0x715018a6
No parameters
requestRedeem 0x107703ab
uint256 _shares
address _token
strategyAssets 0xb2db983a
uint256 _offset
returns: uint256
totalStrategiesAssets 0xbf6590a4
No parameters
returns: uint256
transfer 0xa9059cbb
address to
uint256 value
returns: bool
transferFrom 0x23b872dd
address from
address to
uint256 value
returns: bool
transferOwnership 0xf2fde38b
address newOwner
transferToStrategy 0xba8bfa2a
address _token
uint256 _amount
uint256 _strategyIndex
underlyingTvl 0x079c3b88
No parameters
returns: uint256
unpause 0x3f4ba83a
No parameters
updateExchangePrice 0x3bfaa7e3
No parameters
returns: uint256, uint256
updateExitFeeRate 0x25bd4142
uint256 _newExitFeeRate
updateFeeReceiver 0xc69bebe4
address _newFeeReceiver
updateManagementFee 0x030d624a
uint256 _newManagementFeeRate
updateManagementFeeClaimPeriod 0x3c5280e4
uint256 _newmanagementFeeClaimPeriod
updateMarketCapacity 0x7f6c81b7
uint256 _newCapacityLimit
updateMaxPriceUpdatePeriod 0x34069157
uint256 _newMaxPriceUpdatePeriod
updateRebalancer 0xb046a449
address _newRebalancer
updateRedeemOperator 0x7a825e07
address _newRedeemOperator
updateRevenueRate 0x266f8dc9
uint256 _newRevenueRate
updateStrategyLimit 0x8152cd18
uint256 _offset
uint256 _newPositionLimit
updateUnbackedMinter 0x01c704ba
address _newUnbackedMinter
withdraw 0xb460af94
uint256 _shares
address _receiver
address _owner
returns: uint256

Recent Transactions

No transactions found for this address