Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xA9d997F6952e69BC7aD930a4b344632A6e951d0B
Balance 0 ETH
Nonce 1
Code Size 21112 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

21112 bytes
0x60806040526004361061039b5760003560e01c8063853828b6116101dc578063b6e2b52011610102578063d9f00ec7116100a0578063de5f62681161006f578063de5f626814610bea578063e752923914610bff578063ee7afe2d14610c15578063f6ca71b014610c2a57600080fd5b8063d9f00ec714610b4c578063dbe55e5614610b6c578063dd505df614610ba0578063de34d71314610bd457600080fd5b8063cceab750116100dc578063cceab75014610ac1578063d059f6ef14610af5578063d38bfff414610b0c578063d9caed1214610b2c57600080fd5b8063b6e2b52014610a6c578063c2e1e3f414610a8c578063c7af335214610aac57600080fd5b80639da0e4621161017a578063ab12edf511610149578063ab12edf5146109e6578063ad1728cb14610a06578063ad5c464814610a1b578063b16b7d0b14610a4f57600080fd5b80639da0e46214610927578063a3b81e7314610964578063a4f98af414610984578063aa388af61461099957600080fd5b80639092c31c116101b65780639092c31c1461087f5780639136616a146108b357806391649751146108d357806396d538bb1461090757600080fd5b8063853828b61461082557806387bae8671461083a5780638d7c0e461461085f57600080fd5b80635c975abb116102c15780636ef387951161025f5780637b2d9b2c1161022e5780637b2d9b2c146107c45780637b8962f7146107e4578063842f5c46146107fa5780638456cb591461081057600080fd5b80636ef3879514610730578063714897df1461075057806371a735f3146107845780637260f826146107a457600080fd5b8063630923831161029b57806363092383146106c457806366e3667e146106da57806367c7066c146106f05780636e811d381461071057600080fd5b80635c975abb1461066b5780635d36b1901461068f5780635f515226146106a457600080fd5b80633c86495911610339578063484be81211610308578063484be812146106005780635205c3801461061657806359b80c0a146106365780635a063f631461065657600080fd5b80633c86495914610568578063430bf08a1461058c578063435356d1146105c057806347e7ef24146105e057600080fd5b80630fc3b4c4116103755780630fc3b4c4146104dd5780631072cbea1461051357806313cf69dd1461053357806322495dc81461054857600080fd5b80630c340a24146104575780630df1ecfd146104895780630ed57b3a146104bd57600080fd5b3661045257336001600160a01b037f0000000000000000000000007ed4ccb74a1ee903af5fbd9be00ca8616f23d6271614806103ff5750336001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216145b6104505760405162461bcd60e51b815260206004820152601e60248201527f457468206e6f742066726f6d20616c6c6f77656420636f6e747261637473000060448201526064015b60405180910390fd5b005b600080fd5b34801561046357600080fd5b5061046c610c4c565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561049557600080fd5b5061046c7f0000000000000000000000009d65ff81a3c488d585bbfb0bfe3c7707c7917f5481565b3480156104c957600080fd5b506104506104d836600461433d565b610c69565b3480156104e957600080fd5b5061046c6104f8366004614376565b609f602052600090815260409020546001600160a01b031681565b34801561051f57600080fd5b5061045061052e366004614393565b610c9b565b34801561053f57600080fd5b50610450610d56565b34801561055457600080fd5b506104506105633660046144f1565b610df3565b34801561057457600080fd5b5061057e60695481565b604051908152602001610480565b34801561059857600080fd5b5061046c7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81565b3480156105cc57600080fd5b506104506105db36600461461e565b610f2e565b3480156105ec57600080fd5b506104506105fb366004614393565b611162565b34801561060c57600080fd5b5061057e606a5481565b34801561062257600080fd5b506104506106313660046146af565b61125d565b34801561064257600080fd5b5061045061065136600461472b565b6112bc565b34801561066257600080fd5b50610450611537565b34801561067757600080fd5b5060335460ff165b6040519015158152602001610480565b34801561069b57600080fd5b506104506115d6565b3480156106b057600080fd5b5061057e6106bf366004614376565b61167c565b3480156106d057600080fd5b5061057e611c2081565b3480156106e657600080fd5b5061057e60345481565b3480156106fc57600080fd5b5060a35461046c906001600160a01b031681565b34801561071c57600080fd5b5061045061072b366004614376565b61177e565b34801561073c57600080fd5b5061045061074b3660046147e9565b6117f4565b34801561075c57600080fd5b5061057e7f00000000000000000000000000000000000000000000000000000000000001f481565b34801561079057600080fd5b5061045061079f36600461486b565b611da7565b3480156107b057600080fd5b5060365461046c906001600160a01b031681565b3480156107d057600080fd5b5061046c6107df3660046146af565b611f90565b3480156107f057600080fd5b5061057e60375481565b34801561080657600080fd5b5061057e60685481565b34801561081c57600080fd5b50610450611fba565b34801561083157600080fd5b50610450612074565b34801561084657600080fd5b5060335461046c9061010090046001600160a01b031681565b34801561086b57600080fd5b5061045061087a3660046148f0565b612237565b34801561088b57600080fd5b5061046c7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81565b3480156108bf57600080fd5b506104506108ce3660046146af565b61271b565b3480156108df57600080fd5b5061046c7f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e181565b34801561091357600080fd5b506104506109223660046147e9565b6128e7565b34801561093357600080fd5b506109576109423660046146af565b60356020526000908152604090205460ff1681565b6040516104809190614932565b34801561097057600080fd5b5061045061097f366004614376565b6129fe565b34801561099057600080fd5b5061067f612a6c565b3480156109a557600080fd5b5061067f6109b4366004614376565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0390811691161490565b3480156109f257600080fd5b50610450610a0136600461495a565b612b0c565b348015610a1257600080fd5b50610450612bf8565b348015610a2757600080fd5b5061046c7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b348015610a5b57600080fd5b5061057e6801bc16d674ec80000081565b348015610a7857600080fd5b50610450610a873660046144f1565b612caf565b348015610a9857600080fd5b50610450610aa7366004614376565b612d23565b348015610ab857600080fd5b5061067f612db0565b348015610acd57600080fd5b5061046c7f00000000000000000000000000000000219ab540356cbb839cbe05303d7705fa81565b348015610b0157600080fd5b5061057e6101075481565b348015610b1857600080fd5b50610450610b27366004614376565b612de1565b348015610b3857600080fd5b50610450610b4736600461497c565b612e85565b348015610b5857600080fd5b50610450610b673660046149bd565b612f5f565b348015610b7857600080fd5b5061046c7f000000000000000000000000000000000000000000000000000000000000000081565b348015610bac57600080fd5b5061046c7f0000000000000000000000007ed4ccb74a1ee903af5fbd9be00ca8616f23d62781565b348015610be057600080fd5b5061057e60385481565b348015610bf657600080fd5b50610450613120565b348015610c0b57600080fd5b5061057e606b5481565b348015610c2157600080fd5b5061045061327e565b348015610c3657600080fd5b50610c3f613308565b6040516104809190614a2c565b6000610c646000805160206152238339815191525490565b905090565b610c71612db0565b610c8d5760405162461bcd60e51b815260040161044790614a78565b610c97828261336a565b5050565b610ca3612db0565b610cbf5760405162461bcd60e51b815260040161044790614a78565b6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811690831603610d3a5760405162461bcd60e51b815260206004820152601f60248201527f43616e6e6f74207472616e7366657220737570706f72746564206173736574006044820152606401610447565b610c97610d45610c4c565b6001600160a01b03841690836134c9565b6040516336f370b360e21b81526001600160a01b037f0000000000000000000000007ed4ccb74a1ee903af5fbd9be00ca8616f23d627811660048301527f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e1169063dbcdc2cc90602401600060405180830381600087803b158015610dd957600080fd5b505af1158015610ded573d6000803e3d6000fd5b50505050565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e759190614aaf565b6001600160a01b0316336001600160a01b031614610ea55760405162461bcd60e51b815260040161044790614acc565b60405163bc26e7e560e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e1169063bc26e7e590610ef7903090879087908790600401614b92565b600060405180830381600087803b158015610f1157600080fd5b505af1158015610f25573d6000803e3d6000fd5b50505050505050565b610f36612db0565b610f525760405162461bcd60e51b815260040161044790614a78565b600054610100900460ff1680610f6b575060005460ff16155b610fce5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610447565b600054610100900460ff16158015610ff0576000805461ffff19166101011790555b610ffb848484613520565b60405163095ea7b360e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e18116600483015260001960248301527f0000000000000000000000009d65ff81a3c488d585bbfb0bfe3c7707c7917f54169063095ea7b3906044016020604051808303816000875af115801561108b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110af9190614bd5565b506040516336f370b360e21b81526001600160a01b037f0000000000000000000000007ed4ccb74a1ee903af5fbd9be00ca8616f23d627811660048301527f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e1169063dbcdc2cc90602401600060405180830381600087803b15801561113357600080fd5b505af1158015611147573d6000803e3d6000fd5b505050508015610ded576000805461ff001916905550505050565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab16146111aa5760405162461bcd60e51b815260040161044790614bf2565b600080516020615203833981519152805460011981016111dc5760405162461bcd60e51b815260040161044790614c29565b600282557f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316846001600160a01b0316146112315760405162461bcd60e51b815260040161044790614c51565b8261010760008282546112449190614c92565b90915550611254905084846135d3565b50600190555050565b611265612db0565b6112815760405162461bcd60e51b815260040161044790614a78565b60378190556040518181527fe26b067424903962f951f568e52ec9a3bbe1589526ea54a4e69ca6eaae1a4c779060200160405180910390a150565b60335461010090046001600160a01b031633146112eb5760405162461bcd60e51b815260040161044790614ca5565b60335460ff161561130e5760405162461bcd60e51b815260040161044790614cdc565b86831461135d5760405162461bcd60e51b815260206004820152601a60248201527f5075626b65792073686172657344617461206d69736d617463680000000000006044820152606401610447565b60008060005b8981101561149e578a8a8281811061137d5761137d614d06565b905060200281019061138f9190614d1c565b60405161139d929190614d62565b6040805191829003909120600081815260356020529182205490945060ff1692508260048111156113d0576113d061491c565b1461141d5760405162461bcd60e51b815260206004820152601c60248201527f56616c696461746f7220616c72656164792072656769737465726564000000006044820152606401610447565b6000838152603560205260409020805460ff19166001179055827facd38e900350661e325d592c959664c0000a306efb2004e7dc283f44e0ea04238c8c8481811061146a5761146a614d06565b905060200281019061147c9190614d1c565b8c8c60405161148e9493929190614dd9565b60405180910390a2600101611363565b506040516322f18bf560e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e116906322f18bf5906114f9908d908d908d908d908d908d908d908d90600401614efe565b600060405180830381600087803b15801561151357600080fd5b505af1158015611527573d6000803e3d6000fd5b5050505050505050505050505050565b60a3546001600160a01b031633146115915760405162461bcd60e51b815260206004820152601b60248201527f43616c6c6572206973206e6f74207468652048617276657374657200000000006044820152606401610447565b600080516020615203833981519152805460011981016115c35760405162461bcd60e51b815260040161044790614c29565b600282556115cf613665565b5060019055565b7f44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db546001600160a01b0316336001600160a01b0316146116715760405162461bcd60e51b815260206004820152603060248201527f4f6e6c79207468652070656e64696e6720476f7665726e6f722063616e20636f60448201526f6d706c6574652074686520636c61696d60801b6064820152608401610447565b61167a3361389b565b565b60007f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316826001600160a01b0316146116cf5760405162461bcd60e51b815260040161044790614c51565b6040516370a0823160e01b81523060048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa158015611733573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117579190614f5f565b6801bc16d674ec80000060345461176e9190614f78565b6117789190614c92565b92915050565b611786612db0565b6117a25760405162461bcd60e51b815260040161044790614a78565b60338054610100600160a81b0319166101006001600160a01b038416908102919091179091556040517f83f29c79feb71f8fba9d0fbc4ba5f0982a28b6b1e868b3fc50e6400d100bca0f90600090a250565b60335461010090046001600160a01b031633146118235760405162461bcd60e51b815260040161044790614ca5565b60335460ff16156118465760405162461bcd60e51b815260040161044790614cdc565b600080516020615203833981519152805460011981016118785760405162461bcd60e51b815260040161044790614c29565b6002825560006118916801bc16d674ec80000085614f78565b6040516370a0823160e01b81523060048201529091507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa1580156118f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061191c9190614f5f565b81111561195f5760405162461bcd60e51b8152602060048201526011602482015270092dce6eaccccd2c6d2cadce840ae8aa89607b1b6044820152606401610447565b6034547f00000000000000000000000000000000000000000000000000000000000001f49061198f908690614c92565b11156119d65760405162461bcd60e51b815260206004820152601660248201527513585e081d985b1a59185d1bdc9cc81c995858da195960521b6044820152606401610447565b603754816038546119e79190614c92565b1115611a355760405162461bcd60e51b815260206004820152601a60248201527f5374616b696e6720455448206f766572207468726573686f6c640000000000006044820152606401610447565b8060386000828254611a479190614c92565b9091555050604051632e1a7d4d60e01b8152600481018290527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031690632e1a7d4d90602401600060405180830381600087803b158015611aae57600080fd5b505af1158015611ac2573d6000803e3d6000fd5b50505050611acf816138fa565b60408051600160f81b60208201526000602182018190526bffffffffffffffffffffffff193060601b16602c8301529101604051602081830303815290604052905060005b85811015611d80576000878783818110611b3057611b30614d06565b9050602002810190611b429190614f8f565b611b4c9080614d1c565b604051611b5a929190614d62565b6040519081900390209050600160008281526035602052604090205460ff166004811115611b8a57611b8a61491c565b14611bd75760405162461bcd60e51b815260206004820152601860248201527f56616c696461746f72206e6f74207265676973746572656400000000000000006044820152606401610447565b7f00000000000000000000000000000000219ab540356cbb839cbe05303d7705fa6001600160a01b031663228951186801bc16d674ec8000008a8a86818110611c2257611c22614d06565b9050602002810190611c349190614f8f565b611c3e9080614d1c565b878d8d89818110611c5157611c51614d06565b9050602002810190611c639190614f8f565b611c71906020810190614d1c565b8f8f8b818110611c8357611c83614d06565b9050602002810190611c959190614f8f565b604001356040518863ffffffff1660e01b8152600401611cba96959493929190614fff565b6000604051808303818588803b158015611cd357600080fd5b505af1158015611ce7573d6000803e3d6000fd5b5050506000838152603560205260409020805460ff19166002179055508190507f958934bb53d6b4dc911b6173e586864efbc8076684a31f752c53d5778340b37f898985818110611d3a57611d3a614d06565b9050602002810190611d4c9190614f8f565b611d569080614d1c565b6801bc16d674ec800000604051611d6f9392919061504e565b60405180910390a250600101611b14565b508585905060346000828254611d969190614c92565b909155505060019093555050505050565b60335461010090046001600160a01b03163314611dd65760405162461bcd60e51b815260040161044790614ca5565b60335460ff1615611df95760405162461bcd60e51b815260040161044790614cdc565b60008585604051611e0b929190614d62565b604080519182900390912060008181526035602052919091205490915060ff166003816004811115611e3f57611e3f61491c565b1480611e5c57506001816004811115611e5a57611e5a61491c565b145b611ea85760405162461bcd60e51b815260206004820152601d60248201527f56616c696461746f72206e6f742072656764206f722065786974696e670000006044820152606401610447565b6040516312b3fc1960e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e116906312b3fc1990611efc908a908a908a908a908a90600401615072565b600060405180830381600087803b158015611f1657600080fd5b505af1158015611f2a573d6000803e3d6000fd5b50505060008381526035602052604090819020805460ff19166004179055518391507f6aecca20726a17c1b81989b2fd09dfdf636bae9e564d4066ca18df62dc1f3dc290611f7f908a908a908a908a90614dd9565b60405180910390a250505050505050565b60a48181548110611fa057600080fd5b6000918252602090912001546001600160a01b0316905081565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612018573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061203c9190614aaf565b6001600160a01b0316336001600160a01b03161461206c5760405162461bcd60e51b815260040161044790614acc565b61167a613927565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab1614806120c357506120ae610c4c565b6001600160a01b0316336001600160a01b0316145b61211b5760405162461bcd60e51b815260206004820152602360248201527f43616c6c6572206973206e6f7420746865205661756c74206f7220476f7665726044820152623737b960e91b6064820152608401610447565b6000805160206152038339815191528054600119810161214d5760405162461bcd60e51b815260040161044790614c29565b600282556040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa1580156121b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121dc9190614f5f565b9050801561222f5761222f7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28361399c565b505060019055565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612295573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122b99190614aaf565b6001600160a01b0316336001600160a01b0316146122e95760405162461bcd60e51b815260040161044790614acc565b60335460ff166123325760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610447565b600080516020615203833981519152805460011981016123645760405162461bcd60e51b815260040161044790614c29565b6002825543611c20606b546123799190614c92565b106123c65760405162461bcd60e51b815260206004820152601e60248201527f466978206163636f756e74696e672063616c6c656420746f6f20736f6f6e00006044820152606401610447565b60021985121580156123d9575060038513155b80156123f357506000856034546123f091906150b3565b12155b61243f5760405162461bcd60e51b815260206004820152601760248201527f496e76616c69642076616c696461746f727344656c74610000000000000000006044820152606401610447565b6811ff6cf0fd15afffff19841215801561246257506811ff6cf0fd15b000008413155b801561247c575060008460685461247991906150b3565b12155b6124c85760405162461bcd60e51b815260206004820152601d60248201527f496e76616c696420636f6e73656e7375735265776172647344656c74610000006044820152606401610447565b68053444835ec58000008311156125215760405162461bcd60e51b815260206004820152601960248201527f496e76616c69642077657468546f5661756c74416d6f756e74000000000000006044820152606401610447565b8460345461252f91906150b3565b6034556068546125409085906150b3565b60685543606b55821561267f577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0846040518263ffffffff1660e01b81526004016000604051808303818588803b1580156125a857600080fd5b505af11580156125bc573d6000803e3d6000fd5b505060405163a9059cbb60e01b81526001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81166004830152602482018890527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216935063a9059cbb925060440190506020604051808303816000875af1158015612651573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126759190614bd5565b5061267f83613a9a565b60408051868152602081018690529081018490527f80d022717ea022455c5886b8dd8a29c037570aae58aeb4d7b136d7a10ec2e4319060600160405180910390a16126ca6000613b02565b6127095760405162461bcd60e51b815260206004820152601060248201526f233ab9b29039ba34b63610313637bbb760811b6044820152606401610447565b612711613f6d565b5060019055505050565b612723612db0565b61273f5760405162461bcd60e51b815260040161044790614a78565b60a05481106127805760405162461bcd60e51b815260206004820152600d60248201526c092dcecc2d8d2c840d2dcc8caf609b1b6044820152606401610447565b600060a0828154811061279557612795614d06565b60009182526020808320909101546001600160a01b03908116808452609f90925260409092205460a054919350909116906127d2906001906150db565b8310156128545760a080546127e9906001906150db565b815481106127f9576127f9614d06565b60009182526020909120015460a080546001600160a01b03909216918590811061282557612825614d06565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b031602179055505b60a0805480612865576128656150ee565b60008281526020808220600019908401810180546001600160a01b031990811690915593019093556001600160a01b03858116808352609f855260409283902080549094169093559051908416815290917f16b7600acff27e39a8a96056b3d533045298de927507f5c1d97e4accde60488c91015b60405180910390a2505050565b6128ef612db0565b61290b5760405162461bcd60e51b815260040161044790614a78565b8060005b818110156129b557600084848381811061292b5761292b614d06565b90506020020160208101906129409190614376565b6001600160a01b0316036129ad5760405162461bcd60e51b815260206004820152602e60248201527f43616e206e6f742073657420616e20656d70747920616464726573732061732060448201526d30903932bbb0b932103a37b5b2b760911b6064820152608401610447565b60010161290f565b507f04c0b9649497d316554306e53678d5f5f5dbc3a06f97dec13ff4cfe98b986bbc60a484846040516129ea93929190615104565b60405180910390a1610ded60a4848461425b565b612a06612db0565b612a225760405162461bcd60e51b815260040161044790614a78565b603680546001600160a01b0319166001600160a01b0383169081179091556040517f3329861a0008b3348767567d2405492b997abd79a088d0f2cef6b1a09a8e7ff790600090a250565b60335460009061010090046001600160a01b03163314612a9e5760405162461bcd60e51b815260040161044790614ca5565b60335460ff1615612ac15760405162461bcd60e51b815260040161044790614cdc565b60008051602061520383398151915280546001198101612af35760405162461bcd60e51b815260040161044790614c29565b60028255612b016001613b02565b925060018255505090565b612b14612db0565b612b305760405162461bcd60e51b815260040161044790614a78565b8082108015612b4757506801bc16d674ec80000081105b8015612b645750673782dace9d900000612b6183836150db565b10155b612bb05760405162461bcd60e51b815260206004820152601760248201527f496e636f7272656374206675736520696e74657276616c0000000000000000006044820152606401610447565b6069829055606a81905560408051838152602081018390527fcb8d24e46eb3c402bf344ee60a6576cba9ef2f59ea1af3b311520704924e901a91015b60405180910390a15050565b60405163095ea7b360e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e18116600483015260001960248301527f0000000000000000000000009d65ff81a3c488d585bbfb0bfe3c7707c7917f54169063095ea7b3906044016020604051808303816000875af1158015612c88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cac9190614bd5565b50565b612cb7612db0565b612cd35760405162461bcd60e51b815260040161044790614a78565b604051631a1b9a0b60e21b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e1169063686e682c90610ef790869086908690600401615193565b612d2b612db0565b612d475760405162461bcd60e51b815260040161044790614a78565b60a354604080516001600160a01b03928316815291831660208301527fe48386b84419f4d36e0f96c10cc3510b6fb1a33795620c5098b22472bbe90796910160405180910390a160a380546001600160a01b0319166001600160a01b0392909216919091179055565b6000612dc86000805160206152238339815191525490565b6001600160a01b0316336001600160a01b031614905090565b612de9612db0565b612e055760405162461bcd60e51b815260040161044790614a78565b612e2d817f44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db55565b806001600160a01b0316612e4d6000805160206152238339815191525490565b6001600160a01b03167fa39cc5eb22d0f34d8beaefee8a3f17cc229c1a1d1ef87a5ad47313487b1c4f0d60405160405180910390a350565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab1614612ecd5760405162461bcd60e51b815260040161044790614bf2565b60008051602061520383398151915280546001198101612eff5760405162461bcd60e51b815260040161044790614c29565b600282557f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316846001600160a01b031614612f545760405162461bcd60e51b815260040161044790614c51565b61271185858561399c565b60335461010090046001600160a01b03163314612f8e5760405162461bcd60e51b815260040161044790614ca5565b60335460ff1615612fb15760405162461bcd60e51b815260040161044790614cdc565b60008484604051612fc3929190614d62565b604080519182900390912060008181526035602052919091205490915060ff166002816004811115612ff757612ff761491c565b1461303b5760405162461bcd60e51b815260206004820152601460248201527315985b1a59185d1bdc881b9bdd081cdd185ad95960621b6044820152606401610447565b604051633877322b60e01b81526001600160a01b037f000000000000000000000000dd9bc35ae942ef0cfa76930954a156b3ff30a4e11690633877322b9061308d908990899089908990600401614dd9565b600060405180830381600087803b1580156130a757600080fd5b505af11580156130bb573d6000803e3d6000fd5b50505060008381526035602052604090819020805460ff19166003179055518391507f8c2e15303eb94e531acc988c2a01d1193bdaaa15eda7f16dda85316ed463578d90613110908990899089908990614dd9565b60405180910390a2505050505050565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab16146131685760405162461bcd60e51b815260040161044790614bf2565b6000805160206152038339815191528054600119810161319a5760405162461bcd60e51b815260040161044790614c29565b600282556040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa158015613205573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132299190614f5f565b90506000610107548261323c91906150db565b90508015613274576101078290556132747f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2826135d3565b5050600182555050565b6036546001600160a01b031633146132d85760405162461bcd60e51b815260206004820152601960248201527f43616c6c6572206973206e6f7420746865204d6f6e69746f72000000000000006044820152606401610447565b600060388190556040517fe765a88a37047c5d793dce22b9ceb5a0f5039d276da139b4c7d29613f341f1109190a1565b606060a480548060200260200160405190810160405280929190818152602001828054801561336057602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613342575b5050505050905090565b6001600160a01b038281166000908152609f602052604090205416156133c75760405162461bcd60e51b81526020600482015260126024820152711c151bdad95b88185b1c9958591e481cd95d60721b6044820152606401610447565b6001600160a01b038216158015906133e757506001600160a01b03811615155b6134275760405162461bcd60e51b8152602060048201526011602482015270496e76616c69642061646472657373657360781b6044820152606401610447565b6001600160a01b038281166000818152609f6020908152604080832080549587166001600160a01b0319968716811790915560a0805460018101825594527f78fdc8d422c49ced035a9edf18d00d3c6a8d81df210f3e5e448e045e77b41e8890930180549095168417909455925190815290917fef6485b84315f9b1483beffa32aae9a0596890395e3d7521f1c5fbb51790e765910160405180910390a25050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b17905261351b908490613fe7565b505050565b82516135339060a49060208601906142be565b5081518151811461357d5760405162461bcd60e51b8152602060048201526014602482015273496e76616c696420696e7075742061727261797360601b6044820152606401610447565b60005b818110156135cc576135c484828151811061359d5761359d614d06565b60200260200101518483815181106135b7576135b7614d06565b602002602001015161336a565b600101613580565b5050505050565b6000811161361c5760405162461bcd60e51b81526020600482015260166024820152754d757374206465706f73697420736f6d657468696e6760501b6044820152606401610447565b6040805160008152602081018390526001600160a01b038416917f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f62910160405180910390a25050565b60335460ff16156136885760405162461bcd60e51b815260040161044790614cdc565b60007f0000000000000000000000007ed4ccb74a1ee903af5fbd9be00ca8616f23d6276001600160a01b031663e52253816040518163ffffffff1660e01b81526004016020604051808303816000875af11580156136ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061370e9190614f5f565b90506000606854826137209190614c92565b9050804710156137725760405162461bcd60e51b815260206004820152601860248201527f496e73756666696369656e74206574682062616c616e636500000000000000006044820152606401610447565b8015610c975760006068819055507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b1580156137db57600080fd5b505af11580156137ef573d6000803e3d6000fd5b505060a35461382f93506001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281169350169050836134c9565b60a354604080516001600160a01b0392831681527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2909216602083015281018290527ff6c07a063ed4e63808eb8da7112d46dbcd38de2b40a73dbcc9353c5a94c7235390606001612bec565b6001600160a01b0381166138f15760405162461bcd60e51b815260206004820152601a60248201527f4e657720476f7665726e6f7220697320616464726573732830290000000000006044820152606401610447565b612cac816140b9565b60006139098261010754614120565b905080610107600082825461391e91906150db565b90915550505050565b60335460ff161561394a5760405162461bcd60e51b815260040161044790614cdc565b6033805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861397f3390565b6040516001600160a01b03909116815260200160405180910390a1565b600081116139ec5760405162461bcd60e51b815260206004820152601760248201527f4d75737420776974686472617720736f6d657468696e670000000000000000006044820152606401610447565b6001600160a01b038316613a3b5760405162461bcd60e51b8152602060048201526016602482015275135d5cdd081cdc1958da599e481c9958da5c1a595b9d60521b6044820152606401610447565b613a44816138fa565b613a586001600160a01b03831684836134c9565b6040805160008152602081018390526001600160a01b038416917f2717ead6b9200dd235aad468c9809ea400fe33ac69b5bfaa6d3e90fc922b639891016128da565b6040805160008152602081018390526001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216917f2717ead6b9200dd235aad468c9809ea400fe33ac69b5bfaa6d3e90fc922b6398910160405180910390a250565b6000606854471015613b175761177882614138565b600060685447613b2791906150db565b9050600191506801bc16d674ec8000008110613cfc576000613b526801bc16d674ec800000836151bb565b90508060346000828254613b6691906150db565b9091555060009050613b81826801bc16d674ec800000614f78565b90507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b158015613bde57600080fd5b505af1158015613bf2573d6000803e3d6000fd5b505060405163a9059cbb60e01b81526001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81166004830152602482018690527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216935063a9059cbb925060440190506020604051808303816000875af1158015613c87573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613cab9190614bd5565b50613cb581613a9a565b60345460408051848152602081019290925281018290527fbe7040030ff7b347853214bf49820c6d455fedf58f3815f85c7bc5216993682b9060600160405180910390a150505b600060685447613d0c91906150db565b90506801bc16d674ec8000008110613d5e5760405162461bcd60e51b8152602060048201526015602482015274556e6578706563746564206163636f756e74696e6760581b6044820152606401610447565b80600003613d6d575050919050565b606954811015613dc7578060686000828254613d899190614c92565b90915550506040518181527f7a745a2c63a535068f52ceca27debd5297bbad5f7f37ec53d044a59d0362445d906020015b60405180910390a1613f66565b606a54811115613f55577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b158015613e2c57600080fd5b505af1158015613e40573d6000803e3d6000fd5b505060405163a9059cbb60e01b81526001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81166004830152602482018690527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216935063a9059cbb925060440190506020604051808303816000875af1158015613ed5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ef99190614bd5565b50600160346000828254613f0d91906150db565b90915550613f1c905081613a9a565b60345460408051918252602082018390527f6aa7e30787b26429ced603a7aba8b19c4b5d5bcf29a3257da953c8d53bcaa3a69101613dba565b613f5e84614138565b949350505050565b5050919050565b60335460ff16613fb65760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610447565b6033805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa3361397f565b600061403c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166141509092919063ffffffff16565b80519091501561351b578080602001905181019061405a9190614bd5565b61351b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610447565b806001600160a01b03166140d96000805160206152238339815191525490565b6001600160a01b03167fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a60405160405180910390a360008051602061522383398151915255565b600081831061412f5781614131565b825b9392505050565b6000811561414857614148613927565b506000919050565b6060613f5e848460008585843b6141a95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610447565b600080866001600160a01b031685876040516141c591906151dd565b60006040518083038185875af1925050503d8060008114614202576040519150601f19603f3d011682016040523d82523d6000602084013e614207565b606091505b5091509150614217828286614222565b979650505050505050565b60608315614231575081614131565b8251156142415782518084602001fd5b8160405162461bcd60e51b815260040161044791906151ef565b8280548282559060005260206000209081019282156142ae579160200282015b828111156142ae5781546001600160a01b0319166001600160a01b0384351617825560209092019160019091019061427b565b506142ba929150614313565b5090565b8280548282559060005260206000209081019282156142ae579160200282015b828111156142ae57825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906142de565b5b808211156142ba5760008155600101614314565b6001600160a01b0381168114612cac57600080fd5b6000806040838503121561435057600080fd5b823561435b81614328565b9150602083013561436b81614328565b809150509250929050565b60006020828403121561438857600080fd5b813561413181614328565b600080604083850312156143a657600080fd5b82356143b181614328565b946020939093013593505050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156143fd576143fd6143bf565b604052919050565b60006001600160401b0382111561441e5761441e6143bf565b5060051b60200190565b80356001600160401b038116811461443f57600080fd5b919050565b803563ffffffff8116811461443f57600080fd5b8015158114612cac57600080fd5b600060a0828403121561447857600080fd5b60405160a081016001600160401b038111828210171561449a5761449a6143bf565b6040529050806144a983614444565b81526144b760208401614428565b60208201526144c860408401614428565b604082015260608301356144db81614458565b6060820152608092830135920191909152919050565b600080600060e0848603121561450657600080fd5b83356001600160401b0381111561451c57600080fd5b8401601f8101861361452d57600080fd5b803561454061453b82614405565b6143d5565b8082825260208201915060208360051b85010192508883111561456257600080fd5b6020840193505b8284101561458b5761457a84614428565b825260209384019390910190614569565b9550505050602084013591506145a48560408601614466565b90509250925092565b600082601f8301126145be57600080fd5b81356145cc61453b82614405565b8082825260208201915060208360051b8601019250858311156145ee57600080fd5b602085015b8381101561461457803561460681614328565b8352602092830192016145f3565b5095945050505050565b60008060006060848603121561463357600080fd5b83356001600160401b0381111561464957600080fd5b614655868287016145ad565b93505060208401356001600160401b0381111561467157600080fd5b61467d868287016145ad565b92505060408401356001600160401b0381111561469957600080fd5b6146a5868287016145ad565b9150509250925092565b6000602082840312156146c157600080fd5b5035919050565b60008083601f8401126146da57600080fd5b5081356001600160401b038111156146f157600080fd5b6020830191508360208260051b850101111561470c57600080fd5b9250929050565b600060a0828403121561472557600080fd5b50919050565b600080600080600080600080610120898b03121561474857600080fd5b88356001600160401b0381111561475e57600080fd5b61476a8b828c016146c8565b90995097505060208901356001600160401b0381111561478957600080fd5b6147958b828c016146c8565b90975095505060408901356001600160401b038111156147b457600080fd5b6147c08b828c016146c8565b909550935050606089013591506147da8a60808b01614713565b90509295985092959890939650565b600080602083850312156147fc57600080fd5b82356001600160401b0381111561481257600080fd5b61481e858286016146c8565b90969095509350505050565b60008083601f84011261483c57600080fd5b5081356001600160401b0381111561485357600080fd5b60208301915083602082850101111561470c57600080fd5b600080600080600060e0868803121561488357600080fd5b85356001600160401b0381111561489957600080fd5b6148a58882890161482a565b90965094505060208601356001600160401b038111156148c457600080fd5b6148d0888289016146c8565b90945092506148e490508760408801614713565b90509295509295909350565b60008060006060848603121561490557600080fd5b505081359360208301359350604090920135919050565b634e487b7160e01b600052602160045260246000fd5b602081016005831061495457634e487b7160e01b600052602160045260246000fd5b91905290565b6000806040838503121561496d57600080fd5b50508035926020909101359150565b60008060006060848603121561499157600080fd5b833561499c81614328565b925060208401356149ac81614328565b929592945050506040919091013590565b600080600080604085870312156149d357600080fd5b84356001600160401b038111156149e957600080fd5b6149f58782880161482a565b90955093505060208501356001600160401b03811115614a1457600080fd5b614a20878288016146c8565b95989497509550505050565b602080825282518282018190526000918401906040840190835b81811015614a6d5783516001600160a01b0316835260209384019390920191600101614a46565b509095945050505050565b6020808252601a908201527f43616c6c6572206973206e6f742074686520476f7665726e6f72000000000000604082015260600190565b600060208284031215614ac157600080fd5b815161413181614328565b6020808252601c908201527f43616c6c6572206973206e6f7420746865205374726174656769737400000000604082015260600190565b600081518084526020840193506020830160005b82811015614b3e5781516001600160401b0316865260209586019590910190600101614b17565b5093949350505050565b63ffffffff81511682526001600160401b0360208201511660208301526001600160401b036040820151166040830152606081015115156060830152608081015160808301525050565b6001600160a01b038516815261010060208201819052600090614bb790830186614b03565b9050836040830152614bcc6060830184614b48565b95945050505050565b600060208284031215614be757600080fd5b815161413181614458565b60208082526017908201527f43616c6c6572206973206e6f7420746865205661756c74000000000000000000604082015260600190565b6020808252600e908201526d1499595b9d1c985b9d0818d85b1b60921b604082015260600190565b602080825260119082015270155b9cdd5c1c1bdc9d195908185cdcd95d607a1b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b8082018082111561177857611778614c7c565b6020808252601d908201527f43616c6c6572206973206e6f7420746865205265676973747261746f72000000604082015260600190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b6000808335601e19843603018112614d3357600080fd5b8301803591506001600160401b03821115614d4d57600080fd5b60200191503681900382131561470c57600080fd5b8183823760009101908152919050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b81835260208301925060008160005b84811015614b3e576001600160401b03614dc383614428565b1686526020958601959190910190600101614daa565b604081526000614ded604083018688614d72565b8281036020840152614217818587614d9b565b60008383855260208501945060208460051b8201018360005b86811015614e8d57838303601f19018852813536879003601e19018112614e3f57600080fd5b86016020810190356001600160401b03811115614e5b57600080fd5b803603821315614e6a57600080fd5b614e75858284614d72565b60209a8b019a90955093909301925050600101614e19565b50909695505050505050565b63ffffffff614ea782614444565b1682526001600160401b03614ebe60208301614428565b1660208301526001600160401b03614ed860408301614428565b1660408301526060810135614eec81614458565b15156060830152608090810135910152565b61012081526000614f1461012083018a8c614e00565b8281036020840152614f2781898b614d9b565b90508281036040840152614f3c818789614e00565b915050836060830152614f526080830184614e99565b9998505050505050505050565b600060208284031215614f7157600080fd5b5051919050565b808202811582820484141761177857611778614c7c565b60008235605e19833603018112614fa557600080fd5b9190910192915050565b60005b83811015614fca578181015183820152602001614fb2565b50506000910152565b60008151808452614feb816020860160208601614faf565b601f01601f19169290920160200192915050565b60808152600061501360808301888a614d72565b82810360208401526150258188614fd3565b9050828103604084015261503a818688614d72565b915050826060830152979650505050505050565b604081526000615062604083018587614d72565b9050826020830152949350505050565b60e08152600061508660e083018789614d72565b8281036020840152615099818688614d9b565b9150506150a96040830184614e99565b9695505050505050565b80820182811260008312801582168215821617156150d3576150d3614c7c565b505092915050565b8181038181111561177857611778614c7c565b634e487b7160e01b600052603160045260246000fd5b6040808252845490820181905260008581526020812090916060840190835b8181101561514a5783546001600160a01b0316835260019384019360209093019201615123565b50508381036020808601919091528582520190508460005b85811015614e8d57813561517581614328565b6001600160a01b031683526020928301929190910190600101615162565b60e0815260006151a660e0830186614b03565b9050836020830152613f5e6040830184614b48565b6000826151d857634e487b7160e01b600052601260045260246000fd5b500490565b60008251614fa5818460208701614faf565b6020815260006141316020830184614fd356fe53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac45357bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4aa26469706673582212204b6c708a2f81896e0dd1dad0372daf327a5b4d250fc7af8eab54d0c33efe777264736f6c634300081c0033

