Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xD01aDA994bc08ded72e12812818a35320b0F1cb2
Balance 0 ETH
Nonce 1
Code Size 20978 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

20978 bytes
0x608060405234801561001057600080fd5b50600436106102485760003560e01c806367c7066c1161013b578063b60ce400116100b8578063dbe55e561161007c578063dbe55e5614610608578063de5f62681461062f578063e033193a14610637578063e70940d11461064a578063f6ca71b01461067157600080fd5b8063b60ce400146105a0578063c2e1e3f4146105c7578063c7af3352146105da578063d38bfff4146105e2578063d9caed12146105f557600080fd5b80639642913c116100ff5780639642913c146104e757806396d538bb1461050e578063a6f19c8414610521578063aa388af614610548578063ad1728cb1461059857600080fd5b806367c7066c1461049d5780637b2d9b2c146104b0578063853828b6146104c35780638c04166f146104cb5780639136616a146104d457600080fd5b8063430bf08a116101c95780635d36b1901161018d5780635d36b1901461040f5780635f515226146104175780635fcbd2851461042a57806360b5bb3f1461045157806365a217c61461046457600080fd5b8063430bf08a1461037b57806343f68a49146103a257806347de4b7d146103b557806347e7ef24146103f45780635a063f631461040757600080fd5b80631072cbea116102105780631072cbea146102ea5780631a32aad6146102fd5780631b91d0cc14610324578063218751b214610341578063371450381461036857600080fd5b8063012c63831461024d57806307546172146102625780630c340a24146102a65780630ed57b3a146102ae5780630fc3b4c4146102c1575b600080fd5b61026061025b3660046149bc565b610686565b005b6102897f000000000000000000000000d061d61a4d941c39e5453435b6345dc261c2fce081565b6040516001600160a01b0390911681526020015b60405180910390f35b610289610cf0565b6102606102bc3660046149ea565b610d0d565b6102896102cf366004614a23565b6035602052600090815260409020546001600160a01b031681565b6102606102f8366004614a40565b610d3f565b6102897f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc381565b610333670dd99bb65dd7000081565b60405190815260200161029d565b6102897f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a881565b6102606103763660046149bc565b610dfa565b6102897f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab81565b6102606103b03660046149bc565b611434565b6103dc7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160801b03909116815260200161029d565b610260610402366004614a40565b611464565b6102606114f5565b6102606116a2565b610333610425366004614a23565b611748565b6102897f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a881565b61026061045f366004614ab8565b6119e1565b61048b7f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff909116815260200161029d565b603954610289906001600160a01b031681565b6102896104be3660046149bc565b611bf5565b610260611c1f565b610333609d5481565b6102606104e23660046149bc565b6121c4565b6102897f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b61026061051c366004614b04565b61238f565b6102897f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f81565b610588610556366004614a23565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0390811691161490565b604051901515815260200161029d565b6102606124a6565b6103dc7f000000000000000000000000000000000000000000000000000000000000000181565b6102606105d5366004614a23565b612508565b610588612595565b6102606105f0366004614a23565b6125c6565b610260610603366004614b46565b61266a565b6102897f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a881565b610260612b31565b6102606106453660046149bc565b612c74565b61048b7f000000000000000000000000000000000000000000000000000000000000001281565b610679612fd5565b60405161029d9190614b87565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107089190614bd3565b6001600160a01b0316336001600160a01b0316146107415760405162461bcd60e51b815260040161073890614bf0565b60405180910390fd5b60008051602061515d833981519152805460011981016107735760405162461bcd60e51b815260040161073890614c27565b6002825560007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa1580156107d7573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526107ff9190810190614c65565b9050600061084e827f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061084157610841614d32565b6020026020010151613037565b6108f36108ee7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16867f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106108d7576108d7614d32565b60200260200101516130a59092919063ffffffff16565b613037565b6108fd9190614d5e565b9050600061092b867f0000000000000000000000000000000000000000000000000000000000000001613109565b90506109816001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2167f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab836132fa565b610989613355565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8836040516109f2929190614d85565b60405180910390a25060007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa158015610a5b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610a839190810190614c65565b90506000610ac5827f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061084157610841614d32565b610b4e6108ee7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16867f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106108d7576108d7614d32565b610b589190614d5e565b905082600003610bb5578015610bb05760405162461bcd60e51b815260206004820152601c60248201527f506f736974696f6e2062616c616e636520697320776f7273656e6564000000006044820152606401610738565b610ce3565b6000831215610c4d576000811315610c065760405162461bcd60e51b81526020600482015260146024820152734f546f6b656e73206f76657273686f742070656760601b6044820152606401610738565b808312610bb05760405162461bcd60e51b81526020600482015260156024820152744f546f6b656e732062616c616e636520776f72736560581b6044820152606401610738565b6000831315610ce3576000811215610c9d5760405162461bcd60e51b8152602060048201526013602482015272417373657473206f76657273686f742070656760681b6044820152606401610738565b828112610ce35760405162461bcd60e51b81526020600482015260146024820152734173736574732062616c616e636520776f72736560601b6044820152606401610738565b5050505060018255505050565b6000610d0860008051602061517d8339815191525490565b905090565b610d15612595565b610d315760405162461bcd60e51b815260040161073890614d9e565b610d3b82826134b7565b5050565b610d47612595565b610d635760405162461bcd60e51b815260040161073890614d9e565b6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811690831603610dde5760405162461bcd60e51b815260206004820152601f60248201527f43616e6e6f74207472616e7366657220737570706f72746564206173736574006044820152606401610738565b610d3b610de9610cf0565b6001600160a01b03841690836132fa565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e7c9190614bd3565b6001600160a01b0316336001600160a01b031614610eac5760405162461bcd60e51b815260040161073890614bf0565b60008051602061515d83398151915280546001198101610ede5760405162461bcd60e51b815260040161073890614c27565b6002825560007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa158015610f42573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610f6a9190810190614c65565b90506000610fac827f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061084157610841614d32565b6110356108ee7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16867f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106108d7576108d7614d32565b61103f9190614d5e565b60405163ab80dafb60e01b8152600481018790529091507f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b03169063ab80dafb90602401600060405180830381600087803b1580156110a457600080fd5b505af11580156110b8573d6000803e3d6000fd5b5060009250600291506110c89050565b6040519080825280602002602001820160405280156110f1578160200160208202803683370190505b50905085817f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061113057611130614d32565b60200260200101818152505060006111ca7f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa15801561119f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111c39190614dd5565b8890613616565b905060006111ee609d54670de0b6b3a76400006111e79190614dee565b8390613641565b905060007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663b72df5de85846040518363ffffffff1660e01b8152600401611240929190614e3d565b6020604051808303816000875af115801561125f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112839190614dd5565b9050818110156112cb5760405162461bcd60e51b815260206004820152601360248201527226b4b71026281030b6b7bab73a1032b93937b960691b6044820152606401610738565b60405163b6b55f2560e01b8152600481018290527f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b03169063b6b55f2590602401600060405180830381600087803b15801561132d57600080fd5b505af1158015611341573d6000803e3d6000fd5b5050505061134d613355565b7f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b03167f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f627f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a88b6040516113c8929190614d85565b60405180910390a25050505060007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa158015610a5b573d6000803e3d6000fd5b61143c612595565b6114585760405162461bcd60e51b815260040161073890614d9e565b61146181613656565b50565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab16146114ac5760405162461bcd60e51b815260040161073890614e5f565b60008051602061515d833981519152805460011981016114de5760405162461bcd60e51b815260040161073890614c27565b600282556114ec84846136e8565b50600190555050565b6039546001600160a01b0316331461154f5760405162461bcd60e51b815260206004820152601b60248201527f43616c6c6572206973206e6f74207468652048617276657374657200000000006044820152606401610738565b60008051602061515d833981519152805460011981016115815760405162461bcd60e51b815260040161073890614c27565b600282556040516335313c2160e11b81526001600160a01b037f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f811660048301527f000000000000000000000000d061d61a4d941c39e5453435b6345dc261c2fce01690636a62784290602401600060405180830381600087803b15801561160857600080fd5b505af115801561161c573d6000803e3d6000fd5b505050507f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b031663e6f1daf26040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561167b57600080fd5b505af115801561168f573d6000803e3d6000fd5b5050505061169b613dc9565b5060019055565b7f44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db546001600160a01b0316336001600160a01b03161461173d5760405162461bcd60e51b815260206004820152603060248201527f4f6e6c79207468652070656e64696e6720476f7665726e6f722063616e20636f60448201526f6d706c6574652074686520636c61696d60801b6064820152608401610738565b61174633613edd565b565b60007f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316826001600160a01b0316146117bf5760405162461bcd60e51b8152602060048201526011602482015270155b9cdd5c1c1bdc9d195908185cdcd95d607a1b6044820152606401610738565b6040516370a0823160e01b81523060048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa158015611823573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118479190614dd5565b6040516370a0823160e01b81523060048201529091506000906001600160a01b037f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f16906370a0823190602401602060405180830381865afa1580156118b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d59190614dd5565b905080156119db576119ce7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16670de0b6b3a76400007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa15801561198f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119b39190614dd5565b6119bd9086614e96565b6119c79190614ead565b91906130a5565b6119d89083614ecf565b91505b50919050565b6119e9612595565b611a055760405162461bcd60e51b815260040161073890614d9e565b600054610100900460ff1680611a1e575060005460ff16155b611a815760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610738565b600054610100900460ff16158015611aa3576000805461ffff19166101011790555b604080516001808252818301909252600091602080830190803683370190505090507f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a881600081518110611af957611af9614d32565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092526000918160200160208202803683370190505090507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281600081518110611b6a57611b6a614d32565b60200260200101906001600160a01b031690816001600160a01b031681525050611bca868680806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250859250869150613f3c9050565b611bd2613fef565b611bdb84613656565b50508015611bef576000805461ff00191690555b50505050565b603a8181548110611c0557600080fd5b6000918252602090912001546001600160a01b0316905081565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab161480611c6e5750611c59610cf0565b6001600160a01b0316336001600160a01b0316145b611cc65760405162461bcd60e51b815260206004820152602360248201527f43616c6c6572206973206e6f7420746865205661756c74206f7220476f7665726044820152623737b960e91b6064820152608401610738565b60008051602061515d83398151915280546001198101611cf85760405162461bcd60e51b815260040161073890614c27565b600282556040516370a0823160e01b81523060048201526000907f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b0316906370a0823190602401602060405180830381865afa158015611d63573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d879190614dd5565b9050611d92816141ac565b604080516002808252606082018352600092602083019080368337019050506040516370a0823160e01b81523060048201529091506000906001600160a01b037f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a816906370a0823190602401602060405180830381865afa158015611e1b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e3f9190614dd5565b90508015611ede5760405163350376e360e21b81526001600160a01b037f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8169063d40ddb8c90611e959084908690600401614ee2565b6000604051808303816000875af1158015611eb4573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611edc9190810190614c65565b505b6040516370a0823160e01b81523060048201526000907f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b0316906370a0823190602401602060405180830381865afa158015611f45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f699190614dd5565b60405163310bf9f560e11b8152600481018290529091507f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031690636217f3ea90602401600060405180830381600087803b158015611fce57600080fd5b505af1158015611fe2573d6000803e3d6000fd5b50506040516370a0823160e01b8152306004820152600092507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031691506370a0823190602401602060405180830381865afa15801561204d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120719190614dd5565b90506120c76001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2167f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab836132fa565b801561213f577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a883604051612136929190614d85565b60405180910390a25b81156121b7577f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8846040516121ae929190614d85565b60405180910390a25b5050505050600182555050565b6121cc612595565b6121e85760405162461bcd60e51b815260040161073890614d9e565b60365481106122295760405162461bcd60e51b815260206004820152600d60248201526c092dcecc2d8d2c840d2dcc8caf609b1b6044820152606401610738565b60006036828154811061223e5761223e614d32565b60009182526020808320909101546001600160a01b0390811680845260359092526040909220546036549193509091169061227b90600190614dee565b8310156122fd576036805461229290600190614dee565b815481106122a2576122a2614d32565b600091825260209091200154603680546001600160a01b0390921691859081106122ce576122ce614d32565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b031602179055505b603680548061230e5761230e614efb565b60008281526020808220600019908401810180546001600160a01b031990811690915593019093556001600160a01b038581168083526035855260409283902080549094169093559051908416815290917f16b7600acff27e39a8a96056b3d533045298de927507f5c1d97e4accde60488c910160405180910390a2505050565b612397612595565b6123b35760405162461bcd60e51b815260040161073890614d9e565b8060005b8181101561245d5760008484838181106123d3576123d3614d32565b90506020020160208101906123e89190614a23565b6001600160a01b0316036124555760405162461bcd60e51b815260206004820152602e60248201527f43616e206e6f742073657420616e20656d70747920616464726573732061732060448201526d30903932bbb0b932103a37b5b2b760911b6064820152608401610738565b6001016123b7565b507f04c0b9649497d316554306e53678d5f5f5dbc3a06f97dec13ff4cfe98b986bbc603a848460405161249293929190614f11565b60405180910390a1611bef603a84846148f3565b6124ae612595565b6124ca5760405162461bcd60e51b815260040161073890614d9e565b60008051602061515d833981519152805460011981016124fc5760405162461bcd60e51b815260040161073890614c27565b6002825561169b613fef565b612510612595565b61252c5760405162461bcd60e51b815260040161073890614d9e565b603954604080516001600160a01b03928316815291831660208301527fe48386b84419f4d36e0f96c10cc3510b6fb1a33795620c5098b22472bbe90796910160405180910390a1603980546001600160a01b0319166001600160a01b0392909216919091179055565b60006125ad60008051602061517d8339815191525490565b6001600160a01b0316336001600160a01b031614905090565b6125ce612595565b6125ea5760405162461bcd60e51b815260040161073890614d9e565b612612817f44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db55565b806001600160a01b031661263260008051602061517d8339815191525490565b6001600160a01b03167fa39cc5eb22d0f34d8beaefee8a3f17cc229c1a1d1ef87a5ad47313487b1c4f0d60405160405180910390a350565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab16146126b25760405162461bcd60e51b815260040161073890614e5f565b60008051602061515d833981519152805460011981016126e45760405162461bcd60e51b815260040161073890614c27565b60028255600083116127385760405162461bcd60e51b815260206004820152601760248201527f4d75737420776974686472617720736f6d657468696e670000000000000000006044820152606401610738565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316846001600160a01b0316146127b95760405162461bcd60e51b815260206004820152601c60248201527f43616e206f6e6c792077697468647261772068617264206173736574000000006044820152606401610738565b836001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a885604051612802929190614d85565b60405180910390a260006128656128608560ff7f00000000000000000000000000000000000000000000000000000000000000128116907f0000000000000000000000000000000000000000000000000000000000000012166130a5565b6142f3565b9050612870816141ac565b60408051600280825260608201835260009260208301908036833701905050905084817f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106128cd576128cd614d32565b602090810291909101015260405163350376e360e21b81526001600160a01b037f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8169063d40ddb8c906129269085908590600401614ee2565b6000604051808303816000875af1158015612945573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261296d9190810190614c65565b506040516370a0823160e01b81523060048201526000907f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b0316906370a0823190602401602060405180830381865afa1580156129d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129f99190614dd5565b60405163310bf9f560e11b8152600481018290529091507f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031690636217f3ea90602401600060405180830381600087803b158015612a5e57600080fd5b505af1158015612a72573d6000803e3d6000fd5b505050507f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a883604051612adf929190614d85565b60405180910390a2612b1b6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21689886132fa565b612b23613355565b505050600182555050505050565b336001600160a01b037f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab1614612b795760405162461bcd60e51b815260040161073890614e5f565b60008051602061515d83398151915280546001198101612bab5760405162461bcd60e51b815260040161073890614c27565b600282556040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a0823190602401602060405180830381865afa158015612c16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c3a9190614dd5565b90508015612c6c57612c6c7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2826136e8565b505060019055565b7f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663570d8e1d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612cd2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cf69190614bd3565b6001600160a01b0316336001600160a01b031614612d265760405162461bcd60e51b815260040161073890614bf0565b60008051602061515d83398151915280546001198101612d585760405162461bcd60e51b815260040161073890614c27565b6002825560007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa158015612dbc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612de49190810190614c65565b90506000612e26827f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061084157610841614d32565b612eaf6108ee7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16867f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106108d7576108d7614d32565b612eb99190614d5e565b90506000612ee7867f0000000000000000000000000000000000000000000000000000000000000000613109565b60405163310bf9f560e11b8152600481018290529091507f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031690636217f3ea90602401600060405180830381600087803b158015612f4c57600080fd5b505af1158015612f60573d6000803e3d6000fd5b50505050612f6c613355565b7f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b031660008051602061519d8339815191527f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8836040516109f2929190614d85565b6060603a80548060200260200160405190810160405280929190818152602001828054801561302d57602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831161300f575b5050505050905090565b60006001600160ff1b038211156130a15760405162461bcd60e51b815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604482015267371034b73a191a9b60c11b6064820152608401610738565b5090565b6000818311156130d5576130ce6130bc8385614dee565b6130c790600a615093565b85906144d7565b93506130ff565b818310156130ff576130fc6130ea8484614dee565b6130f590600a615093565b85906144e3565b93505b50825b9392505050565b6000613114836141ac565b60006131a27f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015613177573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061319b9190614dd5565b8590613641565b90507f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316836001600160801b0316036132315761322e8160ff7f00000000000000000000000000000000000000000000000000000000000000128116907f0000000000000000000000000000000000000000000000000000000000000012166130a5565b90505b600061324c609d54670de0b6b3a76400006111e79190614dee565b60405163081579a560e01b815260048101879052600f86900b6024820152604481018290523060648201529091507f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03169063081579a5906084016020604051808303816000875af11580156132cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132f19190614dd5565b95945050505050565b6133508363a9059cbb60e01b8484604051602401613319929190614d85565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526144ef565b505050565b60007f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b031663d4c3eea06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133d99190614dd5565b905060007f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561343b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061345f9190614dd5565b9050670dd99bb65dd700006134748383613616565b1015610d3b5760405162461bcd60e51b8152602060048201526012602482015271141c9bdd1bd8dbdb081a5b9cdbdb1d995b9d60721b6044820152606401610738565b6001600160a01b0382811660009081526035602052604090205416156135145760405162461bcd60e51b81526020600482015260126024820152711c151bdad95b88185b1c9958591e481cd95d60721b6044820152606401610738565b6001600160a01b0382161580159061353457506001600160a01b03811615155b6135745760405162461bcd60e51b8152602060048201526011602482015270496e76616c69642061646472657373657360781b6044820152606401610738565b6001600160a01b03828116600081815260356020908152604080832080549587166001600160a01b031996871681179091556036805460018101825594527f4a11f94e20a93c79f6ec743a1954ec4fc2c08429ae2122118bf234b2185c81b890930180549095168417909455925190815290917fef6485b84315f9b1483beffa32aae9a0596890395e3d7521f1c5fbb51790e765910160405180910390a25050565b60008061362b84670de0b6b3a76400006144d7565b905061363781846144e3565b9150505b92915050565b60006131028383670de0b6b3a76400006145c1565b66b1a2bc2ec500008111156136ad5760405162461bcd60e51b815260206004820152601f60248201527f536c697070616765206d757374206265206c657373207468616e2031303025006044820152606401610738565b609d8190556040518181527f9c922f6d0c990b250e9dd0a427a5c8da7f44b960f697fecb31cbbd8ba79ec8c29060200160405180910390a150565b600081116137315760405162461bcd60e51b81526020600482015260166024820152754d757374206465706f73697420736f6d657468696e6760501b6044820152606401610738565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316826001600160a01b0316146137a65760405162461bcd60e51b8152602060048201526011602482015270155b9cdd5c1c1bdc9d195908185cdcd95d607a1b6044820152606401610738565b816001600160a01b03167f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f627f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a883604051613801929190614d85565b60405180910390a2600061385c8260ff7f00000000000000000000000000000000000000000000000000000000000000128116907f0000000000000000000000000000000000000000000000000000000000000012166130a5565b905060007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166314f059796040518163ffffffff1660e01b8152600401600060405180830381865afa1580156138be573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526138e69190810190614c65565b905060006139d8600061392d847f00000000000000000000000000000000000000000000000000000000000000006001600160801b03168151811061084157610841614d32565b61393686613037565b6139bf6108ee7f000000000000000000000000000000000000000000000000000000000000001260ff167f000000000000000000000000000000000000000000000000000000000000001260ff16897f00000000000000000000000000000000000000000000000000000000000000016001600160801b0316815181106108d7576108d7614d32565b6139c9919061509f565b6139d39190614d5e565b6145da565b90506139e481846145f1565b90506139fa816139f5856002614e96565b614601565b60405163ab80dafb60e01b8152600481018290529091507f00000000000000000000000039254033945aa2e4809cc2977e7087bee48bd7ab6001600160a01b03169063ab80dafb90602401600060405180830381600087803b158015613a5f57600080fd5b505af1158015613a73573d6000803e3d6000fd5b505050507f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc36001600160a01b03167f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f627f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a883604051613af2929190614d85565b60405180910390a260408051600280825260608201835260009260208301908036833701905050905084817f00000000000000000000000000000000000000000000000000000000000000016001600160801b031681518110613b5757613b57614d32565b60200260200101818152505081817f00000000000000000000000000000000000000000000000000000000000000006001600160801b031681518110613b9f57613b9f614d32565b6020026020010181815250506000613c427f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015613c0e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c329190614dd5565b613c3c8588614ecf565b90613616565b90506000613c5f609d54670de0b6b3a76400006111e79190614dee565b905060007f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b031663b72df5de85846040518363ffffffff1660e01b8152600401613cb1929190614e3d565b6020604051808303816000875af1158015613cd0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613cf49190614dd5565b905081811015613d3c5760405162461bcd60e51b815260206004820152601360248201527226b4b71026281030b6b7bab73a1032b93937b960691b6044820152606401610738565b60405163b6b55f2560e01b8152600481018290527f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b03169063b6b55f2590602401600060405180830381600087803b158015613d9e57600080fd5b505af1158015613db2573d6000803e3d6000fd5b50505050613dbe613355565b505050505050505050565b603a5460005b81811015610d3b576000603a8281548110613dec57613dec614d32565b60009182526020822001546040516370a0823160e01b81523060048201526001600160a01b03909116925082906370a0823190602401602060405180830381865afa158015613e3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e639190614dd5565b90508015613ed357603954604080516001600160a01b039283168152918416602083015281018290527ff6c07a063ed4e63808eb8da7112d46dbcd38de2b40a73dbcc9353c5a94c723539060600160405180910390a1603954613ed3906001600160a01b038481169116836132fa565b5050600101613dcf565b6001600160a01b038116613f335760405162461bcd60e51b815260206004820152601a60248201527f4e657720476f7665726e6f7220697320616464726573732830290000000000006044820152606401610738565b61146181614610565b8251613f4f90603a906020860190614952565b50815181518114613f995760405162461bcd60e51b8152602060048201526014602482015273496e76616c696420696e7075742061727261797360601b6044820152606401610738565b60005b81811015613fe857613fe0848281518110613fb957613fb9614d32565b6020026020010151848381518110613fd357613fd3614d32565b60200260200101516134b7565b600101613f9c565b5050505050565b60405163095ea7b360e01b81526001600160a01b037f000000000000000000000000856c4efb76c1d1ae02e20ceb03a2a6a08b0b8dc3169063095ea7b39061405f907f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a89060001990600401614d85565b6020604051808303816000875af115801561407e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140a291906150c7565b506140f96001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2167f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8600019614677565b60405163095ea7b360e01b81526001600160a01b037f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a8169063095ea7b390614169907f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f9060001990600401614d85565b6020604051808303816000875af1158015614188573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146191906150c7565b6040516370a0823160e01b815230600482015281907f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b0316906370a0823190602401602060405180830381865afa158015614212573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906142369190614dd5565b101561427d5760405162461bcd60e51b8152602060048201526016602482015275496e73756666696369656e74204c5020746f6b656e7360501b6044820152606401610738565b604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000036cc1d791704445a5b6b9c36a667e511d4702f3f6001600160a01b031690632e1a7d4d90602401600060405180830381600087803b1580156142df57600080fd5b505af1158015613fe8573d6000803e3d6000fd5b604051634903b0d160e01b81526001600160801b037f000000000000000000000000000000000000000000000000000000000000000116600482015260009081906143f89060ff7f00000000000000000000000000000000000000000000000000000000000000128116917f0000000000000000000000000000000000000000000000000000000000000012909116906001600160a01b037f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a81690634903b0d190602401602060405180830381865afa1580156143d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c79190614dd5565b90506000817f000000000000000000000000cc7d5785ad5755b6164e21495e07adb0ff11c2a86001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561445b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061447f9190614dd5565b614498906ec097ce7bc90715b34b9f1000000000614e96565b6144a29190614ead565b90506000816144b2866001614ecf565b6144bc9190614e96565b90506132f16ec097ce7bc90715b34b9f100000000082614ead565b60006131028284614e96565b60006131028284614ead565b6000614544826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661477b9092919063ffffffff16565b805190915015613350578080602001905181019061456291906150c7565b6133505760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610738565b6000806145ce85856144d7565b90506132f181846144e3565b6000818312156145ea5781613102565b5090919050565b6000818310156145ea5781613102565b60008183106145ea5781613102565b806001600160a01b031661463060008051602061517d8339815191525490565b6001600160a01b03167fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a60405160405180910390a360008051602061517d83398151915255565b8015806146f15750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa1580156146cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906146ef9190614dd5565b155b61475c5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610738565b6133508363095ea7b360e01b8484604051602401613319929190614d85565b606061478a8484600085614792565b949350505050565b6060824710156147f35760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610738565b843b6148415760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610738565b600080866001600160a01b0316858760405161485d919061510d565b60006040518083038185875af1925050503d806000811461489a576040519150601f19603f3d011682016040523d82523d6000602084013e61489f565b606091505b50915091506148af8282866148ba565b979650505050505050565b606083156148c9575081613102565b8251156148d95782518084602001fd5b8160405162461bcd60e51b81526004016107389190615129565b828054828255906000526020600020908101928215614946579160200282015b828111156149465781546001600160a01b0319166001600160a01b03843516178255602090920191600190910190614913565b506130a19291506149a7565b828054828255906000526020600020908101928215614946579160200282015b8281111561494657825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190614972565b5b808211156130a157600081556001016149a8565b6000602082840312156149ce57600080fd5b5035919050565b6001600160a01b038116811461146157600080fd5b600080604083850312156149fd57600080fd5b8235614a08816149d5565b91506020830135614a18816149d5565b809150509250929050565b600060208284031215614a3557600080fd5b8135613102816149d5565b60008060408385031215614a5357600080fd5b8235614a5e816149d5565b946020939093013593505050565b60008083601f840112614a7e57600080fd5b50813567ffffffffffffffff811115614a9657600080fd5b6020830191508360208260051b8501011115614ab157600080fd5b9250929050565b600080600060408486031215614acd57600080fd5b833567ffffffffffffffff811115614ae457600080fd5b614af086828701614a6c565b909790965060209590950135949350505050565b60008060208385031215614b1757600080fd5b823567ffffffffffffffff811115614b2e57600080fd5b614b3a85828601614a6c565b90969095509350505050565b600080600060608486031215614b5b57600080fd5b8335614b66816149d5565b92506020840135614b76816149d5565b929592945050506040919091013590565b602080825282518282018190526000918401906040840190835b81811015614bc85783516001600160a01b0316835260209384019390920191600101614ba1565b509095945050505050565b600060208284031215614be557600080fd5b8151613102816149d5565b6020808252601c908201527f43616c6c6572206973206e6f7420746865205374726174656769737400000000604082015260600190565b6020808252600e908201526d1499595b9d1c985b9d0818d85b1b60921b604082015260600190565b634e487b7160e01b600052604160045260246000fd5b600060208284031215614c7757600080fd5b815167ffffffffffffffff811115614c8e57600080fd5b8201601f81018413614c9f57600080fd5b805167ffffffffffffffff811115614cb957614cb9614c4f565b8060051b604051601f19603f830116810181811067ffffffffffffffff82111715614ce657614ce6614c4f565b604052918252602081840181019290810187841115614d0457600080fd5b6020850194505b83851015614d2757845180825260209586019590935001614d0b565b509695505050505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8181036000831280158383131683831282161715614d7e57614d7e614d48565b5092915050565b6001600160a01b03929092168252602082015260400190565b6020808252601a908201527f43616c6c6572206973206e6f742074686520476f7665726e6f72000000000000604082015260600190565b600060208284031215614de757600080fd5b5051919050565b8181038181111561363b5761363b614d48565b600081518084526020840193506020830160005b82811015614e33578151865260209586019590910190600101614e15565b5093949350505050565b604081526000614e506040830185614e01565b90508260208301529392505050565b60208082526017908201527f43616c6c6572206973206e6f7420746865205661756c74000000000000000000604082015260600190565b808202811582820484141761363b5761363b614d48565b600082614eca57634e487b7160e01b600052601260045260246000fd5b500490565b8082018082111561363b5761363b614d48565b82815260406020820152600061478a6040830184614e01565b634e487b7160e01b600052603160045260246000fd5b6040808252845490820181905260008581526020812090916060840190835b81811015614f575783546001600160a01b0316835260019384019360209093019201614f30565b50508381036020808601919091528582520190508460005b85811015614fa0578135614f82816149d5565b6001600160a01b031683526020928301929190910190600101614f6f565b50909695505050505050565b6001815b6001841115614fe757808504811115614fcb57614fcb614d48565b6001841615614fd957908102905b60019390931c928002614fb0565b935093915050565b600082614ffe5750600161363b565b8161500b5750600061363b565b8160018114615021576002811461502b57615047565b600191505061363b565b60ff84111561503c5761503c614d48565b50506001821b61363b565b5060208310610133831016604e8410600b841016171561506a575081810a61363b565b6150776000198484614fac565b806000190482111561508b5761508b614d48565b029392505050565b60006131028383614fef565b80820182811260008312801582168215821617156150bf576150bf614d48565b505092915050565b6000602082840312156150d957600080fd5b8151801515811461310257600080fd5b60005b838110156151045781810151838201526020016150ec565b50506000910152565b6000825161511f8184602087016150e9565b9190910192915050565b60208152600082518060208401526151488160408501602087016150e9565b601f01601f1916919091016040019291505056fe53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac45357bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a2717ead6b9200dd235aad468c9809ea400fe33ac69b5bfaa6d3e90fc922b6398a264697066735822122029337a4c182fb90fc2edbfe25e32b5811d95e135b6ffc3b686ee4e92c5ee9c1264736f6c634300081c0033

