Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x78cc4FAd915fF9514F73046D84cE8B2AAc98da12
Balance 0 ETH
Nonce 1
Code Size 9996 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

9996 bytes
0x6080604052600436106101405760003560e01c8063a06b2a39116100b6578063dd2518f31161006f578063dd2518f3146103be578063dd38e67c146103de578063e0b4b386146103fe578063e2d94dbd1461042f578063f2fde38b14610444578063f343e8581461046457600080fd5b8063a06b2a39146102ec578063ac4afa381461030c578063beee9fa914610353578063c1b02ae014610368578063c89039c514610388578063d2ba5e3a146103a857600080fd5b80634f9ea6e9116101085780634f9ea6e91461022957806352d1902d146102615780636b04c18a14610284578063715018a6146102a45780638901579e146102b95780638da5cb5b146102ce57600080fd5b806330dc6308146101455780633659cfe6146101b45780633756c011146101d65780633d0a42e7146101f65780634f1ef28614610216575b600080fd5b34801561015157600080fd5b50610190610160366004612161565b60d1602090815260009283526040808420909152908252902080546001909101546001600160801b039091169082565b604080516001600160801b0390931683526020830191909152015b60405180910390f35b3480156101c057600080fd5b506101d46101cf36600461218b565b6104a4565b005b3480156101e257600080fd5b506101d46101f13660046121a6565b61058c565b34801561020257600080fd5b506101d46102113660046121a6565b6105ef565b6101d46102243660046121e8565b61064c565b34801561023557600080fd5b5060ce54610249906001600160a01b031681565b6040516001600160a01b0390911681526020016101ab565b34801561026d57600080fd5b5061027661071c565b6040519081526020016101ab565b34801561029057600080fd5b5060cc54610249906001600160a01b031681565b3480156102b057600080fd5b506101d46107cf565b3480156102c557600080fd5b506101d46107e3565b3480156102da57600080fd5b506033546001600160a01b0316610249565b3480156102f857600080fd5b5060cd54610249906001600160a01b031681565b34801561031857600080fd5b5061032c6103273660046122aa565b610953565b604080516001600160801b03909416845260208401929092521515908201526060016101ab565b34801561035f57600080fd5b506101d4610993565b34801561037457600080fd5b506101d46103833660046122c3565b6109b0565b34801561039457600080fd5b5060cb54610249906001600160a01b031681565b3480156103b457600080fd5b5061027660d25481565b3480156103ca57600080fd5b506101d46103d93660046122db565b610a44565b3480156103ea57600080fd5b506101d46103f9366004612307565b610c18565b34801561040a57600080fd5b5060ca5461041f90600160a01b900460ff1681565b60405190151581526020016101ab565b34801561043b57600080fd5b50610276610e06565b34801561045057600080fd5b506101d461045f36600461218b565b610ede565b34801561047057600080fd5b5061019061047f3660046122aa565b60d060205260009081526040902080546001909101546001600160801b039091169082565b6001600160a01b037f00000000000000000000000078cc4fad915ff9514f73046d84ce8b2aac98da121630036104f55760405162461bcd60e51b81526004016104ec906123af565b60405180910390fd5b7f00000000000000000000000078cc4fad915ff9514f73046d84ce8b2aac98da126001600160a01b031661053e600080516020612690833981519152546001600160a01b031690565b6001600160a01b0316146105645760405162461bcd60e51b81526004016104ec906123fb565b61056d81610f54565b6040805160008082526020820190925261058991839190610fb6565b50565b826105988160cf541190565b6105dd5760405162461bcd60e51b81526020600482015260166024820152751114ce881c1bdbdb08191bd95cdb89dd08195e1a5cdd60521b60448201526064016104ec565b6105e933858585611126565b50505050565b826105fb8160cf541190565b6106405760405162461bcd60e51b81526020600482015260166024820152751114ce881c1bdbdb08191bd95cdb89dd08195e1a5cdd60521b60448201526064016104ec565b6105e9338585856114a1565b6001600160a01b037f00000000000000000000000078cc4fad915ff9514f73046d84ce8b2aac98da121630036106945760405162461bcd60e51b81526004016104ec906123af565b7f00000000000000000000000078cc4fad915ff9514f73046d84ce8b2aac98da126001600160a01b03166106dd600080516020612690833981519152546001600160a01b031690565b6001600160a01b0316146107035760405162461bcd60e51b81526004016104ec906123fb565b61070c82610f54565b61071882826001610fb6565b5050565b6000306001600160a01b037f00000000000000000000000078cc4fad915ff9514f73046d84ce8b2aac98da1216146107bc5760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c60448201527f6c6564207468726f7567682064656c656761746563616c6c000000000000000060648201526084016104ec565b5060008051602061269083398151915290565b6107d761168a565b6107e160006116e4565b565b60006107ed610e06565b9050600081116108365760405162461bcd60e51b815260206004820152601460248201527344533a206f766572706c7573206973207a65726f60601b60448201526064016104ec565b61083f81611736565b5060cb546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015610889573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108ad9190612447565b9050600081116108ff5760405162461bcd60e51b815260206004820152601f60248201527f44533a20636f6e747261637420686173206e6f204441492062616c616e63650060448201526064016104ec565b60cd5460cb5461091c916001600160a01b0391821691168361191c565b6040518281527f1c1beeacf263316031be95f61cdcab6d052033248371579d5a954667ee9df8ad9060200160405180910390a15050565b60cf818154811061096357600080fd5b60009182526020909120600390910201805460018201546002909201546001600160801b03909116925060ff1683565b61099b61168a565b60ca805460ff60a01b1916600160a01b179055565b6109b861168a565b60cf805460018101825560009190915281906003027facb8d954e2cfef495862221e91bd7523613cf8808827cb33edfe4904cc51bf29016109f98282612483565b505060cf54610a0a906001906124f0565b7fef1f367e6c61dfaa1c3f81907cf305caf009b41ec5e5a69900a6424339a18af582604051610a399190612503565b60405180910390a250565b60c9546001600160a01b0316331480610a67575060ca546001600160a01b031633145b610ab35760405162461bcd60e51b815260206004820152601a60248201527f44533a20556e617574686f72697a656420746f20526566756e6400000000000060448201526064016104ec565b6001600160a01b038116610b095760405162461bcd60e51b815260206004820152601c60248201527f44533a207573657220697320746865207a65726f20616464726573730000000060448201526064016104ec565b6001600160a01b038116600090815260d1602090815260408083208584529091529020600181015480156105e9576000600180840182905585825260d06020526040822090810154909190610b5e908461197f565b905080826001016000828254610b7491906124f0565b909155505060d254610b86908461197f565b90508060d26000828254610b9a91906124f0565b9091555060009050610bab82611736565b60cb54909150610bc5906001600160a01b0316878361191c565b60408051858152600060208201819052916001600160a01b038916918a917fa746a3d46437245ec92a03d65f8e29d475586c621a9c23e71fffbdbecdcf07ca910160405180910390a35050505050505050565b600054610100900460ff1615808015610c385750600054600160ff909116105b80610c525750303b158015610c52575060005460ff166001145b610cb55760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016104ec565b6000805460ff191660011790558015610cd8576000805461ff0019166101001790555b610ce0611999565b610ce86119c8565b60005b84811015610d2357610d13868683818110610d0857610d08612544565b9050606002016109b0565b610d1c8161255a565b9050610ceb565b5060cb8054736b175474e89094c44da98b954eedeac495271d0f6001600160a01b0319918216811790925560cc805473373238337bfe1146fb49989fc222523f83081ddb908316811790915560c9805483166001600160a01b038881169190911790915560ca8054841687831617905560ce805484168317905560cd8054909316908a1617909155610db891906000196119ef565b8015610dfe576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b60ce5460405163d7f7098f60e01b815230600482015260009182916001600160a01b039091169063d7f7098f906024016020604051808303816000875af1158015610e55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e799190612447565b905060d2548111610e8c57600091505090565b600060d25482610e9c91906124f0565b60408051848152602081018390529192507fe36196fd0a61846935e395405fbe8ff7b19f5a8c57a263573d618a1c7223b60b910160405180910390a192915050565b610ee661168a565b6001600160a01b038116610f4b5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016104ec565b610589816116e4565b610f5c61168a565b60ca54600160a01b900460ff16156105895760405162461bcd60e51b815260206004820152601b60248201527f44533a20757067726164652069736e277420617661696c61626c65000000000060448201526064016104ec565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff1615610fee57610fe983611b04565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015611048575060408051601f3d908101601f1916820190925261104591810190612447565b60015b6110ab5760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b60648201526084016104ec565b600080516020612690833981519152811461111a5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b60648201526084016104ec565b50610fe9838383611ba0565b600082116111765760405162461bcd60e51b815260206004820152601760248201527f44533a206e6f7468696e6720746f20776974686472617700000000000000000060448201526064016104ec565b600060cf848154811061118b5761118b612544565b6000918252602080832087845260d0825260408085206001600160a01b038b16865260d184528186208a87529093529093206001810154600390930290930193509190806112135760405162461bcd60e51b81526020600482015260156024820152741114ce881d5cd95c881a5cdb89dd081cdd185ad959605a1b60448201526064016104ec565b8086111561121f578095505b8354825460009161123c916001600160801b039182169116612573565b6001600160801b031642116112935760405162461bcd60e51b815260206004820152601b60248201527f44533a20706f6f6c207769746864726177206973206c6f636b6564000000000060448201526064016104ec565b60ce5460405163d7f7098f60e01b81523060048201526000916001600160a01b03169063d7f7098f906024016020604051808303816000875af11580156112de573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113029190612447565b9050808811156113685760405162461bcd60e51b815260206004820152602b60248201527f44533a20616d6f756e742069732067726561746572207468616e20636f6e747260448201526a6163742062616c616e636560a81b60648201526084016104ec565b600061137389611736565b985088905061138281856124f0565b9250866001015483101580611395575082155b6113e15760405162461bcd60e51b815260206004820152601b60248201527f44533a20696e76616c696420776974686472617720616d6f756e74000000000060448201526064016104ec565b85546001600160801b031916426001600160801b03161786556001860180548a91906000906114119084906124f0565b90915550506001850183905560d280548a91906000906114329084906124f0565b909155505060cb5461144e906001600160a01b03168c8b61191c565b604080518a8152602081018a90526001600160a01b038d16918c917fa746a3d46437245ec92a03d65f8e29d475586c621a9c23e71fffbdbecdcf07ca910160405180910390a35050505050505050505050565b600082116114e85760405162461bcd60e51b815260206004820152601460248201527344533a206e6f7468696e6720746f207374616b6560601b60448201526064016104ec565b600060cf84815481106114fd576114fd612544565b6000918252602080832087845260d0825260408085206001600160a01b038b16865260d184528186208a8752909352909320600390920290920192506115576115433390565b60cb546001600160a01b0316903088611bc5565b61156085611bfd565b94508260010154858260010154611577919061259a565b10156115ba5760405162461bcd60e51b815260206004820152601260248201527144533a20616d6f756e7420746f6f206c6f7760701b60448201526064016104ec565b8460d260008282546115cc919061259a565b909155505081546001600160801b031916426001600160801b031617825560018201805486919060009061160190849061259a565b909155505080546001600160801b031916426001600160801b031617815560018101805486919060009061163690849061259a565b909155505060408051868152602081018690526001600160a01b0389169188917f9612520d2ead6ce7570316d46e8b55381a1a66b9d591b1a2e770a36ba276a388910160405180910390a350505050505050565b6033546001600160a01b031633146107e15760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016104ec565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600080821161177d5760405162461bcd60e51b81526020600482015260136024820152721114ce881b9bdd1a1a5b99c81d1bc8195e1a5d606a1b60448201526064016104ec565b60cb546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa1580156117c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117ea9190612447565b60ce5460405163ef693bed60e01b8152306004820152602481018690529192506001600160a01b03169063ef693bed90604401600060405180830381600087803b15801561183757600080fd5b505af115801561184b573d6000803e3d6000fd5b505060cb546040516370a0823160e01b8152306004820152600093506001600160a01b0390911691506370a0823190602401602060405180830381865afa15801561189a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118be9190612447565b905060006118cc83836124f0565b9050600081116119145760405162461bcd60e51b81526020600482015260136024820152721114ce881114d488195e1a5d0819985a5b1959606a1b60448201526064016104ec565b949350505050565b6040516001600160a01b038316602482015260448101829052610fe990849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611ddb565b600082821161198e5781611990565b825b90505b92915050565b600054610100900460ff166119c05760405162461bcd60e51b81526004016104ec906125ad565b6107e1611eb0565b600054610100900460ff166107e15760405162461bcd60e51b81526004016104ec906125ad565b801580611a695750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015611a43573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a679190612447565b155b611ad45760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b60648201526084016104ec565b6040516001600160a01b038316602482015260448101829052610fe990849063095ea7b360e01b90606401611948565b6001600160a01b0381163b611b715760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016104ec565b60008051602061269083398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b611ba983611ee0565b600082511180611bb65750805b15610fe9576105e98383611f20565b6040516001600160a01b03808516602483015283166044820152606481018290526105e99085906323b872dd60e01b90608401611948565b6000808211611c445760405162461bcd60e51b815260206004820152601360248201527222299d103737ba3434b733903a37903537b4b760691b60448201526064016104ec565b60cb546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611c8d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cb19190612447565b60ce54604051633b4da69f60e01b8152306004820152602481018690529192506001600160a01b031690633b4da69f90604401600060405180830381600087803b158015611cfe57600080fd5b505af1158015611d12573d6000803e3d6000fd5b505060cb546040516370a0823160e01b8152306004820152600093506001600160a01b0390911691506370a0823190602401602060405180830381865afa158015611d61573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d859190612447565b90506000611d9382846124f0565b9050600081116119145760405162461bcd60e51b81526020600482015260136024820152721114ce881114d4881a9bda5b8819985a5b1959606a1b60448201526064016104ec565b6000611e30826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611f459092919063ffffffff16565b9050805160001480611e51575080806020019051810190611e5191906125f8565b610fe95760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016104ec565b600054610100900460ff16611ed75760405162461bcd60e51b81526004016104ec906125ad565b6107e1336116e4565b611ee981611b04565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b606061199083836040518060600160405280602781526020016126b060279139611f54565b60606119148484600085611fcc565b6060600080856001600160a01b031685604051611f719190612640565b600060405180830381855af49150503d8060008114611fac576040519150601f19603f3d011682016040523d82523d6000602084013e611fb1565b606091505b5091509150611fc2868383876120a7565b9695505050505050565b60608247101561202d5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016104ec565b600080866001600160a01b031685876040516120499190612640565b60006040518083038185875af1925050503d8060008114612086576040519150601f19603f3d011682016040523d82523d6000602084013e61208b565b606091505b509150915061209c878383876120a7565b979650505050505050565b6060831561211657825160000361210f576001600160a01b0385163b61210f5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016104ec565b5081611914565b611914838381511561212b5781518083602001fd5b8060405162461bcd60e51b81526004016104ec919061265c565b80356001600160a01b038116811461215c57600080fd5b919050565b6000806040838503121561217457600080fd5b61217d83612145565b946020939093013593505050565b60006020828403121561219d57600080fd5b61199082612145565b6000806000606084860312156121bb57600080fd5b505081359360208301359350604090920135919050565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156121fb57600080fd5b61220483612145565b9150602083013567ffffffffffffffff8082111561222157600080fd5b818501915085601f83011261223557600080fd5b813581811115612247576122476121d2565b604051601f8201601f19908116603f0116810190838211818310171561226f5761226f6121d2565b8160405282815288602084870101111561228857600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b6000602082840312156122bc57600080fd5b5035919050565b6000606082840312156122d557600080fd5b50919050565b600080604083850312156122ee57600080fd5b823591506122fe60208401612145565b90509250929050565b60008060008060006080868803121561231f57600080fd5b61232886612145565b9450602086013567ffffffffffffffff8082111561234557600080fd5b818801915088601f83011261235957600080fd5b81358181111561236857600080fd5b89602060608302850101111561237d57600080fd5b60208301965080955050505061239560408701612145565b91506123a360608701612145565b90509295509295909350565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b60006020828403121561245957600080fd5b5051919050565b6001600160801b038116811461058957600080fd5b801515811461058957600080fd5b813561248e81612460565b6001600160801b0381166001600160801b031983541617825550602082013560018201556002810160408301356124c481612475565b815490151560ff1660ff19919091161790555050565b634e487b7160e01b600052601160045260246000fd5b81810381811115611993576119936124da565b60608101823561251281612460565b6001600160801b0316825260208381013590830152604083013561253581612475565b80151560408401525092915050565b634e487b7160e01b600052603260045260246000fd5b60006001820161256c5761256c6124da565b5060010190565b6001600160801b03818116838216019080821115612593576125936124da565b5092915050565b80820180821115611993576119936124da565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b60006020828403121561260a57600080fd5b815161261581612475565b9392505050565b60005b8381101561263757818101518382015260200161261f565b50506000910152565b6000825161265281846020870161261c565b9190910192915050565b602081526000825180602084015261267b81604085016020870161261c565b601f01601f1916919091016040019291505056fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220a6f62939b605927e23c2d87d5974dffd903985d3d8760caf9e52c7d06f83364d64736f6c63430008140033