Verified Source Code Full Match

Compiler: v0.8.28+commit.7893614a EVM: paris Optimization: Yes (200 runs)
Pausable.sol 91 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

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

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

    bool private _paused;

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

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

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

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

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

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}
SafeERC20.sol 99 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.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;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    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));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    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");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @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");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
Address.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)

pragma solidity ^0.8.0;

/**
 * @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
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
Math.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a / b + (a % b == 0 ? 0 : 1);
    }
}
SafeCast.sol 241 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}
Governable.sol 169 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Base for contracts that are managed by the Origin Protocol's Governor.
 * @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
 *      from owner to governor and renounce methods removed. Does not use
 *      Context.sol like Ownable.sol does for simplification.
 * @author Origin Protocol Inc
 */
abstract contract Governable {
    // Storage position of the owner and pendingOwner of the contract
    // keccak256("OUSD.governor");
    bytes32 private constant governorPosition =
        0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;

    // keccak256("OUSD.pending.governor");
    bytes32 private constant pendingGovernorPosition =
        0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;

    // keccak256("OUSD.reentry.status");
    bytes32 private constant reentryStatusPosition =
        0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;

    // See OpenZeppelin ReentrancyGuard implementation
    uint256 constant _NOT_ENTERED = 1;
    uint256 constant _ENTERED = 2;

    event PendingGovernorshipTransfer(
        address indexed previousGovernor,
        address indexed newGovernor
    );

    event GovernorshipTransferred(
        address indexed previousGovernor,
        address indexed newGovernor
    );

    /**
     * @notice Returns the address of the current Governor.
     */
    function governor() public view returns (address) {
        return _governor();
    }

    /**
     * @dev Returns the address of the current Governor.
     */
    function _governor() internal view returns (address governorOut) {
        bytes32 position = governorPosition;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            governorOut := sload(position)
        }
    }

    /**
     * @dev Returns the address of the pending Governor.
     */
    function _pendingGovernor()
        internal
        view
        returns (address pendingGovernor)
    {
        bytes32 position = pendingGovernorPosition;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            pendingGovernor := sload(position)
        }
    }

    /**
     * @dev Throws if called by any account other than the Governor.
     */
    modifier onlyGovernor() {
        require(isGovernor(), "Caller is not the Governor");
        _;
    }

    /**
     * @notice Returns true if the caller is the current Governor.
     */
    function isGovernor() public view returns (bool) {
        return msg.sender == _governor();
    }

    function _setGovernor(address newGovernor) internal {
        emit GovernorshipTransferred(_governor(), newGovernor);

        bytes32 position = governorPosition;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(position, newGovernor)
        }
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        bytes32 position = reentryStatusPosition;
        uint256 _reentry_status;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            _reentry_status := sload(position)
        }

        // On the first call to nonReentrant, _notEntered will be true
        require(_reentry_status != _ENTERED, "Reentrant call");

        // Any calls to nonReentrant after this point will fail
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(position, _ENTERED)
        }

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(position, _NOT_ENTERED)
        }
    }

    function _setPendingGovernor(address newGovernor) internal {
        bytes32 position = pendingGovernorPosition;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(position, newGovernor)
        }
    }

    /**
     * @notice Transfers Governance of the contract to a new account (`newGovernor`).
     * Can only be called by the current Governor. Must be claimed for this to complete
     * @param _newGovernor Address of the new Governor
     */
    function transferGovernance(address _newGovernor) external onlyGovernor {
        _setPendingGovernor(_newGovernor);
        emit PendingGovernorshipTransfer(_governor(), _newGovernor);
    }

    /**
     * @notice Claim Governance of the contract to a new account (`newGovernor`).
     * Can only be called by the new Governor.
     */
    function claimGovernance() external {
        require(
            msg.sender == _pendingGovernor(),
            "Only the pending Governor can complete the claim"
        );
        _changeGovernor(msg.sender);
    }

    /**
     * @dev Change Governance of the contract to a new account (`newGovernor`).
     * @param _newGovernor Address of the new Governor
     */
    function _changeGovernor(address _newGovernor) internal {
        require(_newGovernor != address(0), "New Governor is address(0)");
        _setGovernor(_newGovernor);
    }
}
IBasicToken.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IBasicToken {
    function symbol() external view returns (string memory);

    function decimals() external view returns (uint8);
}
IDepositContract.sol 34 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IDepositContract {
    /// @notice A processed deposit event.
    event DepositEvent(
        bytes pubkey,
        bytes withdrawal_credentials,
        bytes amount,
        bytes signature,
        bytes index
    );

    /// @notice Submit a Phase 0 DepositData object.
    /// @param pubkey A BLS12-381 public key.
    /// @param withdrawal_credentials Commitment to a public key for withdrawals.
    /// @param signature A BLS12-381 signature.
    /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
    /// Used as a protection against malformed input.
    function deposit(
        bytes calldata pubkey,
        bytes calldata withdrawal_credentials,
        bytes calldata signature,
        bytes32 deposit_data_root
    ) external payable;

    /// @notice Query the current deposit root hash.
    /// @return The deposit root hash.
    function get_deposit_root() external view returns (bytes32);

    /// @notice Query the current deposit count.
    /// @return The deposit count encoded as a little endian 64-bit number.
    function get_deposit_count() external view returns (bytes memory);
}
ISSVNetwork.sol 289 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