Verified Source Code Full Match

Compiler: v0.8.28+commit.7893614a EVM: paris Optimization: Yes (200 runs)
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);
            }
        }
    }
}
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);
    }
}
SafeMath.sol 227 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

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

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

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

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

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}
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);
}
ICurveLiquidityGaugeV6.sol 177 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;

interface ICurveLiquidityGaugeV6 {
    event ApplyOwnership(address admin);
    event Approval(
        address indexed _owner,
        address indexed _spender,
        uint256 _value
    );
    event CommitOwnership(address admin);
    event Deposit(address indexed provider, uint256 value);
    event SetGaugeManager(address _gauge_manager);
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event UpdateLiquidityLimit(
        address indexed user,
        uint256 original_balance,
        uint256 original_supply,
        uint256 working_balance,
        uint256 working_supply
    );
    event Withdraw(address indexed provider, uint256 value);

    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function add_reward(address _reward_token, address _distributor) external;

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

    function approve(address _spender, uint256 _value) external returns (bool);

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

    function claim_rewards() external;

    function claim_rewards(address _addr) external;

    function claim_rewards(address _addr, address _receiver) external;

    function claimable_reward(address _user, address _reward_token)
        external
        view
        returns (uint256);

    function claimable_tokens(address addr) external returns (uint256);