Verified Source Code Full Match

Compiler: v0.8.20+commit.a1b79de6 EVM: paris Optimization: Yes (200 runs)
Distribution.sol 290 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

import {PRECISION} from "@solarity/solidity-lib/utils/Globals.sol";

import {IDistribution} from "./interfaces/IDistribution.sol";
import {IDaiDsrManager} from "./interfaces/IDaiDsrManager.sol";

contract Distribution is IDistribution, OwnableUpgradeable, UUPSUpgradeable {
    using SafeERC20 for IERC20;

    address private refunderAddress;
    address private fallbackAddress;

    // Modifier to restrict access to the ejectStakedFunds call
    modifier onlyRefunder() {
        require(msg.sender == refunderAddress || msg.sender == fallbackAddress, "DS: Unauthorized to Refund");
        _;
    }

    bool public isNotUpgradeable;

    address public depositToken;
    address public daiDsrManagerAddress;
    address public aoDistributionWallet;
    IDaiDsrManager public daiDsrManager;

    // Pool storage
    Pool[] public pools;
    mapping(uint256 => PoolData) public poolsData;

    // User storage
    mapping(address => mapping(uint256 => UserData)) public usersData;

    // Total deposited storage
    uint256 public totalDepositedInPublicPools;

    /**********************************************************************************************/
    /*** Modifiers                                                                              ***/
    /**********************************************************************************************/
    modifier poolExists(uint256 poolId_) {
        require(_poolExists(poolId_), "DS: pool doesn't exist");
        _;
    }

    /**********************************************************************************************/
    /*** Init                                                                                   ***/
    /**********************************************************************************************/

    constructor() {
        _disableInitializers();
    }

    function Distribution_init(
        address aoDistributionWallet_,
        Pool[] calldata poolsInfo_,
        address refunderAddress_,
        address fallbackAddress_
    ) external initializer {
        __Ownable_init();
        __UUPSUpgradeable_init();

        for (uint256 i; i < poolsInfo_.length; ++i) {
            createPool(poolsInfo_[i]);
        }

        depositToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
        daiDsrManagerAddress = 0x373238337Bfe1146fb49989fc222523f83081dDb;
        // Setting the Multicall address
        refunderAddress = refunderAddress_;
        // Fallback address for non-multicall refunds
        fallbackAddress = fallbackAddress_;
        daiDsrManager = IDaiDsrManager(daiDsrManagerAddress);
        aoDistributionWallet = aoDistributionWallet_;

        // (almost) unlimited approve of DAI to the DSR
        IERC20(depositToken).safeApprove(daiDsrManagerAddress, type(uint256).max);
    }

    /**********************************************************************************************/
    /*** Pool managment and data retrieval                                                      ***/
    /**********************************************************************************************/
    function createPool(Pool calldata pool_) public onlyOwner {
        pools.push(pool_);

        emit PoolCreated(pools.length - 1, pool_);
    }

    /**********************************************************************************************/
    /*** Stake, withdraw                                                                 ***/
    /**********************************************************************************************/
    function stake(uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) external poolExists(poolId_) {
        _stake(_msgSender(), poolId_, amount_, arweaveAddress_);
    }

    function withdraw(uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) external poolExists(poolId_) {
        _withdraw(_msgSender(), poolId_, amount_, arweaveAddress_);
    }

    /**
     * @dev Deposits the specified amount of DAI into the Dai Savings Rate (DSR) system.
     * @param amount_ The amount of DAI to deposit into DSR.
     * @return The actual amount of DAI deposited, which may differ slightly from the input amount.
     */
    function _joinDsr(uint256 amount_) private returns (uint256) {
        require(amount_ > 0, "DS: nothing to join");
        uint256 initialDaiBalance_ = IERC20(depositToken).balanceOf(address(this));

        daiDsrManager.join(address(this), amount_);

        uint256 newDaiBalance_ = IERC20(depositToken).balanceOf(address(this));
        uint256 depositedAmount_ = initialDaiBalance_ - newDaiBalance_;
        require(depositedAmount_ > 0, "DS: DSR join failed");

        return depositedAmount_;
    }

    /**
     * @dev Withdraws the specified amount of DAI from the Dai Savings Rate (DSR) system.
     * @param amount_ The amount of DAI to withdraw from DSR.
     * @return The actual amount of DAI withdrawn, which may differ slightly from the input amount.
     */
    function _exitDsr(uint256 amount_) private returns (uint256) {
        require(amount_ > 0, "DS: nothing to exit");
        uint256 initialDaiBalance_ = IERC20(depositToken).balanceOf(address(this));

        daiDsrManager.exit(address(this), amount_);

        uint256 newDaiBalance_ = IERC20(depositToken).balanceOf(address(this));
        uint256 exitedAmount_ = newDaiBalance_ - initialDaiBalance_;
        require(exitedAmount_ > 0, "DS: DSR exit failed");

        return exitedAmount_;
    }

    function _stake(address user_, uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) private {
        require(amount_ > 0, "DS: nothing to stake");

        Pool storage pool = pools[poolId_];
        PoolData storage poolData = poolsData[poolId_];
        UserData storage userData = usersData[user_][poolId_];

        IERC20(depositToken).safeTransferFrom(_msgSender(), address(this), amount_);

        // only credit the user for the actual amount that landed in the DSR
        amount_ = _joinDsr(amount_);

        require((userData.deposited + amount_) >= pool.minimalStake, "DS: amount too low");

        totalDepositedInPublicPools += amount_;

        // Update pool data
        poolData.lastUpdate = uint128(block.timestamp);
        poolData.totalDeposited += amount_;

        // Update user data
        userData.lastStake = uint128(block.timestamp);
        userData.deposited += amount_;

        emit UserStaked(poolId_, user_, amount_, arweaveAddress_);
    }

    function _withdraw(address user_, uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) private {
        require(amount_ > 0, "DS: nothing to withdraw");
        Pool storage pool = pools[poolId_];
        PoolData storage poolData = poolsData[poolId_];
        UserData storage userData = usersData[user_][poolId_];

        uint256 deposited_ = userData.deposited;
        require(deposited_ > 0, "DS: user isn't staked");

        if (amount_ > deposited_) {
            amount_ = deposited_;
        }

        uint256 newDeposited_;
        require(
            (block.timestamp > userData.lastStake + pool.withdrawLockPeriodAfterStake),
            "DS: pool withdraw is locked"
        );

        uint256 depositTokenContractBalance_ = daiDsrManager.daiBalance(address(this));
        require(amount_ <= depositTokenContractBalance_, "DS: amount is greater than contract balance");
        uint256 dsrExitedAmount_ = _exitDsr(amount_);
        amount_ = dsrExitedAmount_;

        newDeposited_ = deposited_ - amount_;
        require(newDeposited_ >= pool.minimalStake || newDeposited_ == 0, "DS: invalid withdraw amount");

        // Update pool data
        poolData.lastUpdate = uint128(block.timestamp);
        poolData.totalDeposited -= amount_;

        // Update user data
        userData.deposited = newDeposited_;

        totalDepositedInPublicPools -= amount_;

        IERC20(depositToken).safeTransfer(user_, amount_);

        emit UserWithdrawn(poolId_, user_, amount_, arweaveAddress_);
    }

    function _poolExists(uint256 poolId_) private view returns (bool) {
        return poolId_ < pools.length;
    }

    /**********************************************************************************************/
    /*** Bridge                                                                                 ***/
    /**********************************************************************************************/

    function calculateOverplus() public returns (uint256) {
        uint256 depositTokenContractBalance_ = daiDsrManager.daiBalance(address(this));
        if (depositTokenContractBalance_ <= totalDepositedInPublicPools) {
            return 0;
        }
        uint256 overplus = depositTokenContractBalance_ - totalDepositedInPublicPools;

        emit CalculateOverplusResult(depositTokenContractBalance_, overplus);

        return overplus;
    }

    function bridgeOverplus() external {
        uint256 overplus_ = calculateOverplus();
        require(overplus_ > 0, "DS: overplus is zero");

        _exitDsr(overplus_);
        uint256 currentContractDaiBalance = IERC20(depositToken).balanceOf(address(this));
        require(currentContractDaiBalance > 0, "DS: contract has no DAI balance");

        IERC20(depositToken).safeTransfer(aoDistributionWallet, currentContractDaiBalance);

        emit OverplusBridged(overplus_);
    }

    /**********************************************************************************************/
    /*** UUPS                                                                                   ***/
    /**********************************************************************************************/

    function removeUpgradeability() external onlyOwner {
        isNotUpgradeable = true;
    }

    function _authorizeUpgrade(address) internal view override onlyOwner {
        require(!isNotUpgradeable, "DS: upgrade isn't available");
    }

    /**********************************************************************************************/
    /*** Ejection Handling                                                                                ***/
    /**********************************************************************************************/

    // Helper function to safely reduce values ensuring no underflow occurs
    function safeReduce(uint256 total, uint256 amount) private pure returns (uint256) {
        return amount > total ? total : amount;
    }

    function ejectStakedFunds(uint256 poolId, address user) external onlyRefunder {
        require(user != address(0), "DS: user is the zero address");

        UserData storage userData = usersData[user][poolId];
        uint256 amountToTransfer = userData.deposited;
        if (amountToTransfer > 0) {
            // Clear userData to prepare for transfer
            userData.deposited = 0;
            // Update pool and global state before transferring funds
            PoolData storage poolData = poolsData[poolId];

            // Reduce the total deposited amount in the pool data
            uint256 actualAmountToTransfer = safeReduce(poolData.totalDeposited, amountToTransfer);
            poolData.totalDeposited -= actualAmountToTransfer;

            actualAmountToTransfer = safeReduce(totalDepositedInPublicPools, amountToTransfer);
            totalDepositedInPublicPools -= actualAmountToTransfer;

            // Perform the transfer
            uint256 dsrExitedAmount_ = _exitDsr(actualAmountToTransfer);
            IERC20(depositToken).safeTransfer(user, dsrExitedAmount_);

            bytes32 zeroBytes_ = 0x0000000000000000000000000000000000000000000000000000000000000000;

            // Emit successful withdrawal event
            emit UserWithdrawn(poolId, user, amountToTransfer, zeroBytes_);
        }
    }
}
IDistribution.sol 181 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/**
 * This is Distribution contract that stores all the pools and users data.
 * It is used to calculate the user's rewards and operate with overpluses.
 */