struct Cluster {
    uint32 validatorCount;
    uint64 networkFeeIndex;
    uint64 index;
    bool active;
    uint256 balance;
}

interface ISSVNetwork {
    /**********/
    /* Errors */
    /**********/

    error CallerNotOwner(); // 0x5cd83192
    error CallerNotWhitelisted(); // 0x8c6e5d71
    error FeeTooLow(); // 0x732f9413
    error FeeExceedsIncreaseLimit(); // 0x958065d9
    error NoFeeDeclared(); // 0x1d226c30
    error ApprovalNotWithinTimeframe(); // 0x97e4b518
    error OperatorDoesNotExist(); // 0x961e3e8c
    error InsufficientBalance(); // 0xf4d678b8
    error ValidatorDoesNotExist(); // 0xe51315d2
    error ClusterNotLiquidatable(); // 0x60300a8d
    error InvalidPublicKeyLength(); // 0x637297a4
    error InvalidOperatorIdsLength(); // 0x38186224
    error ClusterAlreadyEnabled(); // 0x3babafd2
    error ClusterIsLiquidated(); // 0x95a0cf33
    error ClusterDoesNotExists(); // 0x185e2b16
    error IncorrectClusterState(); // 0x12e04c87
    error UnsortedOperatorsList(); // 0xdd020e25
    error NewBlockPeriodIsBelowMinimum(); // 0x6e6c9cac
    error ExceedValidatorLimit(); // 0x6df5ab76
    error TokenTransferFailed(); // 0x045c4b02
    error SameFeeChangeNotAllowed(); // 0xc81272f8
    error FeeIncreaseNotAllowed(); // 0x410a2b6c
    error NotAuthorized(); // 0xea8e4eb5
    error OperatorsListNotUnique(); // 0xa5a1ff5d
    error OperatorAlreadyExists(); // 0x289c9494
    error TargetModuleDoesNotExist(); // 0x8f9195fb
    error MaxValueExceeded(); // 0x91aa3017
    error FeeTooHigh(); // 0xcd4e6167
    error PublicKeysSharesLengthMismatch(); // 0x9ad467b8
    error IncorrectValidatorStateWithData(bytes publicKey); // 0x89307938
    error ValidatorAlreadyExistsWithData(bytes publicKey); // 0x388e7999
    error EmptyPublicKeysList(); // df83e679

    // legacy errors
    error ValidatorAlreadyExists(); // 0x8d09a73e
    error IncorrectValidatorState(); // 0x2feda3c1

    event AdminChanged(address previousAdmin, address newAdmin);
    event BeaconUpgraded(address indexed beacon);
    event ClusterDeposited(
        address indexed owner,
        uint64[] operatorIds,
        uint256 value,
        Cluster cluster
    );
    event ClusterLiquidated(
        address indexed owner,
        uint64[] operatorIds,
        Cluster cluster
    );
    event ClusterReactivated(
        address indexed owner,
        uint64[] operatorIds,
        Cluster cluster
    );
    event ClusterWithdrawn(
        address indexed owner,
        uint64[] operatorIds,
        uint256 value,
        Cluster cluster
    );
    event DeclareOperatorFeePeriodUpdated(uint64 value);
    event ExecuteOperatorFeePeriodUpdated(uint64 value);
    event FeeRecipientAddressUpdated(
        address indexed owner,
        address recipientAddress
    );
    event Initialized(uint8 version);
    event LiquidationThresholdPeriodUpdated(uint64 value);
    event MinimumLiquidationCollateralUpdated(uint256 value);
    event NetworkEarningsWithdrawn(uint256 value, address recipient);
    event NetworkFeeUpdated(uint256 oldFee, uint256 newFee);
    event OperatorAdded(
        uint64 indexed operatorId,
        address indexed owner,
        bytes publicKey,
        uint256 fee
    );
    event OperatorFeeDeclarationCancelled(
        address indexed owner,
        uint64 indexed operatorId
    );
    event OperatorFeeDeclared(
        address indexed owner,
        uint64 indexed operatorId,
        uint256 blockNumber,
        uint256 fee
    );
    event OperatorFeeExecuted(
        address indexed owner,
        uint64 indexed operatorId,
        uint256 blockNumber,
        uint256 fee
    );
    event OperatorFeeIncreaseLimitUpdated(uint64 value);
    event OperatorMaximumFeeUpdated(uint64 maxFee);
    event OperatorRemoved(uint64 indexed operatorId);
    event OperatorWhitelistUpdated(
        uint64 indexed operatorId,
        address whitelisted
    );
    event OperatorWithdrawn(
        address indexed owner,
        uint64 indexed operatorId,
        uint256 value
    );
    event OwnershipTransferStarted(
        address indexed previousOwner,
        address indexed newOwner
    );
    event OwnershipTransferred(
        address indexed previousOwner,
        address indexed newOwner
    );
    event Upgraded(address indexed implementation);
    event ValidatorAdded(
        address indexed owner,
        uint64[] operatorIds,
        bytes publicKey,
        bytes shares,
        Cluster cluster
    );
    event ValidatorExited(
        address indexed owner,
        uint64[] operatorIds,
        bytes publicKey
    );
    event ValidatorRemoved(
        address indexed owner,
        uint64[] operatorIds,
        bytes publicKey,
        Cluster cluster
    );

    fallback() external;

    function acceptOwnership() external;

    function cancelDeclaredOperatorFee(uint64 operatorId) external;

    function declareOperatorFee(uint64 operatorId, uint256 fee) external;

    function deposit(
        address clusterOwner,
        uint64[] memory operatorIds,
        uint256 amount,
        Cluster memory cluster
    ) external;

    function executeOperatorFee(uint64 operatorId) external;

    function exitValidator(bytes memory publicKey, uint64[] memory operatorIds)
        external;

    function bulkExitValidator(
        bytes[] calldata publicKeys,
        uint64[] calldata operatorIds
    ) external;

    function getVersion() external pure returns (string memory version);

    function initialize(
        address token_,
        address ssvOperators_,
        address ssvClusters_,
        address ssvDAO_,
        address ssvViews_,
        uint64 minimumBlocksBeforeLiquidation_,
        uint256 minimumLiquidationCollateral_,
        uint32 validatorsPerOperatorLimit_,
        uint64 declareOperatorFeePeriod_,
        uint64 executeOperatorFeePeriod_,
        uint64 operatorMaxFeeIncrease_
    ) external;

    function liquidate(
        address clusterOwner,
        uint64[] memory operatorIds,
        Cluster memory cluster
    ) external;

    function owner() external view returns (address);

    function pendingOwner() external view returns (address);

    function proxiableUUID() external view returns (bytes32);

    function reactivate(
        uint64[] memory operatorIds,
        uint256 amount,
        Cluster memory cluster
    ) external;

    function reduceOperatorFee(uint64 operatorId, uint256 fee) external;

    function registerOperator(bytes memory publicKey, uint256 fee)
        external
        returns (uint64 id);

    function registerValidator(
        bytes memory publicKey,
        uint64[] memory operatorIds,
        bytes memory sharesData,
        uint256 amount,
        Cluster memory cluster
    ) external;

    function bulkRegisterValidator(
        bytes[] calldata publicKeys,
        uint64[] calldata operatorIds,
        bytes[] calldata sharesData,
        uint256 amount,
        Cluster memory cluster
    ) external;

    function removeOperator(uint64 operatorId) external;

    function removeValidator(
        bytes memory publicKey,
        uint64[] memory operatorIds,
        Cluster memory cluster
    ) external;

    function bulkRemoveValidator(
        bytes[] calldata publicKeys,
        uint64[] calldata operatorIds,
        Cluster memory cluster
    ) external;

    function renounceOwnership() external;

    function setFeeRecipientAddress(address recipientAddress) external;

    function setOperatorWhitelist(uint64 operatorId, address whitelisted)
        external;

    function transferOwnership(address newOwner) external;

    function updateDeclareOperatorFeePeriod(uint64 timeInSeconds) external;

    function updateExecuteOperatorFeePeriod(uint64 timeInSeconds) external;

    function updateLiquidationThresholdPeriod(uint64 blocks) external;

    function updateMaximumOperatorFee(uint64 maxFee) external;

    function updateMinimumLiquidationCollateral(uint256 amount) external;

    function updateModule(uint8 moduleId, address moduleAddress) external;

    function updateNetworkFee(uint256 fee) external;

    function updateOperatorFeeIncreaseLimit(uint64 percentage) external;

    function upgradeTo(address newImplementation) external;

    function upgradeToAndCall(address newImplementation, bytes memory data)
        external
        payable;

    function withdraw(
        uint64[] memory operatorIds,
        uint256 amount,
        Cluster memory cluster
    ) external;

    function withdrawAllOperatorEarnings(uint64 operatorId) external;

    function withdrawNetworkEarnings(uint256 amount) external;

    function withdrawOperatorEarnings(uint64 operatorId, uint256 amount)
        external;
}
IStrategy.sol 59 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Platform interface to integrate with lending platform like Compound, AAVE etc.
 */
interface IStrategy {
    /**
     * @dev Deposit the given asset to platform
     * @param _asset asset address
     * @param _amount Amount to deposit
     */
    function deposit(address _asset, uint256 _amount) external;

    /**
     * @dev Deposit the entire balance of all supported assets in the Strategy
     *      to the platform
     */
    function depositAll() external;

    /**
     * @dev Withdraw given asset from Lending platform
     */
    function withdraw(
        address _recipient,
        address _asset,
        uint256 _amount
    ) external;

    /**
     * @dev Liquidate all assets in strategy and return them to Vault.
     */
    function withdrawAll() external;

    /**
     * @dev Returns the current balance of the given asset.
     */
    function checkBalance(address _asset)
        external
        view
        returns (uint256 balance);

    /**
     * @dev Returns bool indicating whether strategy supports asset.
     */
    function supportsAsset(address _asset) external view returns (bool);

    /**
     * @dev Collect reward tokens from the Strategy.
     */
    function collectRewardTokens() external;

    /**
     * @dev The address array of the reward tokens for the Strategy.
     */
    function getRewardTokenAddresses() external view returns (address[] memory);

    function harvesterAddress() external view returns (address);
}
IVault.sol 289 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { VaultStorage } from "../vault/VaultStorage.sol";

interface IVault {
    // slither-disable-start constable-states

    event AssetSupported(address _asset);
    event AssetDefaultStrategyUpdated(address _asset, address _strategy);
    event AssetAllocated(address _asset, address _strategy, uint256 _amount);
    event StrategyApproved(address _addr);
    event StrategyRemoved(address _addr);
    event Mint(address _addr, uint256 _value);
    event Redeem(address _addr, uint256 _value);
    event CapitalPaused();
    event CapitalUnpaused();
    event RebasePaused();
    event RebaseUnpaused();
    event VaultBufferUpdated(uint256 _vaultBuffer);
    event RedeemFeeUpdated(uint256 _redeemFeeBps);
    event PriceProviderUpdated(address _priceProvider);
    event AllocateThresholdUpdated(uint256 _threshold);
    event RebaseThresholdUpdated(uint256 _threshold);
    event StrategistUpdated(address _address);
    event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
    event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
    event TrusteeFeeBpsChanged(uint256 _basis);
    event TrusteeAddressChanged(address _address);
    event SwapperChanged(address _address);
    event SwapAllowedUndervalueChanged(uint256 _basis);
    event SwapSlippageChanged(address _asset, uint256 _basis);
    event Swapped(
        address indexed _fromAsset,
        address indexed _toAsset,
        uint256 _fromAssetAmount,
        uint256 _toAssetAmount
    );
    event StrategyAddedToMintWhitelist(address indexed strategy);
    event StrategyRemovedFromMintWhitelist(address indexed strategy);
    event DripperChanged(address indexed _dripper);
    event WithdrawalRequested(
        address indexed _withdrawer,
        uint256 indexed _requestId,
        uint256 _amount,
        uint256 _queued
    );
    event WithdrawalClaimed(
        address indexed _withdrawer,
        uint256 indexed _requestId,
        uint256 _amount
    );
    event WithdrawalClaimable(uint256 _claimable, uint256 _newClaimable);

    // Governable.sol
    function transferGovernance(address _newGovernor) external;

    function claimGovernance() external;

    function governor() external view returns (address);

    function ADMIN_IMPLEMENTATION() external view returns (address);