    function claimed_reward(address _addr, address _token)
        external
        view
        returns (uint256);

    function decimals() external view returns (uint256);

    function decreaseAllowance(address _spender, uint256 _subtracted_value)
        external
        returns (bool);

    function deposit(uint256 _value) external;

    function deposit(uint256 _value, address _addr) external;

    function deposit(
        uint256 _value,
        address _addr,
        bool _claim_rewards
    ) external;

    function deposit_reward_token(address _reward_token, uint256 _amount)
        external;

    function deposit_reward_token(
        address _reward_token,
        uint256 _amount,
        uint256 _epoch
    ) external;

    function factory() external view returns (address);

    function future_epoch_time() external view returns (uint256);

    function increaseAllowance(address _spender, uint256 _added_value)
        external
        returns (bool);

    function inflation_rate() external view returns (uint256);

    function integrate_checkpoint() external view returns (uint256);

    function integrate_checkpoint_of(address arg0)
        external
        view
        returns (uint256);

    function integrate_fraction(address arg0) external view returns (uint256);

    function integrate_inv_supply(uint256 arg0) external view returns (uint256);

    function integrate_inv_supply_of(address arg0)
        external
        view
        returns (uint256);

    function is_killed() external view returns (bool);

    function kick(address addr) external;

    function lp_token() external view returns (address);