interface IDistribution {
    /**
     * The structure that stores the core pool's data.
     * @param withdrawLockPeriodAfterStake The period in seconds when the user can't withdraw his stake after staking.
     * @param minimalStake The minimal stake amount.
     * @param isPublic The flag that indicates if the pool is public.
     */
    struct Pool {
        uint128 withdrawLockPeriodAfterStake;
        uint256 minimalStake;
        bool isPublic;
    }

    /**
     * The structure that stores the pool's rate data.
     * @param lastUpdate The timestamp when the pool was updated.
     * @param rate The current reward rate.
     * @param totalDeposited The total amount of tokens deposited in the pool.
     */
    struct PoolData {
        uint128 lastUpdate;
        uint256 totalDeposited;
    }

    /**
     * The structure that stores the user's rate data of pool.
     * @param lastStake The timestamp when the user last staked tokens.
     * @param deposited The amount of tokens deposited in the pool.
     * @param rate The current reward rate.
     * @param pendingRewards The amount of pending rewards.
     */
    struct UserData {
        uint128 lastStake;
        uint256 deposited;
    }

    /**
     * The event that is emitted when the pool is created.
     * @param poolId The pool's id.
     * @param pool The pool's data.
     */
    event PoolCreated(uint256 indexed poolId, Pool pool);