    // VaultAdmin.sol
    function setPriceProvider(address _priceProvider) external;

    function priceProvider() external view returns (address);

    function setRedeemFeeBps(uint256 _redeemFeeBps) external;

    function redeemFeeBps() external view returns (uint256);

    function setVaultBuffer(uint256 _vaultBuffer) external;

    function vaultBuffer() external view returns (uint256);

    function setAutoAllocateThreshold(uint256 _threshold) external;

    function autoAllocateThreshold() external view returns (uint256);

    function setRebaseThreshold(uint256 _threshold) external;

    function rebaseThreshold() external view returns (uint256);

    function setStrategistAddr(address _address) external;

    function strategistAddr() external view returns (address);

    function setMaxSupplyDiff(uint256 _maxSupplyDiff) external;

    function maxSupplyDiff() external view returns (uint256);

    function setTrusteeAddress(address _address) external;

    function trusteeAddress() external view returns (address);

    function setTrusteeFeeBps(uint256 _basis) external;

    function trusteeFeeBps() external view returns (uint256);

    function ousdMetaStrategy() external view returns (address);

    function setSwapper(address _swapperAddr) external;

    function setSwapAllowedUndervalue(uint16 _percentageBps) external;

    function setOracleSlippage(address _asset, uint16 _allowedOracleSlippageBps)
        external;

    function supportAsset(address _asset, uint8 _unitConversion) external;

    function approveStrategy(address _addr) external;

    function removeStrategy(address _addr) external;

    function setAssetDefaultStrategy(address _asset, address _strategy)
        external;

    function assetDefaultStrategies(address _asset)
        external
        view
        returns (address);

    function pauseRebase() external;

    function unpauseRebase() external;

    function rebasePaused() external view returns (bool);

    function pauseCapital() external;

    function unpauseCapital() external;

    function capitalPaused() external view returns (bool);

    function transferToken(address _asset, uint256 _amount) external;

    function priceUnitMint(address asset) external view returns (uint256);

    function priceUnitRedeem(address asset) external view returns (uint256);

    function withdrawAllFromStrategy(address _strategyAddr) external;

    function withdrawAllFromStrategies() external;

    function withdrawFromStrategy(
        address _strategyFromAddress,
        address[] calldata _assets,
        uint256[] calldata _amounts
    ) external;

    function depositToStrategy(
        address _strategyToAddress,
        address[] calldata _assets,
        uint256[] calldata _amounts
    ) external;

    // VaultCore.sol
    function mint(
        address _asset,
        uint256 _amount,
        uint256 _minimumOusdAmount
    ) external;

    function mintForStrategy(uint256 _amount) external;

    function redeem(uint256 _amount, uint256 _minimumUnitAmount) external;

    function burnForStrategy(uint256 _amount) external;

    function allocate() external;

    function rebase() external;

    function swapCollateral(
        address fromAsset,
        address toAsset,
        uint256 fromAssetAmount,
        uint256 minToAssetAmount,
        bytes calldata data
    ) external returns (uint256 toAssetAmount);

    function totalValue() external view returns (uint256 value);

    function checkBalance(address _asset) external view returns (uint256);

    function calculateRedeemOutputs(uint256 _amount)
        external
        view
        returns (uint256[] memory);

    function getAssetCount() external view returns (uint256);

    function getAssetConfig(address _asset)
        external
        view
        returns (VaultStorage.Asset memory config);

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

    function getStrategyCount() external view returns (uint256);

    function swapper() external view returns (address);

    function allowedSwapUndervalue() external view returns (uint256);

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

    function isSupportedAsset(address _asset) external view returns (bool);

    function netOusdMintForStrategyThreshold() external view returns (uint256);

    function setOusdMetaStrategy(address _ousdMetaStrategy) external;

    function setNetOusdMintForStrategyThreshold(uint256 _threshold) external;

    function netOusdMintedForStrategy() external view returns (int256);

    function setDripper(address _dripper) external;

    function dripper() external view returns (address);

    function weth() external view returns (address);

    function cacheWETHAssetIndex() external;

    function wethAssetIndex() external view returns (uint256);

    function initialize(address, address) external;

    function setAdminImpl(address) external;

    function removeAsset(address _asset) external;

    // These are OETH specific functions
    function addWithdrawalQueueLiquidity() external;

    function requestWithdrawal(uint256 _amount)
        external
        returns (uint256 requestId, uint256 queued);

    function claimWithdrawal(uint256 requestId)
        external
        returns (uint256 amount);

    function claimWithdrawals(uint256[] memory requestIds)
        external
        returns (uint256[] memory amounts, uint256 totalAmount);

    function withdrawalQueueMetadata()
        external
        view
        returns (VaultStorage.WithdrawalQueueMetadata memory);

    function withdrawalRequests(uint256 requestId)
        external
        view
        returns (VaultStorage.WithdrawalRequest memory);

    // OETHb specific functions
    function addStrategyToMintWhitelist(address strategyAddr) external;

    function removeStrategyFromMintWhitelist(address strategyAddr) external;

    function isMintWhitelistedStrategy(address strategyAddr)
        external
        view
        returns (bool);

    function withdrawalClaimDelay() external view returns (uint256);

    function setWithdrawalClaimDelay(uint256 newDelay) external;

    function lastRebase() external view returns (uint64);

    function dripDuration() external view returns (uint64);

    function setDripDuration(uint256 _dripDuration) external;

    function rebasePerSecondMax() external view returns (uint64);

    function setRebaseRateMax(uint256 yearlyApr) external;

    function rebasePerSecondTarget() external view returns (uint64);

    function previewYield() external view returns (uint256 yield);

    // slither-disable-end constable-states
}
IWETH9.sol 35 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IWETH9 {
    event Approval(address indexed src, address indexed guy, uint256 wad);
    event Deposit(address indexed dst, uint256 wad);
    event Transfer(address indexed src, address indexed dst, uint256 wad);
    event Withdrawal(address indexed src, uint256 wad);

    function allowance(address, address) external view returns (uint256);

    function approve(address guy, uint256 wad) external returns (bool);

    function balanceOf(address) external view returns (uint256);

    function decimals() external view returns (uint8);

    function deposit() external payable;

    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function totalSupply() external view returns (uint256);

    function transfer(address dst, uint256 wad) external returns (bool);

    function transferFrom(
        address src,
        address dst,
        uint256 wad
    ) external returns (bool);

    function withdraw(uint256 wad) external;
}
FeeAccumulator.sol 46 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";

/**
 * @title Fee Accumulator for Native Staking SSV Strategy
 * @notice Receives execution rewards which includes tx fees and
 * MEV rewards like tx priority and tx ordering.
 * It does NOT include swept ETH from beacon chain consensus rewards or full validator withdrawals.
 * @author Origin Protocol Inc
 */
contract FeeAccumulator {
    /// @notice The address of the Native Staking Strategy
    address public immutable STRATEGY;

    event ExecutionRewardsCollected(address indexed strategy, uint256 amount);

    /**
     * @param _strategy Address of the Native Staking Strategy
     */
    constructor(address _strategy) {
        STRATEGY = _strategy;
    }

    /**
     * @notice sends all ETH in this FeeAccumulator contract to the Native Staking Strategy.
     * @return eth The amount of execution rewards that were sent to the Native Staking Strategy
     */
    function collect() external returns (uint256 eth) {
        require(msg.sender == STRATEGY, "Caller is not the Strategy");

        eth = address(this).balance;
        if (eth > 0) {
            // Send the ETH to the Native Staking Strategy
            Address.sendValue(payable(STRATEGY), eth);

            emit ExecutionRewardsCollected(STRATEGY, eth);
        }
    }

    /**
     * @dev Accept ETH
     */
    receive() external payable {}
}
NativeStakingSSVStrategy.sol 343 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

import { InitializableAbstractStrategy } from "../../utils/InitializableAbstractStrategy.sol";
import { IWETH9 } from "../../interfaces/IWETH9.sol";
import { FeeAccumulator } from "./FeeAccumulator.sol";
import { ValidatorAccountant } from "./ValidatorAccountant.sol";
import { ISSVNetwork } from "../../interfaces/ISSVNetwork.sol";

struct ValidatorStakeData {
    bytes pubkey;
    bytes signature;
    bytes32 depositDataRoot;
}

/// @title Native Staking SSV Strategy
/// @notice Strategy to deploy funds into DVT validators powered by the SSV Network
/// @author Origin Protocol Inc
/// @dev This contract handles WETH and ETH and in some operations interchanges between the two. Any WETH that
/// is on the contract across multiple blocks (and not just transitory within a transaction) is considered an
/// asset. Meaning deposits increase the balance of the asset and withdrawal decrease it. As opposed to all
/// our other strategies the WETH doesn't immediately get deposited into an underlying strategy and can be present
/// across multiple blocks waiting to be unwrapped to ETH and staked to validators. This separation of WETH and ETH is
/// required since the rewards (reward token) is also in ETH.
///
/// To simplify the accounting of WETH there is another difference in behavior compared to the other strategies.
/// To withdraw WETH asset - exit message is posted to validators and the ETH hits this contract with multiple days
/// delay. In order to simplify the WETH accounting upon detection of such an event the ValidatorAccountant
/// immediately wraps ETH to WETH and sends it to the Vault.
///
/// On the other hand any ETH on the contract (across multiple blocks) is there either:
///  - as a result of already accounted for consensus rewards
///  - as a result of not yet accounted for consensus rewards
///  - as a results of not yet accounted for full validator withdrawals (or validator slashes)
///
/// Even though the strategy assets and rewards are a very similar asset the consensus layer rewards and the
/// execution layer rewards are considered rewards and those are dripped to the Vault over a configurable time
/// interval and not immediately.
contract NativeStakingSSVStrategy is
    ValidatorAccountant,
    InitializableAbstractStrategy
{
    using SafeERC20 for IERC20;

    /// @notice SSV ERC20 token that serves as a payment for operating SSV validators
    address public immutable SSV_TOKEN;
    /// @notice Fee collector address
    /// @dev this address will receive maximal extractable value (MEV) rewards. These are
    /// rewards for arranging transactions in a way that benefits the validator.
    address payable public immutable FEE_ACCUMULATOR_ADDRESS;

    /// @dev This contract receives WETH as the deposit asset, but unlike other strategies doesn't immediately
    /// deposit it to an underlying platform. Rather a special privilege account stakes it to the validators.
    /// For that reason calling WETH.balanceOf(this) in a deposit function can contain WETH that has just been
    /// deposited and also WETH that has previously been deposited. To keep a correct count we need to keep track
    /// of WETH that has already been accounted for.
    /// This value represents the amount of WETH balance of this contract that has already been accounted for by the
    /// deposit events.
    /// It is important to note that this variable is not concerned with WETH that is a result of full/partial
    /// withdrawal of the validators. It is strictly concerned with WETH that has been deposited and is waiting to
    /// be staked.
    uint256 public depositedWethAccountedFor;

    // For future use
    uint256[49] private __gap;

    /// @param _baseConfig Base strategy config with platformAddress (ERC-4626 Vault contract), eg sfrxETH or sDAI,
    /// and vaultAddress (OToken Vault contract), eg VaultProxy or OETHVaultProxy
    /// @param _wethAddress Address of the Erc20 WETH Token contract
    /// @param _ssvToken Address of the Erc20 SSV Token contract
    /// @param _ssvNetwork Address of the SSV Network contract
    /// @param _maxValidators Maximum number of validators that can be registered in the strategy
    /// @param _feeAccumulator Address of the fee accumulator receiving execution layer validator rewards
    /// @param _beaconChainDepositContract Address of the beacon chain deposit contract
    constructor(
        BaseStrategyConfig memory _baseConfig,
        address _wethAddress,
        address _ssvToken,
        address _ssvNetwork,
        uint256 _maxValidators,
        address _feeAccumulator,
        address _beaconChainDepositContract
    )
        InitializableAbstractStrategy(_baseConfig)
        ValidatorAccountant(
            _wethAddress,
            _baseConfig.vaultAddress,
            _beaconChainDepositContract,
            _ssvNetwork,
            _maxValidators
        )
    {
        SSV_TOKEN = _ssvToken;
        FEE_ACCUMULATOR_ADDRESS = payable(_feeAccumulator);
    }

    /// @notice Set up initial internal state including
    /// 1. approving the SSVNetwork to transfer SSV tokens from this strategy contract
    /// 2. setting the recipient of SSV validator MEV rewards to the FeeAccumulator contract.
    /// @param _rewardTokenAddresses Address of reward token for platform
    /// @param _assets Addresses of initial supported assets
    /// @param _pTokens Platform Token corresponding addresses
    function initialize(
        address[] memory _rewardTokenAddresses,
        address[] memory _assets,
        address[] memory _pTokens
    ) external onlyGovernor initializer {
        InitializableAbstractStrategy._initialize(
            _rewardTokenAddresses,
            _assets,
            _pTokens
        );

        // Approves the SSV Network contract to transfer SSV tokens for deposits
        IERC20(SSV_TOKEN).approve(SSV_NETWORK, type(uint256).max);

        // Set the FeeAccumulator as the address for SSV validators to send MEV rewards to
        ISSVNetwork(SSV_NETWORK).setFeeRecipientAddress(
            FEE_ACCUMULATOR_ADDRESS
        );
    }

    /// @notice Unlike other strategies, this does not deposit assets into the underlying platform.
    /// It just checks the asset is WETH and emits the Deposit event.
    /// To deposit WETH into validators `registerSsvValidator` and `stakeEth` must be used.
    /// Will NOT revert if the strategy is paused from an accounting failure.
    /// @param _asset Address of asset to deposit. Has to be WETH.
    /// @param _amount Amount of assets that were transferred to the strategy by the vault.
    function deposit(address _asset, uint256 _amount)
        external
        override
        onlyVault
        nonReentrant
    {
        require(_asset == WETH, "Unsupported asset");
        depositedWethAccountedFor += _amount;
        _deposit(_asset, _amount);
    }

    /// @dev Deposit WETH to this strategy so it can later be staked into a validator.
    /// @param _asset Address of WETH
    /// @param _amount Amount of WETH to deposit
    function _deposit(address _asset, uint256 _amount) internal {
        require(_amount > 0, "Must deposit something");
        /*
         * We could do a check here that would revert when "_amount % 32 ether != 0". With the idea of
         * not allowing deposits that will result in WETH sitting on the strategy after all the possible batches
         * of 32ETH have been staked.
         * But someone could mess with our strategy by sending some WETH to it. And we might want to deposit just
         * enough WETH to add it up to 32 so it can be staked. For that reason the check is left out.
         *
         * WETH sitting on the strategy won't interfere with the accounting since accounting only operates on ETH.
         */
        emit Deposit(_asset, address(0), _amount);
    }

    /// @notice Unlike other strategies, this does not deposit assets into the underlying platform.
    /// It just emits the Deposit event.
    /// To deposit WETH into validators `registerSsvValidator` and `stakeEth` must be used.
    /// Will NOT revert if the strategy is paused from an accounting failure.
    function depositAll() external override onlyVault nonReentrant {
        uint256 wethBalance = IERC20(WETH).balanceOf(address(this));
        uint256 newWeth = wethBalance - depositedWethAccountedFor;

        if (newWeth > 0) {
            depositedWethAccountedFor = wethBalance;

            _deposit(WETH, newWeth);
        }
    }

    /// @notice Withdraw WETH from this contract. Used only if some WETH for is lingering on the contract.
    /// That can happen when:
    ///   - after mints if the strategy is the default
    ///   - time between depositToStrategy and stakeEth
    ///   - the deposit was not a multiple of 32 WETH
    ///   - someone sent WETH directly to this contract
    /// Will NOT revert if the strategy is paused from an accounting failure.
    /// @param _recipient Address to receive withdrawn assets
    /// @param _asset WETH to withdraw
    /// @param _amount Amount of WETH to withdraw
    function withdraw(
        address _recipient,
        address _asset,
        uint256 _amount
    ) external override onlyVault nonReentrant {
        require(_asset == WETH, "Unsupported asset");
        _withdraw(_recipient, _asset, _amount);
    }

    function _withdraw(
        address _recipient,
        address _asset,
        uint256 _amount
    ) internal {
        require(_amount > 0, "Must withdraw something");
        require(_recipient != address(0), "Must specify recipient");

        _wethWithdrawn(_amount);

        IERC20(_asset).safeTransfer(_recipient, _amount);
        emit Withdrawal(_asset, address(0), _amount);
    }

    /// @notice transfer all WETH deposits back to the vault.
    /// This does not withdraw from the validators. That has to be done separately with the
    /// `exitSsvValidator` and `removeSsvValidator` operations.
    /// This does not withdraw any execution rewards from the FeeAccumulator or
    /// consensus rewards in this strategy.
    /// Any ETH in this strategy that was swept from a full validator withdrawal will not be withdrawn.
    /// ETH from full validator withdrawals is sent to the Vault using `doAccounting`.
    /// Will NOT revert if the strategy is paused from an accounting failure.
    function withdrawAll() external override onlyVaultOrGovernor nonReentrant {
        uint256 wethBalance = IERC20(WETH).balanceOf(address(this));
        if (wethBalance > 0) {
            _withdraw(vaultAddress, WETH, wethBalance);
        }
    }

    /// @notice Returns the total value of (W)ETH that is staked to the validators
    /// and WETH deposits that are still to be staked.
    /// This does not include ETH from consensus rewards sitting in this strategy
    /// or ETH from MEV rewards in the FeeAccumulator. These rewards are harvested
    /// and sent to the Dripper so will eventually be sent to the Vault as WETH.
    /// @param _asset      Address of weth asset
    /// @return balance    Total value of (W)ETH
    function checkBalance(address _asset)
        external
        view
        override
        returns (uint256 balance)
    {
        require(_asset == WETH, "Unsupported asset");

        balance =
            // add the ETH that has been staked in validators
            activeDepositedValidators *
            FULL_STAKE +
            // add the WETH in the strategy from deposits that are still to be staked
            IERC20(WETH).balanceOf(address(this));
    }

    function pause() external onlyStrategist {
        _pause();
    }

    /// @notice Returns bool indicating whether asset is supported by strategy.
    /// @param _asset The address of the asset token.
    function supportsAsset(address _asset) public view override returns (bool) {
        return _asset == WETH;
    }

    /// @notice Approves the SSV Network contract to transfer SSV tokens for deposits
    function safeApproveAllTokens() external override {
        // Approves the SSV Network contract to transfer SSV tokens for deposits
        IERC20(SSV_TOKEN).approve(SSV_NETWORK, type(uint256).max);
    }

    /// @notice Set the FeeAccumulator as the address for SSV validators to send MEV rewards to
    function setFeeRecipient() external {
        ISSVNetwork(SSV_NETWORK).setFeeRecipientAddress(
            FEE_ACCUMULATOR_ADDRESS
        );
    }

    /**
     * @notice Only accept ETH from the FeeAccumulator and the WETH contract - required when
     * unwrapping WETH just before staking it to the validator.
     * The strategy will also receive ETH from the priority fees of transactions when producing blocks
     * as defined in EIP-1559.
     * The tx fees come from the Beacon chain so do not need any EVM level permissions to receive ETH.
     * The tx fees are paid with each block produced. They are not included in the consensus rewards
     * which are periodically swept from the validators to this strategy.
     * For accounting purposes, the priority fees of transactions will be considered consensus rewards
     * and will be included in the AccountingConsensusRewards event.
     * @dev don't want to receive donations from anyone else as donations over the fuse limits will
     * mess with the accounting of the consensus rewards and validator full withdrawals.
     */
    receive() external payable {
        require(
            msg.sender == FEE_ACCUMULATOR_ADDRESS || msg.sender == WETH,
            "Eth not from allowed contracts"
        );
    }

    /***************************************
                Internal functions
    ****************************************/

    function _abstractSetPToken(address _asset, address) internal override {}

    /// @dev Convert accumulated ETH to WETH and send to the Harvester.
    /// Will revert if the strategy is paused for accounting.
    function _collectRewardTokens() internal override whenNotPaused {
        // collect ETH from execution rewards from the fee accumulator
        uint256 executionRewards = FeeAccumulator(FEE_ACCUMULATOR_ADDRESS)
            .collect();

        // total ETH rewards to be harvested = execution rewards + consensus rewards
        uint256 ethRewards = executionRewards + consensusRewards;

        require(
            address(this).balance >= ethRewards,
            "Insufficient eth balance"
        );

        if (ethRewards > 0) {
            // reset the counter keeping track of beacon chain consensus rewards
            consensusRewards = 0;

            // Convert ETH rewards to WETH
            IWETH9(WETH).deposit{ value: ethRewards }();

            IERC20(WETH).safeTransfer(harvesterAddress, ethRewards);
            emit RewardTokenCollected(harvesterAddress, WETH, ethRewards);
        }
    }

    /// @dev emits Withdrawal event from NativeStakingSSVStrategy
    function _wethWithdrawnToVault(uint256 _amount) internal override {
        emit Withdrawal(WETH, address(0), _amount);
    }

    /// @dev Called when WETH is withdrawn from the strategy or staked to a validator so
    /// the strategy knows how much WETH it has on deposit.
    /// This is so it can emit the correct amount in the Deposit event in depositAll().
    function _wethWithdrawn(uint256 _amount) internal override {
        /* In an ideal world we wouldn't need to reduce the deduction amount when the
         * depositedWethAccountedFor is smaller than the _amount.
         *
         * The reason this is required is that a malicious actor could sent WETH directly
         * to this contract and that would circumvent the increase of depositedWethAccountedFor
         * property. When the ETH would be staked the depositedWethAccountedFor amount could
         * be deducted so much that it would be negative.
         */
        uint256 deductAmount = Math.min(_amount, depositedWethAccountedFor);
        depositedWethAccountedFor -= deductAmount;
    }
}
ValidatorAccountant.sol 259 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { ValidatorRegistrator } from "./ValidatorRegistrator.sol";
import { IWETH9 } from "../../interfaces/IWETH9.sol";