    function manager() external view returns (address);

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

    function nonces(address arg0) external view returns (uint256);

    function period() external view returns (int128);

    function period_timestamp(uint256 arg0) external view returns (uint256);

    function permit(
        address _owner,
        address _spender,
        uint256 _value,
        uint256 _deadline,
        uint8 _v,
        bytes32 _r,
        bytes32 _s
    ) external returns (bool);

    function reward_count() external view returns (uint256);

    function reward_integral_for(address arg0, address arg1)
        external
        view
        returns (uint256);

    function reward_tokens(uint256 arg0) external view returns (address);

    function rewards_receiver(address arg0) external view returns (address);

    function salt() external view returns (bytes32);

    function set_gauge_manager(address _gauge_manager) external;

    function set_killed(bool _is_killed) external;

    function set_reward_distributor(address _reward_token, address _distributor)
        external;

    function set_rewards_receiver(address _receiver) external;

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

    function totalSupply() external view returns (uint256);

    function transfer(address _to, uint256 _value) external returns (bool);

    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) external returns (bool);

    function user_checkpoint(address addr) external returns (bool);

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

    function withdraw(uint256 _value) external;

    function withdraw(uint256 _value, bool _claim_rewards) external;

    function working_balances(address arg0) external view returns (uint256);

    function working_supply() external view returns (uint256);
}
ICurveMinter.sol 25 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;

interface ICurveMinter {
    event Minted(address indexed recipient, address gauge, uint256 minted);

    function allowed_to_mint_for(address arg0, address arg1)
        external
        view
        returns (bool);

    function controller() external view returns (address);

    function mint(address gauge_addr) external;