    /**
     * The event that is emitted when the current DAI balance of the contract is updated.
     * @param dsrDaiBalance The current DAI balance.
     * @param currentOverplus The current overplus.
     */
    event CalculateOverplusResult(uint256 dsrDaiBalance, uint256 currentOverplus);

    /**
     * The event that is emitted when the pool is edited.
     * @param poolId The pool's id.
     * @param pool The pool's data.
     */
    event PoolEdited(uint256 indexed poolId, Pool pool);

    /**
     * The event that is emitted when the user stakes tokens in the pool.
     * @param poolId The pool's id.
     * @param user The user's address.
     * @param amount The amount of tokens.
     * @param arweaveAddress The arweave address.
     */
    event UserStaked(uint256 indexed poolId, address indexed user, uint256 amount, bytes32 arweaveAddress);

    /**
     * The event that is emitted when the user claims rewards from the pool.
     * @param poolId The pool's id.
     * @param user The user's address.
     * @param receiver The receiver's address.
     * @param amount The amount of tokens.
     */
    event UserClaimed(uint256 indexed poolId, address indexed user, address receiver, uint256 amount);

    /**
     * The event that is emitted when the user withdraws tokens from the pool.
     * @param poolId The pool's id.
     * @param user The user's address.
     * @param amount The amount of tokens.
     * @param arweaveAddress The arweave address.
     */
    event UserWithdrawn(uint256 indexed poolId, address indexed user, uint256 amount, bytes32 arweaveAddress);