/// @title Validator Accountant
/// @notice Attributes the ETH swept from beacon chain validators to this strategy contract
/// as either full or partial withdrawals. Partial withdrawals being consensus rewards.
/// Full withdrawals are from exited validators.
/// @author Origin Protocol Inc
abstract contract ValidatorAccountant is ValidatorRegistrator {
    /// @notice The minimum amount of blocks that need to pass between two calls to manuallyFixAccounting
    uint256 public constant MIN_FIX_ACCOUNTING_CADENCE = 7200; // 1 day

    /// @notice Keeps track of the total consensus rewards swept from the beacon chain
    uint256 public consensusRewards;

    /// @notice start of fuse interval
    uint256 public fuseIntervalStart;
    /// @notice end of fuse interval
    uint256 public fuseIntervalEnd;
    /// @notice last block number manuallyFixAccounting has been called
    uint256 public lastFixAccountingBlockNumber;

    uint256[49] private __gap;

    event FuseIntervalUpdated(uint256 start, uint256 end);
    event AccountingFullyWithdrawnValidator(
        uint256 noOfValidators,
        uint256 remainingValidators,
        uint256 wethSentToVault
    );
    event AccountingValidatorSlashed(
        uint256 remainingValidators,
        uint256 wethSentToVault
    );
    event AccountingConsensusRewards(uint256 amount);

    event AccountingManuallyFixed(
        int256 validatorsDelta,
        int256 consensusRewardsDelta,
        uint256 wethToVault
    );

    /// @param _wethAddress Address of the Erc20 WETH Token contract
    /// @param _vaultAddress Address of the Vault
    /// @param _beaconChainDepositContract Address of the beacon chain deposit contract
    /// @param _ssvNetwork Address of the SSV Network contract
    /// @param _maxValidators Maximum number of validators that can be registered in the strategy
    constructor(
        address _wethAddress,
        address _vaultAddress,
        address _beaconChainDepositContract,
        address _ssvNetwork,
        uint256 _maxValidators
    )
        ValidatorRegistrator(
            _wethAddress,
            _vaultAddress,
            _beaconChainDepositContract,
            _ssvNetwork,
            _maxValidators
        )
    {}

    /// @notice set fuse interval values
    function setFuseInterval(
        uint256 _fuseIntervalStart,
        uint256 _fuseIntervalEnd
    ) external onlyGovernor {
        require(
            _fuseIntervalStart < _fuseIntervalEnd &&
                _fuseIntervalEnd < 32 ether &&
                _fuseIntervalEnd - _fuseIntervalStart >= 4 ether,
            "Incorrect fuse interval"
        );

        fuseIntervalStart = _fuseIntervalStart;
        fuseIntervalEnd = _fuseIntervalEnd;

        emit FuseIntervalUpdated(_fuseIntervalStart, _fuseIntervalEnd);
    }

    /* solhint-disable max-line-length */
    /// This notion page offers a good explanation of how the accounting functions
    /// https://www.notion.so/originprotocol/Limited-simplified-native-staking-accounting-67a217c8420d40678eb943b9da0ee77d
    /// In short, after dividing by 32, if the ETH remaining on the contract falls between 0 and fuseIntervalStart,
    /// the accounting function will treat that ETH as Beacon chain consensus rewards.
    /// On the contrary, if after dividing by 32, the ETH remaining on the contract falls between fuseIntervalEnd and 32,
    /// the accounting function will treat that as a validator slashing.
    /// @notice Perform the accounting attributing beacon chain ETH to either full or partial withdrawals. Returns true when
    /// accounting is valid and fuse isn't "blown". Returns false when fuse is blown.
    /// @dev This function could in theory be permission-less but lets allow only the Registrator (Defender Action) to call it
    /// for now.
    /// @return accountingValid true if accounting was successful, false if fuse is blown
    /* solhint-enable max-line-length */
    function doAccounting()
        external
        onlyRegistrator
        whenNotPaused
        nonReentrant
        returns (bool accountingValid)
    {
        // pause the accounting on failure
        accountingValid = _doAccounting(true);
    }

    // slither-disable-start reentrancy-eth
    function _doAccounting(bool pauseOnFail)
        internal
        returns (bool accountingValid)
    {
        if (address(this).balance < consensusRewards) {
            return _failAccounting(pauseOnFail);
        }

        // Calculate all the new ETH that has been swept to the contract since the last accounting
        uint256 newSweptETH = address(this).balance - consensusRewards;
        accountingValid = true;

        // send the ETH that is from fully withdrawn validators to the Vault
        if (newSweptETH >= FULL_STAKE) {
            uint256 fullyWithdrawnValidators;
            // explicitly cast to uint256 as we want to round to a whole number of validators
            fullyWithdrawnValidators = uint256(newSweptETH / FULL_STAKE);
            activeDepositedValidators -= fullyWithdrawnValidators;

            uint256 wethToVault = FULL_STAKE * fullyWithdrawnValidators;
            IWETH9(WETH).deposit{ value: wethToVault }();
            // slither-disable-next-line unchecked-transfer
            IWETH9(WETH).transfer(VAULT_ADDRESS, wethToVault);
            _wethWithdrawnToVault(wethToVault);

            emit AccountingFullyWithdrawnValidator(
                fullyWithdrawnValidators,
                activeDepositedValidators,
                wethToVault
            );
        }

        uint256 ethRemaining = address(this).balance - consensusRewards;
        // should be less than a whole validator stake
        require(ethRemaining < FULL_STAKE, "Unexpected accounting");

        // If no Beacon chain consensus rewards swept
        if (ethRemaining == 0) {
            // do nothing
            return accountingValid;
        } else if (ethRemaining < fuseIntervalStart) {
            // Beacon chain consensus rewards swept (partial validator withdrawals)
            // solhint-disable-next-line reentrancy
            consensusRewards += ethRemaining;
            emit AccountingConsensusRewards(ethRemaining);
        } else if (ethRemaining > fuseIntervalEnd) {
            // Beacon chain consensus rewards swept but also a slashed validator fully exited
            IWETH9(WETH).deposit{ value: ethRemaining }();
            // slither-disable-next-line unchecked-transfer
            IWETH9(WETH).transfer(VAULT_ADDRESS, ethRemaining);
            activeDepositedValidators -= 1;

            _wethWithdrawnToVault(ethRemaining);

            emit AccountingValidatorSlashed(
                activeDepositedValidators,
                ethRemaining
            );
        }
        // Oh no... Fuse is blown. The Strategist needs to adjust the accounting values.
        else {
            return _failAccounting(pauseOnFail);
        }
    }

    // slither-disable-end reentrancy-eth

    /// @dev pause any further accounting if required and return false
    function _failAccounting(bool pauseOnFail)
        internal
        returns (bool accountingValid)
    {
        // pause if not already
        if (pauseOnFail) {
            _pause();
        }
        // fail the accounting
        accountingValid = false;
    }

    /// @notice Allow the Strategist to fix the accounting of this strategy and unpause.
    /// @param _validatorsDelta adjust the active validators by up to plus three or minus three
    /// @param _consensusRewardsDelta adjust the accounted for consensus rewards up or down
    /// @param _ethToVaultAmount the amount of ETH that gets wrapped into WETH and sent to the Vault
    /// @dev There is a case when a validator(s) gets slashed so much that the eth swept from
    /// the beacon chain enters the fuse area and there are no consensus rewards on the contract
    /// to "dip into"/use. To increase the amount of unaccounted ETH over the fuse end interval
    /// we need to reduce the amount of active deposited validators and immediately send WETH
    /// to the vault, so it doesn't interfere with further accounting.
    function manuallyFixAccounting(
        int256 _validatorsDelta,
        int256 _consensusRewardsDelta,
        uint256 _ethToVaultAmount
    ) external onlyStrategist whenPaused nonReentrant {
        require(
            lastFixAccountingBlockNumber + MIN_FIX_ACCOUNTING_CADENCE <
                block.number,
            "Fix accounting called too soon"
        );
        require(
            _validatorsDelta >= -3 &&
                _validatorsDelta <= 3 &&
                // new value must be positive
                int256(activeDepositedValidators) + _validatorsDelta >= 0,
            "Invalid validatorsDelta"
        );
        require(
            _consensusRewardsDelta >= -332 ether &&
                _consensusRewardsDelta <= 332 ether &&
                // new value must be positive
                int256(consensusRewards) + _consensusRewardsDelta >= 0,
            "Invalid consensusRewardsDelta"
        );
        require(_ethToVaultAmount <= 32 ether * 3, "Invalid wethToVaultAmount");

        activeDepositedValidators = uint256(
            int256(activeDepositedValidators) + _validatorsDelta
        );
        consensusRewards = uint256(
            int256(consensusRewards) + _consensusRewardsDelta
        );
        lastFixAccountingBlockNumber = block.number;
        if (_ethToVaultAmount > 0) {
            IWETH9(WETH).deposit{ value: _ethToVaultAmount }();
            // slither-disable-next-line unchecked-transfer
            IWETH9(WETH).transfer(VAULT_ADDRESS, _ethToVaultAmount);
            _wethWithdrawnToVault(_ethToVaultAmount);
        }

        emit AccountingManuallyFixed(
            _validatorsDelta,
            _consensusRewardsDelta,
            _ethToVaultAmount
        );

        // rerun the accounting to see if it has now been fixed.
        // Do not pause the accounting on failure as it is already paused
        require(_doAccounting(false), "Fuse still blown");

        // unpause since doAccounting was successful
        _unpause();
    }

    /***************************************
                 Abstract
    ****************************************/

    /// @dev allows for NativeStakingSSVStrategy contract to emit the Withdrawal event
    function _wethWithdrawnToVault(uint256 _amount) internal virtual;
}
ValidatorRegistrator.sol 371 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import { Governable } from "../../governance/Governable.sol";
import { IDepositContract } from "../../interfaces/IDepositContract.sol";
import { IVault } from "../../interfaces/IVault.sol";
import { IWETH9 } from "../../interfaces/IWETH9.sol";
import { ISSVNetwork, Cluster } from "../../interfaces/ISSVNetwork.sol";

struct ValidatorStakeData {
    bytes pubkey;
    bytes signature;
    bytes32 depositDataRoot;
}

/**
 * @title Registrator of the validators
 * @notice This contract implements all the required functionality to register, exit and remove validators.
 * @author Origin Protocol Inc
 */