    function mint_for(address gauge_addr, address _for) external;

    function mint_many(address[8] memory gauge_addrs) external;

    function minted(address arg0, address arg1) external view returns (uint256);

    function toggle_approve_mint(address minting_user) external;

    function token() external view returns (address);
}
ICurveStableSwapNG.sol 273 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;

interface ICurveStableSwapNG {
    event AddLiquidity(
        address indexed provider,
        uint256[] token_amounts,
        uint256[] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event ApplyNewFee(uint256 fee, uint256 offpeg_fee_multiplier);
    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 value
    );
    event RampA(
        uint256 old_A,
        uint256 new_A,
        uint256 initial_time,
        uint256 future_time
    );
    event RemoveLiquidity(
        address indexed provider,
        uint256[] token_amounts,
        uint256[] fees,
        uint256 token_supply
    );
    event RemoveLiquidityImbalance(
        address indexed provider,
        uint256[] token_amounts,
        uint256[] fees,
        uint256 invariant,
        uint256 token_supply
    );
    event RemoveLiquidityOne(
        address indexed provider,
        int128 token_id,
        uint256 token_amount,
        uint256 coin_amount,
        uint256 token_supply
    );
    event SetNewMATime(uint256 ma_exp_time, uint256 D_ma_time);
    event StopRampA(uint256 A, uint256 t);
    event TokenExchange(
        address indexed buyer,
        int128 sold_id,
        uint256 tokens_sold,
        int128 bought_id,
        uint256 tokens_bought
    );
    event TokenExchangeUnderlying(
        address indexed buyer,
        int128 sold_id,
        uint256 tokens_sold,
        int128 bought_id,
        uint256 tokens_bought
    );
    event Transfer(
        address indexed sender,
        address indexed receiver,
        uint256 value
    );

    function A() external view returns (uint256);

    function A_precise() external view returns (uint256);

    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function D_ma_time() external view returns (uint256);

    function D_oracle() external view returns (uint256);

    function N_COINS() external view returns (uint256);

    function add_liquidity(uint256[] memory _amounts, uint256 _min_mint_amount)
        external
        returns (uint256);

    function add_liquidity(
        uint256[] memory _amounts,
        uint256 _min_mint_amount,
        address _receiver
    ) external returns (uint256);

    function admin_balances(uint256 arg0) external view returns (uint256);

    function admin_fee() external view returns (uint256);

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

    function approve(address _spender, uint256 _value) external returns (bool);

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

    function balances(uint256 i) external view returns (uint256);

    function calc_token_amount(uint256[] memory _amounts, bool _is_deposit)
        external
        view
        returns (uint256);

    function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)
        external
        view
        returns (uint256);

    function coins(uint256 arg0) external view returns (address);

    function decimals() external view returns (uint8);

    function dynamic_fee(int128 i, int128 j) external view returns (uint256);

    function ema_price(uint256 i) external view returns (uint256);

    function exchange(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy
    ) external returns (uint256);

    function exchange(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy,
        address _receiver
    ) external returns (uint256);

    function exchange_received(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy
    ) external returns (uint256);

    function exchange_received(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy,
        address _receiver
    ) external returns (uint256);

    function fee() external view returns (uint256);

    function future_A() external view returns (uint256);

    function future_A_time() external view returns (uint256);

    function get_balances() external view returns (uint256[] memory);

    function get_dx(
        int128 i,
        int128 j,
        uint256 dy
    ) external view returns (uint256);

    function get_dy(
        int128 i,
        int128 j,
        uint256 dx
    ) external view returns (uint256);

    function get_p(uint256 i) external view returns (uint256);

    function get_virtual_price() external view returns (uint256);

    function initial_A() external view returns (uint256);

    function initial_A_time() external view returns (uint256);

    function last_price(uint256 i) external view returns (uint256);

    function ma_exp_time() external view returns (uint256);

    function ma_last_time() external view returns (uint256);

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

    function nonces(address arg0) external view returns (uint256);

    function offpeg_fee_multiplier() external view returns (uint256);

    function permit(
        address _owner,
        address _spender,
        uint256 _value,
        uint256 _deadline,
        uint8 _v,
        bytes32 _r,
        bytes32 _s
    ) external returns (bool);

    function price_oracle(uint256 i) external view returns (uint256);

    function ramp_A(uint256 _future_A, uint256 _future_time) external;

    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts
    ) external returns (uint256[] memory);

    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts,
        address _receiver
    ) external returns (uint256[] memory);

    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts,
        address _receiver,
        bool _claim_admin_fees
    ) external returns (uint256[] memory);

    function remove_liquidity_imbalance(
        uint256[] memory _amounts,
        uint256 _max_burn_amount
    ) external returns (uint256);

    function remove_liquidity_imbalance(
        uint256[] memory _amounts,
        uint256 _max_burn_amount,
        address _receiver
    ) external returns (uint256);

    function remove_liquidity_one_coin(
        uint256 _burn_amount,
        int128 i,
        uint256 _min_received
    ) external returns (uint256);

    function remove_liquidity_one_coin(
        uint256 _burn_amount,
        int128 i,
        uint256 _min_received,
        address _receiver
    ) external returns (uint256);

    function salt() external view returns (bytes32);

    function set_ma_exp_time(uint256 _ma_exp_time, uint256 _D_ma_time) external;

    function set_new_fee(uint256 _new_fee, uint256 _new_offpeg_fee_multiplier)
        external;

    function stop_ramp_A() external;

    function stored_rates() external view returns (uint256[] memory);

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

    function totalSupply() external view returns (uint256);

    function transfer(address _to, uint256 _value) external returns (bool);

    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) external returns (bool);

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

    function withdraw_admin_fees() 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
}
CurveAMOStrategy.sol 705 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Curve Automated Market Maker (AMO) Strategy
 * @notice AMO strategy for a Curve pool using an OToken.
 * @author Origin Protocol Inc
 */
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { IERC20, InitializableAbstractStrategy } from "../utils/InitializableAbstractStrategy.sol";
import { StableMath } from "../utils/StableMath.sol";
import { IVault } from "../interfaces/IVault.sol";
import { ICurveStableSwapNG } from "../interfaces/ICurveStableSwapNG.sol";
import { ICurveLiquidityGaugeV6 } from "../interfaces/ICurveLiquidityGaugeV6.sol";
import { IBasicToken } from "../interfaces/IBasicToken.sol";
import { ICurveMinter } from "../interfaces/ICurveMinter.sol";