    /**
     * The event that is emitted when the overplus of the deposit tokens is bridged.
     */
    event OverplusBridged(uint256 amount);

    /**
     * The function to initialize the contract.
     * @param aoDistributionWallet_ The address of distribution wallet.
     * @param poolsInfo_ The array of initial pools.
     * @param refunderAddress The address of the refunder contract.
     * @param fallbackAddress The address of the fallback contract.
     */
    function Distribution_init(
        address aoDistributionWallet_,
        Pool[] calldata poolsInfo_,
        address refunderAddress,
        address fallbackAddress
    ) external;

    /**
     * The function to create a new pool.
     * @param pool_ The pool's data.
     */
    function createPool(Pool calldata pool_) external;

    /**
     * The function to stake tokens in the public pool.
     * @param poolId_ The pool's id.
     * @param amount_ The amount of tokens to stake.
     * @param arweaveAddress_ The arweave address.
     */
    function stake(uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) external;

    /**
     * The function to withdraw tokens from the pool.
     * @param poolId_ The pool's id.
     * @param amount_ The amount of tokens to withdraw.
     * @param arweaveAddress_ The arweave address.
     */
    function withdraw(uint256 poolId_, uint256 amount_, bytes32 arweaveAddress_) external;

    /**
     * The function to calculate the total overplus of the staked deposit tokens.
     * @return The total overplus amount.
     */
    function calculateOverplus() external returns (uint256);