abstract contract ValidatorRegistrator is Governable, Pausable {
    /// @notice The maximum amount of ETH that can be staked by a validator
    /// @dev this can change in the future with EIP-7251, Increase the MAX_EFFECTIVE_BALANCE
    uint256 public constant FULL_STAKE = 32 ether;

    /// @notice The address of the Wrapped ETH (WETH) token contract
    address public immutable WETH;
    /// @notice The address of the beacon chain deposit contract
    address public immutable BEACON_CHAIN_DEPOSIT_CONTRACT;
    /// @notice The address of the SSV Network contract used to interface with
    address public immutable SSV_NETWORK;
    /// @notice Address of the OETH Vault proxy contract
    address public immutable VAULT_ADDRESS;
    /// @notice Maximum number of validators that can be registered in this strategy
    uint256 public immutable MAX_VALIDATORS;

    /// @notice Address of the registrator - allowed to register, exit and remove validators
    address public validatorRegistrator;
    /// @notice The number of validators that have 32 (!) ETH actively deposited. When a new deposit
    /// to a validator happens this number increases, when a validator exit is detected this number
    /// decreases.
    uint256 public activeDepositedValidators;
    /// @notice State of the validators keccak256(pubKey) => state
    mapping(bytes32 => VALIDATOR_STATE) public validatorsStates;
    /// @notice The account that is allowed to modify stakeETHThreshold and reset stakeETHTally
    address public stakingMonitor;
    /// @notice Amount of ETH that can be staked before staking on the contract is suspended
    /// and the `stakingMonitor` needs to approve further staking by calling `resetStakeETHTally`
    uint256 public stakeETHThreshold;
    /// @notice Amount of ETH that has been staked since the `stakingMonitor` last called `resetStakeETHTally`.
    /// This can not go above `stakeETHThreshold`.
    uint256 public stakeETHTally;
    // For future use
    uint256[47] private __gap;

    enum VALIDATOR_STATE {
        NON_REGISTERED, // validator is not registered on the SSV network
        REGISTERED, // validator is registered on the SSV network
        STAKED, // validator has funds staked
        EXITING, // exit message has been posted and validator is in the process of exiting
        EXIT_COMPLETE // validator has funds withdrawn to the EigenPod and is removed from the SSV
    }

    event RegistratorChanged(address indexed newAddress);
    event StakingMonitorChanged(address indexed newAddress);
    event ETHStaked(bytes32 indexed pubKeyHash, bytes pubKey, uint256 amount);
    event SSVValidatorRegistered(
        bytes32 indexed pubKeyHash,
        bytes pubKey,
        uint64[] operatorIds
    );
    event SSVValidatorExitInitiated(
        bytes32 indexed pubKeyHash,
        bytes pubKey,
        uint64[] operatorIds
    );
    event SSVValidatorExitCompleted(
        bytes32 indexed pubKeyHash,
        bytes pubKey,
        uint64[] operatorIds
    );
    event StakeETHThresholdChanged(uint256 amount);
    event StakeETHTallyReset();

    /// @dev Throws if called by any account other than the Registrator
    modifier onlyRegistrator() {
        require(
            msg.sender == validatorRegistrator,
            "Caller is not the Registrator"
        );
        _;
    }

    /// @dev Throws if called by any account other than the Staking monitor
    modifier onlyStakingMonitor() {
        require(msg.sender == stakingMonitor, "Caller is not the Monitor");
        _;
    }

    /// @dev Throws if called by any account other than the Strategist
    modifier onlyStrategist() {
        require(
            msg.sender == IVault(VAULT_ADDRESS).strategistAddr(),
            "Caller is not the Strategist"
        );
        _;
    }

    /// @param _wethAddress Address of the Erc20 WETH Token contract
    /// @param _vaultAddress Address of the Vault
    /// @param _beaconChainDepositContract Address of the beacon chain deposit contract
    /// @param _ssvNetwork Address of the SSV Network contract
    /// @param _maxValidators Maximum number of validators that can be registered in the strategy
    constructor(
        address _wethAddress,
        address _vaultAddress,
        address _beaconChainDepositContract,
        address _ssvNetwork,
        uint256 _maxValidators
    ) {
        WETH = _wethAddress;
        BEACON_CHAIN_DEPOSIT_CONTRACT = _beaconChainDepositContract;
        SSV_NETWORK = _ssvNetwork;
        VAULT_ADDRESS = _vaultAddress;
        MAX_VALIDATORS = _maxValidators;
    }

    /// @notice Set the address of the registrator which can register, exit and remove validators
    function setRegistrator(address _address) external onlyGovernor {
        validatorRegistrator = _address;
        emit RegistratorChanged(_address);
    }

    /// @notice Set the address of the staking monitor that is allowed to reset stakeETHTally
    function setStakingMonitor(address _address) external onlyGovernor {
        stakingMonitor = _address;
        emit StakingMonitorChanged(_address);
    }

    /// @notice Set the amount of ETH that can be staked before staking monitor
    // needs to a approve further staking by resetting the stake ETH tally
    function setStakeETHThreshold(uint256 _amount) external onlyGovernor {
        stakeETHThreshold = _amount;
        emit StakeETHThresholdChanged(_amount);
    }

    /// @notice Reset the stakeETHTally
    function resetStakeETHTally() external onlyStakingMonitor {
        stakeETHTally = 0;
        emit StakeETHTallyReset();
    }

    /// @notice Stakes WETH to the node validators
    /// @param validators A list of validator data needed to stake.
    /// The `ValidatorStakeData` struct contains the pubkey, signature and depositDataRoot.
    /// Only the registrator can call this function.
    // slither-disable-start reentrancy-eth
    function stakeEth(ValidatorStakeData[] calldata validators)
        external
        onlyRegistrator
        whenNotPaused
        nonReentrant
    {
        uint256 requiredETH = validators.length * FULL_STAKE;

        // Check there is enough WETH from the deposits sitting in this strategy contract
        require(
            requiredETH <= IWETH9(WETH).balanceOf(address(this)),
            "Insufficient WETH"
        );
        require(
            activeDepositedValidators + validators.length <= MAX_VALIDATORS,
            "Max validators reached"
        );

        require(
            stakeETHTally + requiredETH <= stakeETHThreshold,
            "Staking ETH over threshold"
        );
        stakeETHTally += requiredETH;

        // Convert required ETH from WETH
        IWETH9(WETH).withdraw(requiredETH);
        _wethWithdrawn(requiredETH);

        /* 0x01 to indicate that withdrawal credentials will contain an EOA address that the sweeping function
         * can sweep funds to.
         * bytes11(0) to fill up the required zeros
         * remaining bytes20 are for the address
         */
        bytes memory withdrawalCredentials = abi.encodePacked(
            bytes1(0x01),
            bytes11(0),
            address(this)
        );

        // For each validator
        for (uint256 i = 0; i < validators.length; ++i) {
            bytes32 pubKeyHash = keccak256(validators[i].pubkey);

            require(
                validatorsStates[pubKeyHash] == VALIDATOR_STATE.REGISTERED,
                "Validator not registered"
            );

            IDepositContract(BEACON_CHAIN_DEPOSIT_CONTRACT).deposit{
                value: FULL_STAKE
            }(
                validators[i].pubkey,
                withdrawalCredentials,
                validators[i].signature,
                validators[i].depositDataRoot
            );

            validatorsStates[pubKeyHash] = VALIDATOR_STATE.STAKED;

            emit ETHStaked(pubKeyHash, validators[i].pubkey, FULL_STAKE);
        }
        // save gas by changing this storage variable only once rather each time in the loop.
        activeDepositedValidators += validators.length;
    }

    // slither-disable-end reentrancy-eth

    /// @notice Registers a new validator in the SSV Cluster.
    /// Only the registrator can call this function.
    /// @param publicKeys The public keys of the validators
    /// @param operatorIds The operator IDs of the SSV Cluster
    /// @param sharesData The shares data for each validator
    /// @param ssvAmount The amount of SSV tokens to be deposited to the SSV cluster
    /// @param cluster The SSV cluster details including the validator count and SSV balance
    // slither-disable-start reentrancy-no-eth
    function registerSsvValidators(
        bytes[] calldata publicKeys,
        uint64[] calldata operatorIds,
        bytes[] calldata sharesData,
        uint256 ssvAmount,
        Cluster calldata cluster
    ) external onlyRegistrator whenNotPaused {
        require(
            publicKeys.length == sharesData.length,
            "Pubkey sharesData mismatch"
        );
        // Check each public key has not already been used
        bytes32 pubKeyHash;
        VALIDATOR_STATE currentState;
        for (uint256 i = 0; i < publicKeys.length; ++i) {
            pubKeyHash = keccak256(publicKeys[i]);
            currentState = validatorsStates[pubKeyHash];
            require(
                currentState == VALIDATOR_STATE.NON_REGISTERED,
                "Validator already registered"
            );

            validatorsStates[pubKeyHash] = VALIDATOR_STATE.REGISTERED;

            emit SSVValidatorRegistered(pubKeyHash, publicKeys[i], operatorIds);
        }

        ISSVNetwork(SSV_NETWORK).bulkRegisterValidator(
            publicKeys,
            operatorIds,
            sharesData,
            ssvAmount,
            cluster
        );
    }

    // slither-disable-end reentrancy-no-eth

    /// @notice Exit a validator from the Beacon chain.
    /// The staked ETH will eventually swept to this native staking strategy.
    /// Only the registrator can call this function.
    /// @param publicKey The public key of the validator
    /// @param operatorIds The operator IDs of the SSV Cluster
    // slither-disable-start reentrancy-no-eth
    function exitSsvValidator(
        bytes calldata publicKey,
        uint64[] calldata operatorIds
    ) external onlyRegistrator whenNotPaused {
        bytes32 pubKeyHash = keccak256(publicKey);
        VALIDATOR_STATE currentState = validatorsStates[pubKeyHash];
        require(currentState == VALIDATOR_STATE.STAKED, "Validator not staked");

        ISSVNetwork(SSV_NETWORK).exitValidator(publicKey, operatorIds);

        validatorsStates[pubKeyHash] = VALIDATOR_STATE.EXITING;

        emit SSVValidatorExitInitiated(pubKeyHash, publicKey, operatorIds);
    }

    // slither-disable-end reentrancy-no-eth

    /// @notice Remove a validator from the SSV Cluster.
    /// Make sure `exitSsvValidator` is called before and the validate has exited the Beacon chain.
    /// If removed before the validator has exited the beacon chain will result in the validator being slashed.
    /// Only the registrator can call this function.
    /// @param publicKey The public key of the validator
    /// @param operatorIds The operator IDs of the SSV Cluster
    /// @param cluster The SSV cluster details including the validator count and SSV balance
    // slither-disable-start reentrancy-no-eth
    function removeSsvValidator(
        bytes calldata publicKey,
        uint64[] calldata operatorIds,
        Cluster calldata cluster
    ) external onlyRegistrator whenNotPaused {
        bytes32 pubKeyHash = keccak256(publicKey);
        VALIDATOR_STATE currentState = validatorsStates[pubKeyHash];
        // Can remove SSV validators that were incorrectly registered and can not be deposited to.
        require(
            currentState == VALIDATOR_STATE.EXITING ||
                currentState == VALIDATOR_STATE.REGISTERED,
            "Validator not regd or exiting"
        );

        ISSVNetwork(SSV_NETWORK).removeValidator(
            publicKey,
            operatorIds,
            cluster
        );

        validatorsStates[pubKeyHash] = VALIDATOR_STATE.EXIT_COMPLETE;

        emit SSVValidatorExitCompleted(pubKeyHash, publicKey, operatorIds);
    }

    // slither-disable-end reentrancy-no-eth

    /// @notice Deposits more SSV Tokens to the SSV Network contract which is used to pay the SSV Operators.
    /// @dev A SSV cluster is defined by the SSVOwnerAddress and the set of operatorIds.
    /// uses "onlyStrategist" modifier so continuous front-running can't DOS our maintenance service
    /// that tries to top up SSV tokens.
    /// @param operatorIds The operator IDs of the SSV Cluster
    /// @param ssvAmount The amount of SSV tokens to be deposited to the SSV cluster
    /// @param cluster The SSV cluster details including the validator count and SSV balance
    function depositSSV(
        uint64[] memory operatorIds,
        uint256 ssvAmount,
        Cluster memory cluster
    ) external onlyStrategist {
        ISSVNetwork(SSV_NETWORK).deposit(
            address(this),
            operatorIds,
            ssvAmount,
            cluster
        );
    }

    /// @notice Withdraws excess SSV Tokens from the SSV Network contract which was used to pay the SSV Operators.
    /// @dev A SSV cluster is defined by the SSVOwnerAddress and the set of operatorIds.
    /// @param operatorIds The operator IDs of the SSV Cluster
    /// @param ssvAmount The amount of SSV tokens to be deposited to the SSV cluster
    /// @param cluster The SSV cluster details including the validator count and SSV balance
    function withdrawSSV(
        uint64[] memory operatorIds,
        uint256 ssvAmount,
        Cluster memory cluster
    ) external onlyGovernor {
        ISSVNetwork(SSV_NETWORK).withdraw(operatorIds, ssvAmount, cluster);
    }

    /***************************************
                 Abstract
    ****************************************/

    /// @dev Called when WETH is withdrawn from the strategy or staked to a validator so
    /// the strategy knows how much WETH it has on deposit.
    /// This is so it can emit the correct amount in the Deposit event in depositAll().
    function _wethWithdrawn(uint256 _amount) internal virtual;
}
OUSD.sol 712 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title OUSD Token Contract
 * @dev ERC20 compatible contract for OUSD
 * @dev Implements an elastic supply
 * @author Origin Protocol Inc
 */
import { Governable } from "../governance/Governable.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