contract CurveAMOStrategy is InitializableAbstractStrategy {
    using SafeCast for uint256;
    using SafeERC20 for IERC20;
    using StableMath for uint256;

    /**
     * @dev a threshold under which the contract no longer allows for the protocol to manually rebalance.
     *      Guarding against a strategist / guardian being taken over and with multiple transactions
     *      draining the protocol funds.
     */
    uint256 public constant SOLVENCY_THRESHOLD = 0.998 ether;

    // New immutable variables that must be set in the constructor
    /**
     * @notice Address of the hard asset (weth, usdt, usdc).
     */
    IERC20 public immutable hardAsset;

    /**
     * @notice Address of the OTOKEN token contract.
     */
    IERC20 public immutable oToken;

    /**
     * @notice Address of the LP (Liquidity Provider) token contract.
     */
    IERC20 public immutable lpToken;

    /**
     * @notice Address of the Curve StableSwap NG pool contract.
     */
    ICurveStableSwapNG public immutable curvePool;

    /**
     * @notice Address of the Curve X-Chain Liquidity Gauge contract.
     */
    ICurveLiquidityGaugeV6 public immutable gauge;

    /**
     * @notice Address of the Curve Minter contract.
     */
    ICurveMinter public immutable minter;

    /**
     * @notice Index of the OTOKEN and hardAsset in the Curve pool.
     */
    uint128 public immutable otokenCoinIndex;
    uint128 public immutable hardAssetCoinIndex;

    /**
     * @notice Decimals of the OTOKEN and hardAsset.
     */
    uint8 public immutable decimalsOToken;
    uint8 public immutable decimalsHardAsset;

    /**
     * @notice Maximum slippage allowed for adding/removing liquidity from the Curve pool.
     */
    uint256 public maxSlippage;

    event MaxSlippageUpdated(uint256 newMaxSlippage);

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

    /**
     * @dev Checks the Curve pool's balances have improved and the balances
     * have not tipped to the other side.
     * This modifier is only applied to functions that do a single sided add or remove.
     * The standard deposit function adds to both sides of the pool in a way that
     * the pool's balance is not worsened.
     * Withdrawals are proportional so doesn't change the pools asset balance.
     */
    modifier improvePoolBalance() {
        // Get the hard asset and OToken balances in the Curve pool
        uint256[] memory balancesBefore = curvePool.get_balances();
        // diff = hardAsset balance - OTOKEN balance
        int256 diffBefore = (
            balancesBefore[hardAssetCoinIndex].scaleBy(
                decimalsOToken,
                decimalsHardAsset
            )
        ).toInt256() - balancesBefore[otokenCoinIndex].toInt256();

        _;

        // Get the hard asset and OToken balances in the Curve pool
        uint256[] memory balancesAfter = curvePool.get_balances();
        // diff = hardAsset balance - OTOKEN balance
        int256 diffAfter = (
            balancesAfter[hardAssetCoinIndex].scaleBy(
                decimalsOToken,
                decimalsHardAsset
            )
        ).toInt256() - balancesAfter[otokenCoinIndex].toInt256();

        if (diffBefore == 0) {
            require(diffAfter == 0, "Position balance is worsened");
        } else if (diffBefore < 0) {
            // If the pool was originally imbalanced in favor of OTOKEN, then
            // we want to check that the pool is now more balanced
            require(diffAfter <= 0, "OTokens overshot peg");
            require(diffBefore < diffAfter, "OTokens balance worse");
        } else if (diffBefore > 0) {
            // If the pool was originally imbalanced in favor of hardAsset, then
            // we want to check that the pool is now more balanced
            require(diffAfter >= 0, "Assets overshot peg");
            require(diffAfter < diffBefore, "Assets balance worse");
        }
    }

    constructor(
        BaseStrategyConfig memory _baseConfig,
        address _otoken,
        address _hardAsset,
        address _gauge,
        address _minter
    ) InitializableAbstractStrategy(_baseConfig) {
        lpToken = IERC20(_baseConfig.platformAddress);
        curvePool = ICurveStableSwapNG(_baseConfig.platformAddress);
        minter = ICurveMinter(_minter);

        oToken = IERC20(_otoken);
        hardAsset = IERC20(_hardAsset);
        gauge = ICurveLiquidityGaugeV6(_gauge);
        decimalsHardAsset = IBasicToken(_hardAsset).decimals();
        decimalsOToken = IBasicToken(_otoken).decimals();

        (hardAssetCoinIndex, otokenCoinIndex) = curvePool.coins(0) == _hardAsset
            ? (0, 1)
            : (1, 0);
        require(
            curvePool.coins(otokenCoinIndex) == _otoken &&
                curvePool.coins(hardAssetCoinIndex) == _hardAsset,
            "Invalid coin indexes"
        );
        require(gauge.lp_token() == address(curvePool), "Invalid pool");
    }

    /**
     * Initializer for setting up strategy internal state. This overrides the
     * InitializableAbstractStrategy initializer as Curve strategies don't fit
     * well within that abstraction.
     * @param _rewardTokenAddresses Address of CRV
     * @param _maxSlippage Maximum slippage allowed for adding/removing liquidity from the Curve pool.
     */
    function initialize(
        address[] calldata _rewardTokenAddresses, // CRV
        uint256 _maxSlippage
    ) external onlyGovernor initializer {
        address[] memory pTokens = new address[](1);
        pTokens[0] = address(curvePool);

        address[] memory _assets = new address[](1);
        _assets[0] = address(hardAsset);

        InitializableAbstractStrategy._initialize(
            _rewardTokenAddresses,
            _assets,
            pTokens
        );

        _approveBase();
        _setMaxSlippage(_maxSlippage);
    }

    /***************************************
                    Deposit
    ****************************************/

    /**
     * @notice Deposit hard asset into the Curve pool
     * @param _hardAsset Address of hard asset contract.
     * @param _amount Amount of hard asset to deposit.
     */
    function deposit(address _hardAsset, uint256 _amount)
        external
        override
        onlyVault
        nonReentrant
    {
        _deposit(_hardAsset, _amount);
    }

    function _deposit(address _hardAsset, uint256 _hardAssetAmount) internal {
        require(_hardAssetAmount > 0, "Must deposit something");
        require(_hardAsset == address(hardAsset), "Unsupported asset");

        emit Deposit(_hardAsset, address(lpToken), _hardAssetAmount);
        uint256 scaledHardAssetAmount = _hardAssetAmount.scaleBy(
            decimalsOToken,
            decimalsHardAsset
        );

        // Get the asset and OToken balances in the Curve pool
        uint256[] memory balances = curvePool.get_balances();
        // safe to cast since min value is at least 0
        uint256 otokenToAdd = uint256(
            _max(
                0,
                (
                    balances[hardAssetCoinIndex].scaleBy(
                        decimalsOToken,
                        decimalsHardAsset
                    )
                ).toInt256() +
                    scaledHardAssetAmount.toInt256() -
                    balances[otokenCoinIndex].toInt256()
            )
        );

        /* Add so much OTOKEN so that the pool ends up being balanced. And at minimum
         * add as much OTOKEN as hard asset and at maximum twice as much OTOKEN.
         */
        otokenToAdd = Math.max(otokenToAdd, scaledHardAssetAmount);
        otokenToAdd = Math.min(otokenToAdd, scaledHardAssetAmount * 2);

        /* Mint OTOKEN with a strategy that attempts to contribute to stability of OTOKEN/hardAsset pool. Try
         * to mint so much OTOKEN that after deployment of liquidity pool ends up being balanced.
         *
         * To manage unpredictability minimal OTOKEN minted will always be at least equal or greater
         * to hardAsset amount deployed. And never larger than twice the hardAsset amount deployed even if
         * it would have a further beneficial effect on pool stability.
         */
        IVault(vaultAddress).mintForStrategy(otokenToAdd);

        emit Deposit(address(oToken), address(lpToken), otokenToAdd);

        uint256[] memory _amounts = new uint256[](2);
        _amounts[hardAssetCoinIndex] = _hardAssetAmount;
        _amounts[otokenCoinIndex] = otokenToAdd;

        uint256 valueInLpTokens = (scaledHardAssetAmount + otokenToAdd)
            .divPrecisely(curvePool.get_virtual_price());
        uint256 minMintAmount = valueInLpTokens.mulTruncate(
            uint256(1e18) - maxSlippage
        );

        // Do the deposit to the Curve pool
        uint256 lpDeposited = curvePool.add_liquidity(_amounts, minMintAmount);
        require(lpDeposited >= minMintAmount, "Min LP amount error");

        // Deposit the Curve pool's LP tokens into the Curve gauge
        gauge.deposit(lpDeposited);

        // Ensure solvency of the vault
        _solvencyAssert();
    }

    /**
     * @notice Deposit the strategy's entire balance of hardAsset into the Curve pool
     */
    function depositAll() external override onlyVault nonReentrant {
        uint256 balance = hardAsset.balanceOf(address(this));
        if (balance > 0) {
            _deposit(address(hardAsset), balance);
        }
    }

    /***************************************
                    Withdraw
    ****************************************/

    /**
     * @notice Withdraw hardAsset and OTOKEN from the Curve pool, burn the OTOKEN,
     * transfer hardAsset to the recipient.
     * @param _recipient Address to receive withdrawn asset which is normally the Vault.
     * @param _hardAsset Address of the hardAsset contract.
     * @param _amount Amount of hardAsset to withdraw.
     */
    function withdraw(
        address _recipient,
        address _hardAsset,
        uint256 _amount
    ) external override onlyVault nonReentrant {
        require(_amount > 0, "Must withdraw something");
        require(
            _hardAsset == address(hardAsset),
            "Can only withdraw hard asset"
        );

        emit Withdrawal(_hardAsset, address(lpToken), _amount);

        uint256 requiredLpTokens = calcTokenToBurn(
            _amount.scaleBy(decimalsOToken, decimalsHardAsset)
        );

        _lpWithdraw(requiredLpTokens);

        /* math in requiredLpTokens should correctly calculate the amount of LP to remove
         * in that the strategy receives enough hardAsset on balanced removal
         */
        uint256[] memory _minWithdrawalAmounts = new uint256[](2);
        _minWithdrawalAmounts[hardAssetCoinIndex] = _amount;
        // slither-disable-next-line unused-return
        curvePool.remove_liquidity(requiredLpTokens, _minWithdrawalAmounts);

        // Burn all the removed OTOKEN and any that was left in the strategy
        uint256 otokenToBurn = oToken.balanceOf(address(this));
        IVault(vaultAddress).burnForStrategy(otokenToBurn);

        emit Withdrawal(address(oToken), address(lpToken), otokenToBurn);

        // Transfer hardAsset to the recipient
        hardAsset.safeTransfer(_recipient, _amount);

        // Ensure solvency of the vault
        _solvencyAssert();
    }

    function calcTokenToBurn(uint256 _hardAssetAmount)
        internal
        view
        returns (uint256 lpToBurn)
    {
        /* The rate between coins in the pool determines the rate at which pool returns
         * tokens when doing balanced removal (remove_liquidity call). And by knowing how much hardAsset
         * we want we can determine how much of OTOKEN we receive by removing liquidity.
         *
         * Because we are doing balanced removal we should be making profit when removing liquidity in a
         * pool tilted to either side.
         *
         * Important: A downside is that the Strategist / Governor needs to be
         * cognisant of not removing too much liquidity. And while the proposal to remove liquidity
         * is being voted on the pool tilt might change so much that the proposal that has been valid while
         * created is no longer valid.
         */

        uint256 poolHardAssetBalance = curvePool
            .balances(hardAssetCoinIndex)
            .scaleBy(decimalsOToken, decimalsHardAsset);
        /* K is multiplied by 1e36 which is used for higher precision calculation of required
         * pool LP tokens. Without it the end value can have rounding errors up to precision of
         * 10 digits. This way we move the decimal point by 36 places when doing the calculation
         * and again by 36 places when we are done with it.
         */
        uint256 k = (1e36 * lpToken.totalSupply()) / poolHardAssetBalance;
        // prettier-ignore
        // slither-disable-next-line divide-before-multiply
        uint256 diff = (_hardAssetAmount + 1) * k;
        lpToBurn = diff / 1e36;
    }

    /**
     * @notice Remove all hardAsset and OTOKEN from the Curve pool, burn the OTOKEN,
     * transfer hardAsset to the Vault contract.
     */
    function withdrawAll() external override onlyVaultOrGovernor nonReentrant {
        uint256 gaugeTokens = gauge.balanceOf(address(this));
        _lpWithdraw(gaugeTokens);

        // Withdraws are proportional to assets held by 3Pool
        uint256[] memory minWithdrawAmounts = new uint256[](2);

        // Check balance of LP tokens in the strategy, if 0 return
        uint256 lpBalance = lpToken.balanceOf(address(this));

        // Remove liquidity
        // slither-disable-next-line unused-return
        if (lpBalance > 0) {
            curvePool.remove_liquidity(lpBalance, minWithdrawAmounts);
        }

        // Burn all OTOKEN
        uint256 otokenToBurn = oToken.balanceOf(address(this));
        IVault(vaultAddress).burnForStrategy(otokenToBurn);

        // Get the strategy contract's hardAsset balance.
        // This includes all that was removed from the Curve pool and
        // any hardAsset that was sitting in the strategy contract before the removal.
        uint256 hardAssetBalance = hardAsset.balanceOf(address(this));
        hardAsset.safeTransfer(vaultAddress, hardAssetBalance);

        if (hardAssetBalance > 0)
            emit Withdrawal(
                address(hardAsset),
                address(lpToken),
                hardAssetBalance
            );
        if (otokenToBurn > 0)
            emit Withdrawal(address(oToken), address(lpToken), otokenToBurn);
    }

    /***************************************
            Curve pool Rebalancing
    ****************************************/

    /**
     * @notice Mint OTokens and one-sided add to the Curve pool.
     * This is used when the Curve pool does not have enough OTokens and too many hardAsset.
     * The OToken/Asset, eg OTOKEN/hardAsset, price with increase.
     * The amount of assets in the vault is unchanged.
     * The total supply of OTokens is increased.
     * The asset value of the strategy and vault is increased.
     * @param _oTokens The amount of OTokens to be minted and added to the pool.
     */
    function mintAndAddOTokens(uint256 _oTokens)
        external
        onlyStrategist
        nonReentrant
        improvePoolBalance
    {
        IVault(vaultAddress).mintForStrategy(_oTokens);

        uint256[] memory amounts = new uint256[](2);
        amounts[otokenCoinIndex] = _oTokens;

        // Convert OTOKEN to Curve pool LP tokens
        uint256 valueInLpTokens = (_oTokens).divPrecisely(
            curvePool.get_virtual_price()
        );
        // Apply slippage to LP tokens
        uint256 minMintAmount = valueInLpTokens.mulTruncate(
            uint256(1e18) - maxSlippage
        );

        // Add the minted OTokens to the Curve pool
        uint256 lpDeposited = curvePool.add_liquidity(amounts, minMintAmount);
        require(lpDeposited >= minMintAmount, "Min LP amount error");

        // Deposit the Curve pool LP tokens to the Curve gauge
        gauge.deposit(lpDeposited);

        // Ensure solvency of the vault
        _solvencyAssert();

        emit Deposit(address(oToken), address(lpToken), _oTokens);
    }

    /**
     * @notice One-sided remove of OTokens from the Curve pool which are then burned.
     * This is used when the Curve pool has too many OTokens and not enough hardAsset.
     * The amount of assets in the vault is unchanged.
     * The total supply of OTokens is reduced.
     * The asset value of the strategy and vault is reduced.
     * @param _lpTokens The amount of Curve pool LP tokens to be burned for OTokens.
     */
    function removeAndBurnOTokens(uint256 _lpTokens)
        external
        onlyStrategist
        nonReentrant
        improvePoolBalance
    {
        // Withdraw Curve pool LP tokens from gauge and remove OTokens from the Curve pool
        uint256 otokenToBurn = _withdrawAndRemoveFromPool(
            _lpTokens,
            otokenCoinIndex
        );

        // The vault burns the OTokens from this strategy
        IVault(vaultAddress).burnForStrategy(otokenToBurn);

        // Ensure solvency of the vault
        _solvencyAssert();

        emit Withdrawal(address(oToken), address(lpToken), otokenToBurn);
    }

    /**
     * @notice One-sided remove of hardAsset from the Curve pool and transfer to the vault.
     * This is used when the Curve pool does not have enough OTokens and too many hardAsset.
     * The OToken/Asset, eg OTOKEN/hardAsset, price with decrease.
     * The amount of assets in the vault increases.
     * The total supply of OTokens does not change.
     * The asset value of the strategy reduces.
     * The asset value of the vault should be close to the same.
     * @param _lpTokens The amount of Curve pool LP tokens to be burned for hardAsset.
     * @dev Curve pool LP tokens is used rather than hardAsset assets as Curve does not
     * have a way to accurately calculate the amount of LP tokens for a required
     * amount of hardAsset. Curve's `calc_token_amount` function does not include fees.
     * A 3rd party library can be used that takes into account the fees, but this
     * is a gas intensive process. It's easier for the trusted strategist to
     * calculate the amount of Curve pool LP tokens required off-chain.
     */
    function removeOnlyAssets(uint256 _lpTokens)
        external
        onlyStrategist
        nonReentrant
        improvePoolBalance
    {
        // Withdraw Curve pool LP tokens from Curve gauge and remove hardAsset from the Curve pool
        uint256 hardAssetAmount = _withdrawAndRemoveFromPool(
            _lpTokens,
            hardAssetCoinIndex
        );

        // Transfer hardAsset to the vault
        hardAsset.safeTransfer(vaultAddress, hardAssetAmount);

        // Ensure solvency of the vault
        _solvencyAssert();

        emit Withdrawal(address(hardAsset), address(lpToken), hardAssetAmount);
    }

    /**
     * @dev Remove Curve pool LP tokens from the gauge and
     * do a one-sided remove of hardAsset or OTOKEN from the Curve pool.
     * @param _lpTokens The amount of Curve pool LP tokens to be removed from the gauge
     * @param coinIndex The index of the coin to be removed from the Curve pool. 0 = hardAsset, 1 = OTOKEN.
     * @return coinsRemoved The amount of hardAsset or OTOKEN removed from the Curve pool.
     */
    function _withdrawAndRemoveFromPool(uint256 _lpTokens, uint128 coinIndex)
        internal
        returns (uint256 coinsRemoved)
    {
        // Withdraw Curve pool LP tokens from Curve gauge
        _lpWithdraw(_lpTokens);

        // Convert Curve pool LP tokens to hardAsset value
        uint256 valueInEth = _lpTokens.mulTruncate(
            curvePool.get_virtual_price()
        );

        if (coinIndex == hardAssetCoinIndex) {
            valueInEth = valueInEth.scaleBy(decimalsHardAsset, decimalsOToken);
        }

        // Apply slippage to hardAsset value
        uint256 minAmount = valueInEth.mulTruncate(uint256(1e18) - maxSlippage);

        // Remove just the hardAsset from the Curve pool
        coinsRemoved = curvePool.remove_liquidity_one_coin(
            _lpTokens,
            int128(coinIndex),
            minAmount,
            address(this)
        );
    }

    /**
     * Checks that the protocol is solvent, protecting from a rogue Strategist / Guardian that can
     * keep rebalancing the pool in both directions making the protocol lose a tiny amount of
     * funds each time.
     *
     * Protocol must be at least SOLVENCY_THRESHOLD (99,8 %) backed in order for the rebalances to
     * function.
     */
    function _solvencyAssert() internal view {
        uint256 _totalVaultValue = IVault(vaultAddress).totalValue();
        uint256 _totalOtokenSupply = oToken.totalSupply();

        if (
            _totalVaultValue.divPrecisely(_totalOtokenSupply) <
            SOLVENCY_THRESHOLD
        ) {
            revert("Protocol insolvent");
        }
    }

    /***************************************
                Assets and Rewards
    ****************************************/

    /**
     * @notice Collect accumulated CRV (and other) rewards and send to the Harvester.
     */
    function collectRewardTokens()
        external
        override
        onlyHarvester
        nonReentrant
    {
        // Collect CRV rewards from inflation
        minter.mint(address(gauge));

        // Collect extra gauge rewards (outside of CRV)
        gauge.claim_rewards();

        _collectRewardTokens();
    }

    function _lpWithdraw(uint256 _lpAmount) internal {
        require(
            gauge.balanceOf(address(this)) >= _lpAmount,
            "Insufficient LP tokens"
        );
        // withdraw lp tokens from the gauge without claiming rewards
        gauge.withdraw(_lpAmount);
    }

    /**
     * @notice Get the total asset value held in the platform
     * @param _asset      Address of the asset
     * @return balance    Total value of the asset in the platform
     */
    function checkBalance(address _asset)
        external
        view
        override
        returns (uint256 balance)
    {
        require(_asset == address(hardAsset), "Unsupported asset");

        // hardAsset balance needed here for the balance check that happens from vault during depositing.
        balance = hardAsset.balanceOf(address(this));
        uint256 lpTokens = gauge.balanceOf(address(this));
        if (lpTokens > 0) {
            balance += ((lpTokens * curvePool.get_virtual_price()) / 1e18)
                .scaleBy(decimalsHardAsset, decimalsOToken);
        }
    }

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

    /***************************************
                    Approvals
    ****************************************/

    /**
     * @notice Sets the maximum slippage allowed for any swap/liquidity operation
     * @param _maxSlippage Maximum slippage allowed, 1e18 = 100%.
     */
    function setMaxSlippage(uint256 _maxSlippage) external onlyGovernor {
        _setMaxSlippage(_maxSlippage);
    }

    function _setMaxSlippage(uint256 _maxSlippage) internal {
        require(_maxSlippage <= 5e16, "Slippage must be less than 100%");
        maxSlippage = _maxSlippage;
        emit MaxSlippageUpdated(_maxSlippage);
    }

    /**
     * @notice Approve the spending of all assets by their corresponding pool tokens,
     *      if for some reason is it necessary.
     */
    function safeApproveAllTokens()
        external
        override
        onlyGovernor
        nonReentrant
    {
        _approveBase();
    }

    /**
     * @dev Since we are unwrapping WETH before depositing it to Curve
     *      there is no need to set an approval for WETH on the Curve
     *      pool
     * @param _asset Address of the asset
     * @param _pToken Address of the Curve LP token
     */
    // solhint-disable-next-line no-unused-vars
    function _abstractSetPToken(address _asset, address _pToken)
        internal
        override
    {}

    function _approveBase() internal {
        // Approve Curve pool for OTOKEN (required for adding liquidity)
        // slither-disable-next-line unused-return
        oToken.approve(platformAddress, type(uint256).max);

        // Approve Curve pool for hardAsset (required for adding liquidity)
        // slither-disable-next-line unused-return
        hardAsset.safeApprove(platformAddress, type(uint256).max);

        // Approve Curve gauge contract to transfer Curve pool LP tokens
        // This is needed for deposits if Curve pool LP tokens into the Curve gauge.
        // slither-disable-next-line unused-return
        lpToken.approve(address(gauge), type(uint256).max);
    }

    /**
     * @dev Returns the largest of two numbers int256 version
     */
    function _max(int256 a, int256 b) internal pure returns (int256) {
        return a >= b ? a : b;
    }
}
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);
}
StableMath.sol 115 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

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

// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol

library StableMath {
    using SafeMath for uint256;

    /**
     * @dev Scaling unit for use in specific calculations,
     * where 1 * 10**18, or 1e18 represents a unit '1'
     */
    uint256 private constant FULL_SCALE = 1e18;

    /***************************************
                    Helpers
    ****************************************/

    /**
     * @dev Adjust the scale of an integer
     * @param to Decimals to scale to
     * @param from Decimals to scale from
     */
    function scaleBy(
        uint256 x,
        uint256 to,
        uint256 from
    ) internal pure returns (uint256) {
        if (to > from) {
            x = x.mul(10**(to - from));
        } else if (to < from) {
            // slither-disable-next-line divide-before-multiply
            x = x.div(10**(from - to));
        }
        return x;
    }

    /***************************************
               Precise Arithmetic
    ****************************************/

    /**
     * @dev Multiplies two precise units, and then truncates by the full scale
     * @param x Left hand input to multiplication
     * @param y Right hand input to multiplication
     * @return Result after multiplying the two inputs and then dividing by the shared
     *         scale unit
     */
    function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulTruncateScale(x, y, FULL_SCALE);
    }

    /**
     * @dev Multiplies two precise units, and then truncates by the given scale. For example,
     * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
     * @param x Left hand input to multiplication
     * @param y Right hand input to multiplication
     * @param scale Scale unit
     * @return Result after multiplying the two inputs and then dividing by the shared
     *         scale unit
     */
    function mulTruncateScale(
        uint256 x,
        uint256 y,
        uint256 scale
    ) internal pure returns (uint256) {
        // e.g. assume scale = fullScale
        // z = 10e18 * 9e17 = 9e36
        uint256 z = x.mul(y);
        // return 9e36 / 1e18 = 9e18
        return z.div(scale);
    }

    /**
     * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
     * @param x Left hand input to multiplication
     * @param y Right hand input to multiplication
     * @return Result after multiplying the two inputs and then dividing by the shared
     *          scale unit, rounded up to the closest base unit.
     */
    function mulTruncateCeil(uint256 x, uint256 y)
        internal
        pure
        returns (uint256)
    {
        // e.g. 8e17 * 17268172638 = 138145381104e17
        uint256 scaled = x.mul(y);
        // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
        uint256 ceil = scaled.add(FULL_SCALE.sub(1));
        // e.g. 13814538111.399...e18 / 1e18 = 13814538111
        return ceil.div(FULL_SCALE);
    }

    /**
     * @dev Precisely divides two units, by first scaling the left hand operand. Useful
     *      for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
     * @param x Left hand input to division
     * @param y Right hand input to division
     * @return Result after multiplying the left operand by the scale, and
     *         executing the division on the right hand input.
     */
    function divPrecisely(uint256 x, uint256 y)
        internal
        pure
        returns (uint256)
    {
        // e.g. 8e18 * 1e18 = 8e36
        uint256 z = x.mul(FULL_SCALE);
        // e.g. 8e36 / 10e18 = 8e17
        return z.div(y);
    }
}
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