    /**
     * The function to bridge the overplus of the staked deposit tokens.
     */
    function bridgeOverplus() external;

    /**
     * The function to remove upgradeability.
     */
    function removeUpgradeability() external;

    /**
     * The function to check if the contract is upgradeable.
     * @return The flag that indicates if the contract is upgradeable.
     */
    function isNotUpgradeable() external view returns (bool);

    /**
     * The function to get the address of deposit token.
     * @return The address of deposit token.
     */
    function depositToken() external view returns (address);

    /**
     * The function to get the address of bridge contract.
     * @return The address of bridge contract.
     */
    function aoDistributionWallet() external view returns (address);

    /**
     * The function to get the amount of deposit tokens that are staked in all of the public pools.
     * @dev The value accumulates the amount amount despite the rate differences.
     * @return The amount of deposit tokens.
     */
    function totalDepositedInPublicPools() external view returns (uint256);

    /**
     * The function to eject funds for a user.
     * Can only be called by the Refunder contract.
     * @param poolId The pool's id.
     * @param user The address of the user to refund.
     */
    function ejectStakedFunds(uint256 poolId, address user) external;
}
IDaiDsrManager.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IDaiDsrManager {
    function daiBalance(address usr) external returns (uint256 wad);
    function join(address dst, uint256 wad) external;
    function exit(address dst, uint256 wad) external;
}
Globals.sol 6 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