contract OUSD is Governable {
    using SafeCast for int256;
    using SafeCast for uint256;

    /// @dev Event triggered when the supply changes
    /// @param totalSupply Updated token total supply
    /// @param rebasingCredits Updated token rebasing credits
    /// @param rebasingCreditsPerToken Updated token rebasing credits per token
    event TotalSupplyUpdatedHighres(
        uint256 totalSupply,
        uint256 rebasingCredits,
        uint256 rebasingCreditsPerToken
    );
    /// @dev Event triggered when an account opts in for rebasing
    /// @param account Address of the account
    event AccountRebasingEnabled(address account);
    /// @dev Event triggered when an account opts out of rebasing
    /// @param account Address of the account
    event AccountRebasingDisabled(address account);
    /// @dev Emitted when `value` tokens are moved from one account `from` to
    ///      another `to`.
    /// @param from Address of the account tokens are moved from
    /// @param to Address of the account tokens are moved to
    /// @param value Amount of tokens transferred
    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.
    /// @param owner Address of the owner approving allowance
    /// @param spender Address of the spender allowance is granted to
    /// @param value Amount of tokens spender can transfer
    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 value
    );
    /// @dev Yield resulting from {changeSupply} that a `source` account would
    ///      receive is directed to `target` account.
    /// @param source Address of the source forwarding the yield
    /// @param target Address of the target receiving the yield
    event YieldDelegated(address source, address target);
    /// @dev Yield delegation from `source` account to the `target` account is
    ///      suspended.
    /// @param source Address of the source suspending yield forwarding
    /// @param target Address of the target no longer receiving yield from `source`
    ///        account
    event YieldUndelegated(address source, address target);

    enum RebaseOptions {
        NotSet,
        StdNonRebasing,
        StdRebasing,
        YieldDelegationSource,
        YieldDelegationTarget
    }

    uint256[154] private _gap; // Slots to align with deployed contract
    uint256 private constant MAX_SUPPLY = type(uint128).max;
    /// @dev The amount of tokens in existence
    uint256 public totalSupply;
    mapping(address => mapping(address => uint256)) private allowances;
    /// @dev The vault with privileges to execute {mint}, {burn}
    ///     and {changeSupply}
    address public vaultAddress;
    mapping(address => uint256) internal creditBalances;
    // the 2 storage variables below need trailing underscores to not name collide with public functions
    uint256 private rebasingCredits_; // Sum of all rebasing credits (creditBalances for rebasing accounts)
    uint256 private rebasingCreditsPerToken_;
    /// @dev The amount of tokens that are not rebasing - receiving yield
    uint256 public nonRebasingSupply;
    mapping(address => uint256) internal alternativeCreditsPerToken;
    /// @dev A map of all addresses and their respective RebaseOptions
    mapping(address => RebaseOptions) public rebaseState;
    mapping(address => uint256) private __deprecated_isUpgraded;
    /// @dev A map of addresses that have yields forwarded to. This is an
    ///      inverse mapping of {yieldFrom}
    /// Key Account forwarding yield
    /// Value Account receiving yield
    mapping(address => address) public yieldTo;
    /// @dev A map of addresses that are receiving the yield. This is an
    ///      inverse mapping of {yieldTo}
    /// Key Account receiving yield
    /// Value Account forwarding yield
    mapping(address => address) public yieldFrom;

    uint256 private constant RESOLUTION_INCREASE = 1e9;
    uint256[34] private __gap; // including below gap totals up to 200

    /// @dev Initializes the contract and sets necessary variables.
    /// @param _vaultAddress Address of the vault contract
    /// @param _initialCreditsPerToken The starting rebasing credits per token.
    function initialize(address _vaultAddress, uint256 _initialCreditsPerToken)
        external
        onlyGovernor
    {
        require(_vaultAddress != address(0), "Zero vault address");
        require(vaultAddress == address(0), "Already initialized");

        rebasingCreditsPerToken_ = _initialCreditsPerToken;
        vaultAddress = _vaultAddress;
    }

    /// @dev Returns the symbol of the token, a shorter version
    ///      of the name.
    function symbol() external pure virtual returns (string memory) {
        return "OUSD";
    }

    /// @dev Returns the name of the token.
    function name() external pure virtual returns (string memory) {
        return "Origin Dollar";
    }

    /// @dev Returns the number of decimals used to get its user representation.
    function decimals() external pure virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev Verifies that the caller is the Vault contract
     */
    modifier onlyVault() {
        require(vaultAddress == msg.sender, "Caller is not the Vault");
        _;
    }

    /**
     * @return High resolution rebasingCreditsPerToken
     */
    function rebasingCreditsPerTokenHighres() external view returns (uint256) {
        return rebasingCreditsPerToken_;
    }

    /**
     * @return Low resolution rebasingCreditsPerToken
     */
    function rebasingCreditsPerToken() external view returns (uint256) {
        return rebasingCreditsPerToken_ / RESOLUTION_INCREASE;
    }

    /**
     * @return High resolution total number of rebasing credits
     */
    function rebasingCreditsHighres() external view returns (uint256) {
        return rebasingCredits_;
    }

    /**
     * @return Low resolution total number of rebasing credits
     */
    function rebasingCredits() external view returns (uint256) {
        return rebasingCredits_ / RESOLUTION_INCREASE;
    }

    /**
     * @notice Gets the balance of the specified address.
     * @param _account Address to query the balance of.
     * @return A uint256 representing the amount of base units owned by the
     *         specified address.
     */
    function balanceOf(address _account) public view returns (uint256) {
        RebaseOptions state = rebaseState[_account];
        if (state == RebaseOptions.YieldDelegationSource) {
            // Saves a slot read when transferring to or from a yield delegating source
            // since we know creditBalances equals the balance.
            return creditBalances[_account];
        }
        uint256 baseBalance = (creditBalances[_account] * 1e18) /
            _creditsPerToken(_account);
        if (state == RebaseOptions.YieldDelegationTarget) {
            // creditBalances of yieldFrom accounts equals token balances
            return baseBalance - creditBalances[yieldFrom[_account]];
        }
        return baseBalance;
    }

    /**
     * @notice Gets the credits balance of the specified address.
     * @dev Backwards compatible with old low res credits per token.
     * @param _account The address to query the balance of.
     * @return (uint256, uint256) Credit balance and credits per token of the
     *         address
     */
    function creditsBalanceOf(address _account)
        external
        view
        returns (uint256, uint256)
    {
        uint256 cpt = _creditsPerToken(_account);
        if (cpt == 1e27) {
            // For a period before the resolution upgrade, we created all new
            // contract accounts at high resolution. Since they are not changing
            // as a result of this upgrade, we will return their true values
            return (creditBalances[_account], cpt);
        } else {
            return (
                creditBalances[_account] / RESOLUTION_INCREASE,
                cpt / RESOLUTION_INCREASE
            );
        }
    }

    /**
     * @notice Gets the credits balance of the specified address.
     * @param _account The address to query the balance of.
     * @return (uint256, uint256, bool) Credit balance, credits per token of the
     *         address, and isUpgraded
     */
    function creditsBalanceOfHighres(address _account)
        external
        view
        returns (
            uint256,
            uint256,
            bool
        )
    {
        return (
            creditBalances[_account],
            _creditsPerToken(_account),
            true // all accounts have their resolution "upgraded"
        );
    }

    // Backwards compatible view
    function nonRebasingCreditsPerToken(address _account)
        external
        view
        returns (uint256)
    {
        return alternativeCreditsPerToken[_account];
    }

    /**
     * @notice Transfer tokens to a specified address.
     * @param _to the address to transfer to.
     * @param _value the amount to be transferred.
     * @return true on success.
     */
    function transfer(address _to, uint256 _value) external returns (bool) {
        require(_to != address(0), "Transfer to zero address");

        _executeTransfer(msg.sender, _to, _value);

        emit Transfer(msg.sender, _to, _value);
        return true;
    }

    /**
     * @notice Transfer tokens from one address to another.
     * @param _from The address you want to send tokens from.
     * @param _to The address you want to transfer to.
     * @param _value The amount of tokens to be transferred.
     * @return true on success.
     */
    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) external returns (bool) {
        require(_to != address(0), "Transfer to zero address");
        uint256 userAllowance = allowances[_from][msg.sender];
        require(_value <= userAllowance, "Allowance exceeded");

        unchecked {
            allowances[_from][msg.sender] = userAllowance - _value;
        }

        _executeTransfer(_from, _to, _value);

        emit Transfer(_from, _to, _value);
        return true;
    }

    function _executeTransfer(
        address _from,
        address _to,
        uint256 _value
    ) internal {
        (
            int256 fromRebasingCreditsDiff,
            int256 fromNonRebasingSupplyDiff
        ) = _adjustAccount(_from, -_value.toInt256());
        (
            int256 toRebasingCreditsDiff,
            int256 toNonRebasingSupplyDiff
        ) = _adjustAccount(_to, _value.toInt256());

        _adjustGlobals(
            fromRebasingCreditsDiff + toRebasingCreditsDiff,
            fromNonRebasingSupplyDiff + toNonRebasingSupplyDiff
        );
    }

    function _adjustAccount(address _account, int256 _balanceChange)
        internal
        returns (int256 rebasingCreditsDiff, int256 nonRebasingSupplyDiff)
    {
        RebaseOptions state = rebaseState[_account];
        int256 currentBalance = balanceOf(_account).toInt256();
        if (currentBalance + _balanceChange < 0) {
            revert("Transfer amount exceeds balance");
        }
        uint256 newBalance = (currentBalance + _balanceChange).toUint256();

        if (state == RebaseOptions.YieldDelegationSource) {
            address target = yieldTo[_account];
            uint256 targetOldBalance = balanceOf(target);
            uint256 targetNewCredits = _balanceToRebasingCredits(
                targetOldBalance + newBalance
            );
            rebasingCreditsDiff =
                targetNewCredits.toInt256() -
                creditBalances[target].toInt256();

            creditBalances[_account] = newBalance;
            creditBalances[target] = targetNewCredits;
        } else if (state == RebaseOptions.YieldDelegationTarget) {
            uint256 newCredits = _balanceToRebasingCredits(
                newBalance + creditBalances[yieldFrom[_account]]
            );
            rebasingCreditsDiff =
                newCredits.toInt256() -
                creditBalances[_account].toInt256();
            creditBalances[_account] = newCredits;
        } else {
            _autoMigrate(_account);
            uint256 alternativeCreditsPerTokenMem = alternativeCreditsPerToken[
                _account
            ];
            if (alternativeCreditsPerTokenMem > 0) {
                nonRebasingSupplyDiff = _balanceChange;
                if (alternativeCreditsPerTokenMem != 1e18) {
                    alternativeCreditsPerToken[_account] = 1e18;
                }
                creditBalances[_account] = newBalance;
            } else {
                uint256 newCredits = _balanceToRebasingCredits(newBalance);
                rebasingCreditsDiff =
                    newCredits.toInt256() -
                    creditBalances[_account].toInt256();
                creditBalances[_account] = newCredits;
            }
        }
    }

    function _adjustGlobals(
        int256 _rebasingCreditsDiff,
        int256 _nonRebasingSupplyDiff
    ) internal {
        if (_rebasingCreditsDiff != 0) {
            rebasingCredits_ = (rebasingCredits_.toInt256() +
                _rebasingCreditsDiff).toUint256();
        }
        if (_nonRebasingSupplyDiff != 0) {
            nonRebasingSupply = (nonRebasingSupply.toInt256() +
                _nonRebasingSupplyDiff).toUint256();
        }
    }

    /**
     * @notice Function to check the amount of tokens that _owner has allowed
     *      to `_spender`.
     * @param _owner The address which owns the funds.
     * @param _spender The address which will spend the funds.
     * @return The number of tokens still available for the _spender.
     */
    function allowance(address _owner, address _spender)
        external
        view
        returns (uint256)
    {
        return allowances[_owner][_spender];
    }

    /**
     * @notice Approve the passed address to spend the specified amount of
     *      tokens on behalf of msg.sender.
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     * @return true on success.
     */
    function approve(address _spender, uint256 _value) external returns (bool) {
        allowances[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @notice Creates `_amount` tokens and assigns them to `_account`,
     *     increasing the total supply.
     */
    function mint(address _account, uint256 _amount) external onlyVault {
        require(_account != address(0), "Mint to the zero address");

        // Account
        (
            int256 toRebasingCreditsDiff,
            int256 toNonRebasingSupplyDiff
        ) = _adjustAccount(_account, _amount.toInt256());
        // Globals
        _adjustGlobals(toRebasingCreditsDiff, toNonRebasingSupplyDiff);
        totalSupply = totalSupply + _amount;

        require(totalSupply < MAX_SUPPLY, "Max supply");
        emit Transfer(address(0), _account, _amount);
    }

    /**
     * @notice Destroys `_amount` tokens from `_account`,
     *     reducing the total supply.
     */
    function burn(address _account, uint256 _amount) external onlyVault {
        require(_account != address(0), "Burn from the zero address");
        if (_amount == 0) {
            return;
        }

        // Account
        (
            int256 toRebasingCreditsDiff,
            int256 toNonRebasingSupplyDiff
        ) = _adjustAccount(_account, -_amount.toInt256());
        // Globals
        _adjustGlobals(toRebasingCreditsDiff, toNonRebasingSupplyDiff);
        totalSupply = totalSupply - _amount;

        emit Transfer(_account, address(0), _amount);
    }

    /**
     * @dev Get the credits per token for an account. Returns a fixed amount
     *      if the account is non-rebasing.
     * @param _account Address of the account.
     */
    function _creditsPerToken(address _account)
        internal
        view
        returns (uint256)
    {
        uint256 alternativeCreditsPerTokenMem = alternativeCreditsPerToken[
            _account
        ];
        if (alternativeCreditsPerTokenMem != 0) {
            return alternativeCreditsPerTokenMem;
        } else {
            return rebasingCreditsPerToken_;
        }
    }

    /**
     * @dev Auto migrate contracts to be non rebasing,
     *     unless they have opted into yield.
     * @param _account Address of the account.
     */
    function _autoMigrate(address _account) internal {
        bool isContract = _account.code.length > 0;
        // In previous code versions, contracts would not have had their
        // rebaseState[_account] set to RebaseOptions.NonRebasing when migrated
        // therefore we check the actual accounting used on the account instead.
        if (
            isContract &&
            rebaseState[_account] == RebaseOptions.NotSet &&
            alternativeCreditsPerToken[_account] == 0
        ) {
            _rebaseOptOut(_account);
        }
    }

    /**
     * @dev Calculates credits from contract's global rebasingCreditsPerToken_, and
     *      also balance that corresponds to those credits. The latter is important
     *      when adjusting the contract's global nonRebasingSupply to circumvent any
     *      possible rounding errors.
     *
     * @param _balance Balance of the account.
     */
    function _balanceToRebasingCredits(uint256 _balance)
        internal
        view
        returns (uint256 rebasingCredits)
    {
        // Rounds up, because we need to ensure that accounts always have
        // at least the balance that they should have.
        // Note this should always be used on an absolute account value,
        // not on a possibly negative diff, because then the rounding would be wrong.
        return ((_balance) * rebasingCreditsPerToken_ + 1e18 - 1) / 1e18;
    }

    /**
     * @notice The calling account will start receiving yield after a successful call.
     * @param _account Address of the account.
     */
    function governanceRebaseOptIn(address _account) external onlyGovernor {
        require(_account != address(0), "Zero address not allowed");
        _rebaseOptIn(_account);
    }

    /**
     * @notice The calling account will start receiving yield after a successful call.
     */
    function rebaseOptIn() external {
        _rebaseOptIn(msg.sender);
    }

    function _rebaseOptIn(address _account) internal {
        uint256 balance = balanceOf(_account);

        // prettier-ignore
        require(
            alternativeCreditsPerToken[_account] > 0 ||
                // Accounts may explicitly `rebaseOptIn` regardless of
                // accounting if they have a 0 balance.
                creditBalances[_account] == 0
            ,
            "Account must be non-rebasing"
        );
        RebaseOptions state = rebaseState[_account];
        // prettier-ignore
        require(
            state == RebaseOptions.StdNonRebasing ||
                state == RebaseOptions.NotSet,
            "Only standard non-rebasing accounts can opt in"
        );

        uint256 newCredits = _balanceToRebasingCredits(balance);

        // Account
        rebaseState[_account] = RebaseOptions.StdRebasing;
        alternativeCreditsPerToken[_account] = 0;
        creditBalances[_account] = newCredits;
        // Globals
        _adjustGlobals(newCredits.toInt256(), -balance.toInt256());

        emit AccountRebasingEnabled(_account);
    }

    /**
     * @notice The calling account will no longer receive yield
     */
    function rebaseOptOut() external {
        _rebaseOptOut(msg.sender);
    }

    function _rebaseOptOut(address _account) internal {
        require(
            alternativeCreditsPerToken[_account] == 0,
            "Account must be rebasing"
        );
        RebaseOptions state = rebaseState[_account];
        require(
            state == RebaseOptions.StdRebasing || state == RebaseOptions.NotSet,
            "Only standard rebasing accounts can opt out"
        );

        uint256 oldCredits = creditBalances[_account];
        uint256 balance = balanceOf(_account);

        // Account
        rebaseState[_account] = RebaseOptions.StdNonRebasing;
        alternativeCreditsPerToken[_account] = 1e18;
        creditBalances[_account] = balance;
        // Globals
        _adjustGlobals(-oldCredits.toInt256(), balance.toInt256());

        emit AccountRebasingDisabled(_account);
    }

    /**
     * @notice Distribute yield to users. This changes the exchange rate
     *  between "credits" and OUSD tokens to change rebasing user's balances.
     * @param _newTotalSupply New total supply of OUSD.
     */
    function changeSupply(uint256 _newTotalSupply) external onlyVault {
        require(totalSupply > 0, "Cannot increase 0 supply");

        if (totalSupply == _newTotalSupply) {
            emit TotalSupplyUpdatedHighres(
                totalSupply,
                rebasingCredits_,
                rebasingCreditsPerToken_
            );
            return;
        }

        totalSupply = _newTotalSupply > MAX_SUPPLY
            ? MAX_SUPPLY
            : _newTotalSupply;

        uint256 rebasingSupply = totalSupply - nonRebasingSupply;
        // round up in the favour of the protocol
        rebasingCreditsPerToken_ =
            (rebasingCredits_ * 1e18 + rebasingSupply - 1) /
            rebasingSupply;

        require(rebasingCreditsPerToken_ > 0, "Invalid change in supply");

        emit TotalSupplyUpdatedHighres(
            totalSupply,
            rebasingCredits_,
            rebasingCreditsPerToken_
        );
    }

    /*
     * @notice Send the yield from one account to another account.
     *         Each account keeps its own balances.
     */
    function delegateYield(address _from, address _to) external onlyGovernor {
        require(_from != address(0), "Zero from address not allowed");
        require(_to != address(0), "Zero to address not allowed");

        require(_from != _to, "Cannot delegate to self");
        require(
            yieldFrom[_to] == address(0) &&
                yieldTo[_to] == address(0) &&
                yieldFrom[_from] == address(0) &&
                yieldTo[_from] == address(0),
            "Blocked by existing yield delegation"
        );
        RebaseOptions stateFrom = rebaseState[_from];
        RebaseOptions stateTo = rebaseState[_to];

        require(
            stateFrom == RebaseOptions.NotSet ||
                stateFrom == RebaseOptions.StdNonRebasing ||
                stateFrom == RebaseOptions.StdRebasing,
            "Invalid rebaseState from"
        );

        require(
            stateTo == RebaseOptions.NotSet ||
                stateTo == RebaseOptions.StdNonRebasing ||
                stateTo == RebaseOptions.StdRebasing,
            "Invalid rebaseState to"
        );

        if (alternativeCreditsPerToken[_from] == 0) {
            _rebaseOptOut(_from);
        }
        if (alternativeCreditsPerToken[_to] > 0) {
            _rebaseOptIn(_to);
        }

        uint256 fromBalance = balanceOf(_from);
        uint256 toBalance = balanceOf(_to);
        uint256 oldToCredits = creditBalances[_to];
        uint256 newToCredits = _balanceToRebasingCredits(
            fromBalance + toBalance
        );

        // Set up the bidirectional links
        yieldTo[_from] = _to;
        yieldFrom[_to] = _from;

        // Local
        rebaseState[_from] = RebaseOptions.YieldDelegationSource;
        alternativeCreditsPerToken[_from] = 1e18;
        creditBalances[_from] = fromBalance;
        rebaseState[_to] = RebaseOptions.YieldDelegationTarget;
        creditBalances[_to] = newToCredits;

        // Global
        int256 creditsChange = newToCredits.toInt256() -
            oldToCredits.toInt256();
        _adjustGlobals(creditsChange, -(fromBalance).toInt256());
        emit YieldDelegated(_from, _to);
    }

    /*
     * @notice Stop sending the yield from one account to another account.
     */
    function undelegateYield(address _from) external onlyGovernor {
        // Require a delegation, which will also ensure a valid delegation
        require(yieldTo[_from] != address(0), "Zero address not allowed");

        address to = yieldTo[_from];
        uint256 fromBalance = balanceOf(_from);
        uint256 toBalance = balanceOf(to);
        uint256 oldToCredits = creditBalances[to];
        uint256 newToCredits = _balanceToRebasingCredits(toBalance);

        // Remove the bidirectional links
        yieldFrom[to] = address(0);
        yieldTo[_from] = address(0);

        // Local
        rebaseState[_from] = RebaseOptions.StdNonRebasing;
        // alternativeCreditsPerToken[from] already 1e18 from `delegateYield()`
        creditBalances[_from] = fromBalance;
        rebaseState[to] = RebaseOptions.StdRebasing;
        // alternativeCreditsPerToken[to] already 0 from `delegateYield()`
        creditBalances[to] = newToCredits;

        // Global
        int256 creditsChange = newToCredits.toInt256() -
            oldToCredits.toInt256();
        _adjustGlobals(creditsChange, fromBalance.toInt256());
        emit YieldUndelegated(_from, to);
    }
}
Helpers.sol 34 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import { IBasicToken } from "../interfaces/IBasicToken.sol";

library Helpers {
    /**
     * @notice Fetch the `symbol()` from an ERC20 token
     * @dev Grabs the `symbol()` from a contract
     * @param _token Address of the ERC20 token
     * @return string Symbol of the ERC20 token
     */
    function getSymbol(address _token) internal view returns (string memory) {
        string memory symbol = IBasicToken(_token).symbol();
        return symbol;
    }

    /**
     * @notice Fetch the `decimals()` from an ERC20 token
     * @dev Grabs the `decimals()` from a contract and fails if
     *      the decimal value does not live within a certain range
     * @param _token Address of the ERC20 token
     * @return uint256 Decimals of the ERC20 token
     */
    function getDecimals(address _token) internal view returns (uint256) {
        uint256 decimals = IBasicToken(_token).decimals();
        require(
            decimals >= 4 && decimals <= 18,
            "Token must have sufficient decimal places"
        );

        return decimals;
    }
}
Initializable.sol 42 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Base contract any contracts that need to initialize state after deployment.
 * @author Origin Protocol Inc
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private initialized;

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

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        require(
            initializing || !initialized,
            "Initializable: contract is already initialized"
        );

        bool isTopLevelCall = !initializing;
        if (isTopLevelCall) {
            initializing = true;
            initialized = true;
        }

        _;

        if (isTopLevelCall) {
            initializing = false;
        }
    }

    uint256[50] private ______gap;
}
InitializableAbstractStrategy.sol 352 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Base contract for vault strategies.
 * @author Origin Protocol Inc
 */
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { Initializable } from "../utils/Initializable.sol";
import { Governable } from "../governance/Governable.sol";
import { IVault } from "../interfaces/IVault.sol";

abstract contract InitializableAbstractStrategy is Initializable, Governable {
    using SafeERC20 for IERC20;

    event PTokenAdded(address indexed _asset, address _pToken);
    event PTokenRemoved(address indexed _asset, address _pToken);
    event Deposit(address indexed _asset, address _pToken, uint256 _amount);
    event Withdrawal(address indexed _asset, address _pToken, uint256 _amount);
    event RewardTokenCollected(
        address recipient,
        address rewardToken,
        uint256 amount
    );
    event RewardTokenAddressesUpdated(
        address[] _oldAddresses,
        address[] _newAddresses
    );
    event HarvesterAddressesUpdated(
        address _oldHarvesterAddress,
        address _newHarvesterAddress
    );

    /// @notice Address of the underlying platform
    address public immutable platformAddress;
    /// @notice Address of the OToken vault
    address public immutable vaultAddress;

    /// @dev Replaced with an immutable variable
    // slither-disable-next-line constable-states
    address private _deprecated_platformAddress;

    /// @dev Replaced with an immutable
    // slither-disable-next-line constable-states
    address private _deprecated_vaultAddress;

    /// @notice asset => pToken (Platform Specific Token Address)
    mapping(address => address) public assetToPToken;

    /// @notice Full list of all assets supported by the strategy
    address[] internal assetsMapped;

    // Deprecated: Reward token address
    // slither-disable-next-line constable-states
    address private _deprecated_rewardTokenAddress;

    // Deprecated: now resides in Harvester's rewardTokenConfigs
    // slither-disable-next-line constable-states
    uint256 private _deprecated_rewardLiquidationThreshold;

    /// @notice Address of the Harvester contract allowed to collect reward tokens
    address public harvesterAddress;

    /// @notice Address of the reward tokens. eg CRV, BAL, CVX, AURA
    address[] public rewardTokenAddresses;

    /* Reserved for future expansion. Used to be 100 storage slots
     * and has decreased to accommodate:
     * - harvesterAddress
     * - rewardTokenAddresses
     */
    int256[98] private _reserved;

    struct BaseStrategyConfig {
        address platformAddress; // Address of the underlying platform
        address vaultAddress; // Address of the OToken's Vault
    }

    /**
     * @param _config The platform and OToken vault addresses
     */
    constructor(BaseStrategyConfig memory _config) {
        platformAddress = _config.platformAddress;
        vaultAddress = _config.vaultAddress;
    }

    /**
     * @dev Internal initialize function, to set up initial internal state
     * @param _rewardTokenAddresses Address of reward token for platform
     * @param _assets Addresses of initial supported assets
     * @param _pTokens Platform Token corresponding addresses
     */
    function _initialize(
        address[] memory _rewardTokenAddresses,
        address[] memory _assets,
        address[] memory _pTokens
    ) internal {
        rewardTokenAddresses = _rewardTokenAddresses;

        uint256 assetCount = _assets.length;
        require(assetCount == _pTokens.length, "Invalid input arrays");
        for (uint256 i = 0; i < assetCount; ++i) {
            _setPTokenAddress(_assets[i], _pTokens[i]);
        }
    }

    /**
     * @notice Collect accumulated reward token and send to Vault.
     */
    function collectRewardTokens() external virtual onlyHarvester nonReentrant {
        _collectRewardTokens();
    }

    /**
     * @dev Default implementation that transfers reward tokens to the Harvester
     * Implementing strategies need to add custom logic to collect the rewards.
     */
    function _collectRewardTokens() internal virtual {
        uint256 rewardTokenCount = rewardTokenAddresses.length;
        for (uint256 i = 0; i < rewardTokenCount; ++i) {
            IERC20 rewardToken = IERC20(rewardTokenAddresses[i]);
            uint256 balance = rewardToken.balanceOf(address(this));
            if (balance > 0) {
                emit RewardTokenCollected(
                    harvesterAddress,
                    address(rewardToken),
                    balance
                );
                rewardToken.safeTransfer(harvesterAddress, balance);
            }
        }
    }

    /**
     * @dev Verifies that the caller is the Vault.
     */
    modifier onlyVault() {
        require(msg.sender == vaultAddress, "Caller is not the Vault");
        _;
    }

    /**
     * @dev Verifies that the caller is the Harvester.
     */
    modifier onlyHarvester() {
        require(msg.sender == harvesterAddress, "Caller is not the Harvester");
        _;
    }

    /**
     * @dev Verifies that the caller is the Vault or Governor.
     */
    modifier onlyVaultOrGovernor() {
        require(
            msg.sender == vaultAddress || msg.sender == governor(),
            "Caller is not the Vault or Governor"
        );
        _;
    }

    /**
     * @dev Verifies that the caller is the Vault, Governor, or Strategist.
     */
    modifier onlyVaultOrGovernorOrStrategist() {
        require(
            msg.sender == vaultAddress ||
                msg.sender == governor() ||
                msg.sender == IVault(vaultAddress).strategistAddr(),
            "Caller is not the Vault, Governor, or Strategist"
        );
        _;
    }

    /**
     * @notice Set the reward token addresses. Any old addresses will be overwritten.
     * @param _rewardTokenAddresses Array of reward token addresses
     */
    function setRewardTokenAddresses(address[] calldata _rewardTokenAddresses)
        external
        onlyGovernor
    {
        uint256 rewardTokenCount = _rewardTokenAddresses.length;
        for (uint256 i = 0; i < rewardTokenCount; ++i) {
            require(
                _rewardTokenAddresses[i] != address(0),
                "Can not set an empty address as a reward token"
            );
        }

        emit RewardTokenAddressesUpdated(
            rewardTokenAddresses,
            _rewardTokenAddresses
        );
        rewardTokenAddresses = _rewardTokenAddresses;
    }

    /**
     * @notice Get the reward token addresses.
     * @return address[] the reward token addresses.
     */
    function getRewardTokenAddresses()
        external
        view
        returns (address[] memory)
    {
        return rewardTokenAddresses;
    }

    /**
     * @notice Provide support for asset by passing its pToken address.
     *      This method can only be called by the system Governor
     * @param _asset    Address for the asset
     * @param _pToken   Address for the corresponding platform token
     */
    function setPTokenAddress(address _asset, address _pToken)
        external
        virtual
        onlyGovernor
    {
        _setPTokenAddress(_asset, _pToken);
    }

    /**
     * @notice Remove a supported asset by passing its index.
     *      This method can only be called by the system Governor
     * @param _assetIndex Index of the asset to be removed
     */
    function removePToken(uint256 _assetIndex) external virtual onlyGovernor {
        require(_assetIndex < assetsMapped.length, "Invalid index");
        address asset = assetsMapped[_assetIndex];
        address pToken = assetToPToken[asset];

        if (_assetIndex < assetsMapped.length - 1) {
            assetsMapped[_assetIndex] = assetsMapped[assetsMapped.length - 1];
        }
        assetsMapped.pop();
        assetToPToken[asset] = address(0);

        emit PTokenRemoved(asset, pToken);
    }

    /**
     * @notice Provide support for asset by passing its pToken address.
     *      Add to internal mappings and execute the platform specific,
     * abstract method `_abstractSetPToken`
     * @param _asset    Address for the asset
     * @param _pToken   Address for the corresponding platform token
     */
    function _setPTokenAddress(address _asset, address _pToken) internal {
        require(assetToPToken[_asset] == address(0), "pToken already set");
        require(
            _asset != address(0) && _pToken != address(0),
            "Invalid addresses"
        );

        assetToPToken[_asset] = _pToken;
        assetsMapped.push(_asset);

        emit PTokenAdded(_asset, _pToken);

        _abstractSetPToken(_asset, _pToken);
    }

    /**
     * @notice Transfer token to governor. Intended for recovering tokens stuck in
     *      strategy contracts, i.e. mistaken sends.
     * @param _asset Address for the asset
     * @param _amount Amount of the asset to transfer
     */
    function transferToken(address _asset, uint256 _amount)
        public
        virtual
        onlyGovernor
    {
        require(!supportsAsset(_asset), "Cannot transfer supported asset");
        IERC20(_asset).safeTransfer(governor(), _amount);
    }

    /**
     * @notice Set the Harvester contract that can collect rewards.
     * @param _harvesterAddress Address of the harvester contract.
     */
    function setHarvesterAddress(address _harvesterAddress)
        external
        onlyGovernor
    {
        emit HarvesterAddressesUpdated(harvesterAddress, _harvesterAddress);
        harvesterAddress = _harvesterAddress;
    }

    /***************************************
                 Abstract
    ****************************************/

    function _abstractSetPToken(address _asset, address _pToken)
        internal
        virtual;

    function safeApproveAllTokens() external virtual;

    /**
     * @notice Deposit an amount of assets into the platform
     * @param _asset               Address for the asset
     * @param _amount              Units of asset to deposit
     */
    function deposit(address _asset, uint256 _amount) external virtual;

    /**
     * @notice Deposit all supported assets in this strategy contract to the platform
     */
    function depositAll() external virtual;

    /**
     * @notice Withdraw an `amount` of assets from the platform and
     * send to the `_recipient`.
     * @param _recipient         Address to which the asset should be sent
     * @param _asset             Address of the asset
     * @param _amount            Units of asset to withdraw
     */
    function withdraw(
        address _recipient,
        address _asset,
        uint256 _amount
    ) external virtual;

    /**
     * @notice Withdraw all supported assets from platform and
     * sends to the OToken's Vault.
     */
    function withdrawAll() external virtual;

    /**
     * @notice Get the total asset value held in the platform.
     *      This includes any interest that was generated since depositing.
     * @param _asset      Address of the asset
     * @return balance    Total value of the asset in the platform
     */
    function checkBalance(address _asset)
        external
        view
        virtual
        returns (uint256 balance);

    /**
     * @notice Check if an asset is supported.
     * @param _asset    Address of the asset
     * @return bool     Whether asset is supported
     */
    function supportsAsset(address _asset) public view virtual returns (bool);
}
VaultStorage.sol 274 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title OToken VaultStorage contract
 * @notice The VaultStorage contract defines the storage for the Vault contracts
 * @author Origin Protocol Inc
 */

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