SOLVENCY_THRESHOLD 0x1b91d0cc → uint256
assetToPToken 0x0fc3b4c4 → address
checkBalance 0x5f515226 → uint256
curvePool 0x218751b2 → address
decimalsHardAsset 0x65a217c6 → uint8
decimalsOToken 0xe70940d1 → uint8
gauge 0xa6f19c84 → address
getRewardTokenAddresses 0xf6ca71b0 → address[]
governor 0x0c340a24 → address
hardAsset 0x9642913c → address
hardAssetCoinIndex 0xb60ce400 → uint128
harvesterAddress 0x67c7066c → address
isGovernor 0xc7af3352 → bool
lpToken 0x5fcbd285 → address
maxSlippage 0x8c04166f → uint256
minter 0x07546172 → address
oToken 0x1a32aad6 → address
otokenCoinIndex 0x47de4b7d → uint128
platformAddress 0xdbe55e56 → address
rewardTokenAddresses 0x7b2d9b2c → address
supportsAsset 0xaa388af6 → bool
vaultAddress 0x430bf08a → address

Write Contract 18 functions

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

claimGovernance 0x5d36b190
No parameters
collectRewardTokens 0x5a063f63
No parameters
deposit 0x47e7ef24
address _hardAsset
uint256 _amount
depositAll 0xde5f6268
No parameters
initialize 0x60b5bb3f
address[] _rewardTokenAddresses
uint256 _maxSlippage
mintAndAddOTokens 0x37145038
uint256 _oTokens
removeAndBurnOTokens 0xe033193a
uint256 _lpTokens
removeOnlyAssets 0x012c6383
uint256 _lpTokens
removePToken 0x9136616a
uint256 _assetIndex
safeApproveAllTokens 0xad1728cb
No parameters
setHarvesterAddress 0xc2e1e3f4
address _harvesterAddress
setMaxSlippage 0x43f68a49
uint256 _maxSlippage
setPTokenAddress 0x0ed57b3a
address _asset
address _pToken
setRewardTokenAddresses 0x96d538bb
address[] _rewardTokenAddresses
transferGovernance 0xd38bfff4
address _newGovernor
transferToken 0x1072cbea
address _asset
uint256 _amount
withdraw 0xd9caed12
address _recipient
address _hardAsset
uint256 _amount
withdrawAll 0x853828b6
No parameters

Recent Transactions

No transactions found for this address