uint256 constant PRECISION = 10 ** 25;
uint256 constant DECIMAL = 10 ** 18;
uint256 constant PERCENTAGE_100 = 10 ** 27;
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
        }
    }
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

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

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @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.isContract(address(token));
    }
}
IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @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.
 */
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].
     */
    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);
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
        }
    }
}
ContextUpgradeable.sol 37 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../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;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}
OwnableUpgradeable.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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 {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @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 Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _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 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _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() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @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 {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}
UUPSUpgradeable.sol 112 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
        return _IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data, true);
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeTo} and {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal override onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}
StorageSlotUpgradeable.sol 138 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @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(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlotUpgradeable {
    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
        }
    }
}
IERC1967Upgradeable.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967Upgradeable {
    /**
     * @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);
}
IBeaconUpgradeable.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}
draft-IERC1822Upgradeable.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}
ERC1967UpgradeUpgradeable.sol 170 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
    function __ERC1967Upgrade_init() internal onlyInitializing {
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {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 bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

Read Contract

aoDistributionWallet 0xa06b2a39 → address
daiDsrManager 0x4f9ea6e9 → address
daiDsrManagerAddress 0x6b04c18a → address
depositToken 0xc89039c5 → address
isNotUpgradeable 0xe0b4b386 → bool
owner 0x8da5cb5b → address
pools 0xac4afa38 → uint128, uint256, bool
poolsData 0xf343e858 → uint128, uint256
proxiableUUID 0x52d1902d → bytes32
totalDepositedInPublicPools 0xd2ba5e3a → uint256
usersData 0x30dc6308 → uint128, uint256

Write Contract 12 functions

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

Distribution_init 0x6dffe356
address aoDistributionWallet_
tuple[] poolsInfo_
address refunderAddress_
address fallbackAddress_
bridgeOverplus 0x8901579e
No parameters
calculateOverplus 0xe2d94dbd
No parameters
returns: uint256
createPool 0xe6550fd9
tuple pool_
ejectStakedFunds 0xdd2518f3
uint256 poolId
address user
removeUpgradeability 0xbeee9fa9
No parameters
renounceOwnership 0x715018a6
No parameters
stake 0x3d0a42e7
uint256 poolId_
uint256 amount_
bytes32 arweaveAddress_
transferOwnership 0xf2fde38b
address newOwner
upgradeTo 0x3659cfe6
address newImplementation
upgradeToAndCall 0x4f1ef286
address newImplementation
bytes data
withdraw 0x3756c011
uint256 poolId_
uint256 amount_
bytes32 arweaveAddress_

Recent Transactions

No transactions found for this address