import { IStrategy } from "../interfaces/IStrategy.sol";
import { Governable } from "../governance/Governable.sol";
import { OUSD } from "../token/OUSD.sol";
import { Initializable } from "../utils/Initializable.sol";
import "../utils/Helpers.sol";

contract VaultStorage is Initializable, Governable {
    using SafeERC20 for IERC20;

    event AssetSupported(address _asset);
    event AssetRemoved(address _asset);
    event AssetDefaultStrategyUpdated(address _asset, address _strategy);
    event AssetAllocated(address _asset, address _strategy, uint256 _amount);
    event StrategyApproved(address _addr);
    event StrategyRemoved(address _addr);
    event Mint(address _addr, uint256 _value);
    event Redeem(address _addr, uint256 _value);
    event CapitalPaused();
    event CapitalUnpaused();
    event RebasePaused();
    event RebaseUnpaused();
    event VaultBufferUpdated(uint256 _vaultBuffer);
    event OusdMetaStrategyUpdated(address _ousdMetaStrategy);
    event RedeemFeeUpdated(uint256 _redeemFeeBps);
    event PriceProviderUpdated(address _priceProvider);
    event AllocateThresholdUpdated(uint256 _threshold);
    event RebaseThresholdUpdated(uint256 _threshold);
    event StrategistUpdated(address _address);
    event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
    event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
    event TrusteeFeeBpsChanged(uint256 _basis);
    event TrusteeAddressChanged(address _address);
    event NetOusdMintForStrategyThresholdChanged(uint256 _threshold);
    event SwapperChanged(address _address);
    event SwapAllowedUndervalueChanged(uint256 _basis);
    event SwapSlippageChanged(address _asset, uint256 _basis);
    event Swapped(
        address indexed _fromAsset,
        address indexed _toAsset,
        uint256 _fromAssetAmount,
        uint256 _toAssetAmount
    );
    event StrategyAddedToMintWhitelist(address indexed strategy);
    event StrategyRemovedFromMintWhitelist(address indexed strategy);
    event DripperChanged(address indexed _dripper);
    event RebasePerSecondMaxChanged(uint256 rebaseRatePerSecond);
    event DripDurationChanged(uint256 dripDuration);
    event WithdrawalRequested(
        address indexed _withdrawer,
        uint256 indexed _requestId,
        uint256 _amount,
        uint256 _queued
    );
    event WithdrawalClaimed(
        address indexed _withdrawer,
        uint256 indexed _requestId,
        uint256 _amount
    );
    event WithdrawalClaimable(uint256 _claimable, uint256 _newClaimable);
    event WithdrawalClaimDelayUpdated(uint256 _newDelay);

    // Since we are proxy, all state should be uninitalized.
    // Since this storage contract does not have logic directly on it
    // we should not be checking for to see if these variables can be constant.
    // slither-disable-start uninitialized-state
    // slither-disable-start constable-states

    // Assets supported by the Vault, i.e. Stablecoins
    enum UnitConversion {
        DECIMALS,
        GETEXCHANGERATE
    }
    // Changed to fit into a single storage slot so the decimals needs to be recached
    struct Asset {
        // Note: OETHVaultCore doesn't use `isSupported` when minting,
        // redeeming or checking balance of assets.
        bool isSupported;
        UnitConversion unitConversion;
        uint8 decimals;
        // Max allowed slippage from the Oracle price when swapping collateral assets in basis points.
        // For example 40 == 0.4% slippage
        uint16 allowedOracleSlippageBps;
    }

    /// @dev mapping of supported vault assets to their configuration
    mapping(address => Asset) internal assets;
    /// @dev list of all assets supported by the vault.
    address[] internal allAssets;

    // Strategies approved for use by the Vault
    struct Strategy {
        bool isSupported;
        uint256 _deprecated; // Deprecated storage slot
    }
    /// @dev mapping of strategy contracts to their configuration
    mapping(address => Strategy) public strategies;
    /// @dev list of all vault strategies
    address[] internal allStrategies;

    /// @notice Address of the Oracle price provider contract
    address public priceProvider;
    /// @notice pause rebasing if true
    bool public rebasePaused;
    /// @notice pause operations that change the OToken supply.
    /// eg mint, redeem, allocate, mint/burn for strategy
    bool public capitalPaused;
    /// @notice Redemption fee in basis points. eg 50 = 0.5%
    uint256 public redeemFeeBps;
    /// @notice Percentage of assets to keep in Vault to handle (most) withdrawals. 100% = 1e18.
    uint256 public vaultBuffer;
    /// @notice OToken mints over this amount automatically allocate funds. 18 decimals.
    uint256 public autoAllocateThreshold;
    /// @notice OToken mints over this amount automatically rebase. 18 decimals.
    uint256 public rebaseThreshold;

    /// @dev Address of the OToken token. eg OUSD or OETH.
    OUSD public oUSD;

    /// @dev Storage slot for the address of the VaultAdmin contract that is delegated to
    // keccak256("OUSD.vault.governor.admin.impl");
    bytes32 public constant adminImplPosition =
        0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;

    /// @dev Address of the contract responsible for post rebase syncs with AMMs
    address private _deprecated_rebaseHooksAddr = address(0);

    /// @dev Deprecated: Address of Uniswap
    address private _deprecated_uniswapAddr = address(0);

    /// @notice Address of the Strategist
    address public strategistAddr = address(0);

    /// @notice Mapping of asset address to the Strategy that they should automatically
    // be allocated to
    mapping(address => address) public assetDefaultStrategies;

    /// @notice Max difference between total supply and total value of assets. 18 decimals.
    uint256 public maxSupplyDiff;

    /// @notice Trustee contract that can collect a percentage of yield
    address public trusteeAddress;

    /// @notice Amount of yield collected in basis points. eg 2000 = 20%
    uint256 public trusteeFeeBps;

    /// @dev Deprecated: Tokens that should be swapped for stablecoins
    address[] private _deprecated_swapTokens;

    uint256 constant MINT_MINIMUM_UNIT_PRICE = 0.998e18;

    /// @notice Metapool strategy that is allowed to mint/burn OTokens without changing collateral

    address public ousdMetaStrategy;

    /// @notice How much OTokens are currently minted by the strategy
    int256 public netOusdMintedForStrategy;

    /// @notice How much net total OTokens are allowed to be minted by all strategies
    uint256 public netOusdMintForStrategyThreshold;

    uint256 constant MIN_UNIT_PRICE_DRIFT = 0.7e18;
    uint256 constant MAX_UNIT_PRICE_DRIFT = 1.3e18;

    /// @notice Collateral swap configuration.
    /// @dev is packed into a single storage slot to save gas.
    struct SwapConfig {
        // Contract that swaps the vault's collateral assets
        address swapper;
        // Max allowed percentage the total value can drop below the total supply in basis points.
        // For example 100 == 1%
        uint16 allowedUndervalueBps;
    }
    SwapConfig internal swapConfig = SwapConfig(address(0), 0);

    // List of strategies that can mint oTokens directly
    // Used in OETHBaseVaultCore
    mapping(address => bool) public isMintWhitelistedStrategy;

    /// @notice Address of the Dripper contract that streams harvested rewards to the Vault
    /// @dev The vault is proxied so needs to be set with setDripper against the proxy contract.
    address public dripper;

    /// Withdrawal Queue Storage /////

    struct WithdrawalQueueMetadata {
        // cumulative total of all withdrawal requests included the ones that have already been claimed
        uint128 queued;
        // cumulative total of all the requests that can be claimed including the ones that have already been claimed
        uint128 claimable;
        // total of all the requests that have been claimed
        uint128 claimed;
        // index of the next withdrawal request starting at 0
        uint128 nextWithdrawalIndex;
    }

    /// @notice Global metadata for the withdrawal queue including:
    /// queued - cumulative total of all withdrawal requests included the ones that have already been claimed
    /// claimable - cumulative total of all the requests that can be claimed including the ones already claimed
    /// claimed - total of all the requests that have been claimed
    /// nextWithdrawalIndex - index of the next withdrawal request starting at 0
    WithdrawalQueueMetadata public withdrawalQueueMetadata;

    struct WithdrawalRequest {
        address withdrawer;
        bool claimed;
        uint40 timestamp; // timestamp of the withdrawal request
        // Amount of oTokens to redeem. eg OETH
        uint128 amount;
        // cumulative total of all withdrawal requests including this one.
        // this request can be claimed when this queued amount is less than or equal to the queue's claimable amount.
        uint128 queued;
    }

    /// @notice Mapping of withdrawal request indices to the user withdrawal request data
    mapping(uint256 => WithdrawalRequest) public withdrawalRequests;

    /// @notice Sets a minimum delay that is required to elapse between
    ///     requesting async withdrawals and claiming the request.
    ///     When set to 0 async withdrawals are disabled.
    uint256 public withdrawalClaimDelay;

    /// @notice Time in seconds that the vault last rebased yield.
    uint64 public lastRebase;

    /// @notice Automatic rebase yield calculations. In seconds. Set to 0 or 1 to disable.
    uint64 public dripDuration;

    /// @notice max rebase percentage per second
    ///   Can be used to set maximum yield of the protocol,
    ///   spreading out yield over time
    uint64 public rebasePerSecondMax;

    /// @notice target rebase rate limit, based on past rates and funds available.
    uint64 public rebasePerSecondTarget;

    uint256 internal constant MAX_REBASE = 0.02 ether;
    uint256 internal constant MAX_REBASE_PER_SECOND =
        uint256(0.05 ether) / 1 days;

    // For future use
    uint256[43] private __gap;

    // slither-disable-end constable-states
    // slither-disable-end uninitialized-state

    /**
     * @notice set the implementation for the admin, this needs to be in a base class else we cannot set it
     * @param newImpl address of the implementation
     */
    function setAdminImpl(address newImpl) external onlyGovernor {
        require(
            Address.isContract(newImpl),
            "new implementation is not a contract"
        );
        bytes32 position = adminImplPosition;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(position, newImpl)
        }
    }
}

Read Contract

BEACON_CHAIN_DEPOSIT_CONTRACT 0xcceab750 → address
FEE_ACCUMULATOR_ADDRESS 0xdd505df6 → address
FULL_STAKE 0xb16b7d0b → uint256
MAX_VALIDATORS 0x714897df → uint256
MIN_FIX_ACCOUNTING_CADENCE 0x63092383 → uint256
SSV_NETWORK 0x91649751 → address
SSV_TOKEN 0x0df1ecfd → address
VAULT_ADDRESS 0x9092c31c → address
WETH 0xad5c4648 → address
activeDepositedValidators 0x66e3667e → uint256
assetToPToken 0x0fc3b4c4 → address
checkBalance 0x5f515226 → uint256
consensusRewards 0x842f5c46 → uint256
depositedWethAccountedFor 0xd059f6ef → uint256
fuseIntervalEnd 0x484be812 → uint256
fuseIntervalStart 0x3c864959 → uint256
getRewardTokenAddresses 0xf6ca71b0 → address[]
governor 0x0c340a24 → address
harvesterAddress 0x67c7066c → address
isGovernor 0xc7af3352 → bool
lastFixAccountingBlockNumber 0xe7529239 → uint256
paused 0x5c975abb → bool
platformAddress 0xdbe55e56 → address
rewardTokenAddresses 0x7b2d9b2c → address
stakeETHTally 0xde34d713 → uint256
stakeETHThreshold 0x7b8962f7 → uint256
stakingMonitor 0x7260f826 → address
supportsAsset 0xaa388af6 → bool
validatorRegistrator 0x87bae867 → address
validatorsStates 0x9da0e462 → uint8
vaultAddress 0x430bf08a → address

Write Contract 29 functions

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

claimGovernance 0x5d36b190
No parameters
collectRewardTokens 0x5a063f63
No parameters
deposit 0x47e7ef24
address _asset
uint256 _amount
depositAll 0xde5f6268
No parameters
depositSSV 0xd8f9b3a1
uint64[] operatorIds
uint256 ssvAmount
tuple cluster
doAccounting 0xa4f98af4
No parameters
returns: bool
exitSsvValidator 0xd9f00ec7
bytes publicKey
uint64[] operatorIds
initialize 0x435356d1
address[] _rewardTokenAddresses
address[] _assets
address[] _pTokens
manuallyFixAccounting 0x8d7c0e46
int256 _validatorsDelta
int256 _consensusRewardsDelta
uint256 _ethToVaultAmount
pause 0x8456cb59
No parameters
registerSsvValidators 0x637b20ba
bytes[] publicKeys
uint64[] operatorIds
bytes[] sharesData
uint256 ssvAmount
tuple cluster
removePToken 0x9136616a
uint256 _assetIndex
removeSsvValidator 0x03ce812b
bytes publicKey
uint64[] operatorIds
tuple cluster
resetStakeETHTally 0xee7afe2d
No parameters
safeApproveAllTokens 0xad1728cb
No parameters
setFeeRecipient 0x13cf69dd
No parameters
setFuseInterval 0xab12edf5
uint256 _fuseIntervalStart
uint256 _fuseIntervalEnd
setHarvesterAddress 0xc2e1e3f4
address _harvesterAddress
setPTokenAddress 0x0ed57b3a
address _asset
address _pToken
setRegistrator 0x6e811d38
address _address
setRewardTokenAddresses 0x96d538bb
address[] _rewardTokenAddresses
setStakeETHThreshold 0x5205c380
uint256 _amount
setStakingMonitor 0xa3b81e73
address _address
stakeEth 0x24ee9c39
tuple[] validators
transferGovernance 0xd38bfff4
address _newGovernor
transferToken 0x1072cbea
address _asset
uint256 _amount
withdraw 0xd9caed12
address _recipient
address _asset
uint256 _amount
withdrawAll 0x853828b6
No parameters
withdrawSSV 0xc93ce1af
uint64[] operatorIds
uint256 ssvAmount
tuple cluster

Recent Transactions

No transactions found for this address