Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0x3Fa73f1E5d8A792C80F426fc8F84FBF7Ce9bBCAC
Balance 0 ETH
Nonce 1
Code Size 21952 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

21952 bytes
0x608060405234801561001057600080fd5b50600436106103a45760003560e01c8063829965cc116101e9578063c00007b01161010f578063dc01f60d116100ad578063f2fde38b1161007c578063f2fde38b146109b0578063f8261597146109c3578063f9f92be4146109d6578063fc0e74d1146109f957600080fd5b8063dc01f60d14610937578063e432488d14610957578063f1127ed814610960578063f12297771461099d57600080fd5b8063ca5c7b91116100e9578063ca5c7b9114610900578063cc6df13814610909578063d336ecfb1461091c578063db2e21bc1461092f57600080fd5b8063c00007b0146108ae578063c1009f4b146108c1578063c6b61e4c146108c957600080fd5b806396ce079511610187578063ae8d482511610156578063ae8d48251461082f578063b53a6a7114610856578063b79c030314610876578063bf86d690146108a157600080fd5b806396ce0795146107f75780639ab24eb0146108005780639bdc746714610813578063aa33fedb1461081c57600080fd5b80638980f11f116101c35780638980f11f146107b85780638da5cb5b146107cb5780638e539e8c146107dc57806395d89b41146107ef57600080fd5b8063829965cc146107955780638757b15b1461079d578063887c7dc5146107a557600080fd5b8063587cde1e116102ce5780637050ccd91161026c57806372f702f31161023b57806372f702f3146106d5578063768e5b27146106fc5780637bb7bed11461075b57806382480df91461076e57600080fd5b80637050ccd91461069457806370a08231146106a757806370b36d79146106ba578063715018a6146106cd57600080fd5b806363f1c8e2116102a857806363f1c8e21461063d5780636724c910146106505780636c8bcee8146106635780636fcfff451461066c57600080fd5b8063587cde1e146105d35780635c19a95c14610617578063638634ee1461062a57600080fd5b8063282d3fdf1161034657806339fc97131161031557806339fc9713146104e95780633a46b1a81461052757806340b47e1a1461053a57806348e5d9f81461054d57600080fd5b8063282d3fdf14610488578063312ff8391461049b578063313ce567146104ae578063386a9525146104df57600080fd5b806306fdde031161038257806306fdde03146103fc57806318160ddd146104115780631c6073951461041957806327e235e31461042c57600080fd5b806304554443146103a95780630483a7f6146103c457806304d0c2c5146103e7575b600080fd5b6103b1610a01565b6040519081526020015b60405180910390f35b6103d76103d2366004615009565b610a12565b6040516103bb9493929190615024565b6103fa6103f536600461509a565b610c08565b005b610404610ed9565b6040516103bb91906150f0565b6103b1610f6b565b6103b1610427366004615123565b610f7e565b61046461043a366004615009565b6009602052600090815260409020546001600160701b03811690600160701b900463ffffffff1682565b604080516001600160701b03909316835263ffffffff9091166020830152016103bb565b6103fa61049636600461509a565b611108565b6103fa6104a936600461515d565b611352565b60405160ff7f00000000000000000000000000000000000000000000000000000000000000121681526020016103bb565b6103b162093a8081565b6105176104f736600461517a565b600560209081526000928352604080842090915290825290205460ff1681565b60405190151581526020016103bb565b6103b161053536600461509a565b6113c2565b6103fa61054836600461517a565b6114ff565b61059c61055b366004615009565b60046020526000908152604090205463ffffffff808216916401000000008104909116906001600160601b03600160401b8204811691600160a01b90041684565b6040805163ffffffff95861681529490931660208501526001600160601b03918216928401929092521660608201526080016103bb565b6105ff6105e1366004615009565b6001600160a01b039081166000908152600b60205260409020541690565b6040516001600160a01b0390911681526020016103bb565b6103fa610625366004615009565b611760565b6103b1610638366004615009565b611b1a565b6103fa61064b3660046151a4565b611b42565b6103fa61065e3660046151c6565b611c87565b6103b161033e81565b61067f61067a366004615009565b611d8e565b60405163ffffffff90911681526020016103bb565b6103fa6106a236600461520d565b611db0565b6103b16106b5366004615009565b61219a565b6103b16106c8366004615244565b6121ae565b6103fa612316565b6105ff7f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf81565b61073b61070a36600461517a565b60066020908152600092835260408084209091529082529020546001600160801b0380821691600160801b90041682565b604080516001600160801b039384168152929091166020830152016103bb565b6105ff610769366004615244565b61237c565b6105ff7f000000000000000000000000616e8bfa43f920657b3497dbf40d6b1a02d4608d81565b6008546103b1565b6103fa6123a6565b6103fa6107b3366004615009565b612451565b6103fa6107c636600461509a565b6124d0565b6001546001600160a01b03166105ff565b6103b16107ea366004615244565b612685565b6104046126e2565b6103b161271081565b6103b161080e366004615009565b6126f1565b6103b1600f5481565b61046461082a36600461509a565b6126fd565b6105ff7f0000000000000000000000005e5ea2048475854a5702f5b8468a51ba1296efcc81565b6103b1610864366004615009565b60036020526000908152604090205481565b6103b161088436600461509a565b600d60209081526000928352604080842090915290825290205481565b6011546105179060ff1681565b6103fa6108bc366004615009565b612743565b6103fa612751565b6108dc6108d7366004615244565b612759565b604080516001600160e01b03909316835263ffffffff9091166020830152016103bb565b6103b160075481565b6103fa61091736600461520d565b612791565b6103fa61092a36600461525d565b61289e565b6103fa612c1c565b61094a610945366004615009565b612e78565b6040516103bb91906152e3565b6103b160105481565b61097361096e36600461533b565b612fb7565b6040805182516001600160e01b0316815260209283015163ffffffff1692810192909252016103bb565b6103b16109ab366004615009565b61303a565b6103fa6109be366004615009565b613045565b6103b16109d1366004615244565b613124565b6105176109e4366004615009565b600e6020526000908152604090205460ff1681565b6103fa613168565b610a0f62093a806011615386565b81565b6001600160a01b0381166000908152600a6020908152604080832060099092528220805483928392606092600160701b900463ffffffff1684815b8454811015610bf05742858281548110610a6957610a696153a5565b600091825260209091200154600160701b900463ffffffff161115610baa5781610afb578454610a9a9082906153bb565b67ffffffffffffffff811115610ab257610ab26153d2565b604051908082528060200260200182016040528015610af757816020015b6040805180820190915260008082526020820152815260200190600190039081610ad05790505b5095505b848181548110610b0d57610b0d6153a5565b6000918252602091829020604080518082019091529101546001600160701b0381168252600160701b900463ffffffff16918101919091528651879084908110610b5957610b596153a5565b60200260200101819052508180610b6f906153e8565b925050610ba3858281548110610b8757610b876153a5565b60009182526020909120015488906001600160701b0316613219565b9650610bde565b610bdb858281548110610bbf57610bbf6153a5565b60009182526020909120015489906001600160701b0316613219565b97505b80610be8816153e8565b915050610a4d565b505090546001600160701b0316955050509193509193565b60026000541415610c605760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b600260009081556001600160a01b038316815260056020908152604080832033845290915290205460ff16610cd75760405162461bcd60e51b815260206004820152600b60248201527f21617574686f72697a65640000000000000000000000000000000000000000006044820152606401610c57565b60008111610d275760405162461bcd60e51b815260206004820152600960248201527f4e6f2072657761726400000000000000000000000000000000000000000000006044820152606401610c57565b6001600160a01b038216600081815260046020526040902090610d4c90333085613225565b6001600160a01b038316600090815260036020526040902054610d70908390613219565b91506a084595161401484a0000008210610dcc5760405162461bcd60e51b815260206004820152600860248201527f21726577617264730000000000000000000000000000000000000000000000006044820152606401610c57565b805463ffffffff164210610e0357610de483836132ae565b506001600160a01b038216600090815260036020526040812055610ed0565b6000610e3e610e29610e1762093a806136b1565b845463ffffffff908116919061370b16565b63ffffffff164261371790919063ffffffff16565b8254909150600090610e61908390600160401b90046001600160601b0316615386565b90506000610e7b85610e75846103e861320d565b906131fa565b905061033e811015610eaf57610e9186866132ae565b6001600160a01b038616600090815260036020526040812055610ecb565b6001600160a01b03861660009081526003602052604090208590555b505050505b50506001600055565b606060128054610ee890615403565b80601f0160208091040260200160405190810160405280929190818152602001828054610f1490615403565b8015610f615780601f10610f3657610100808354040283529160200191610f61565b820191906000526020600020905b815481529060010190602001808311610f4457829003601f168201915b5050505050905090565b6000610f796106c842613124565b905090565b600080610fc8610f918562093a8061320d565b6008600081548110610fa557610fa56153a5565b60009182526020909120015463ffffffff600160e01b9091048116919061321916565b90504281106110195760405162461bcd60e51b815260206004820152601660248201527f45706f636820697320696e2074686520667574757265000000000000000000006044820152606401610c57565b600061103361102c62093a806011615386565b8390613717565b6001600160a01b0385166000908152600a60205260409020805491925090805b80156110fc5760006110ab61106c62093a806011615386565b856110786001866153bb565b81548110611088576110886153a5565b60009182526020909120015463ffffffff600160701b9091048116919061371716565b9050858110156110e957848111156110e3576110dc846110cc6001856153bb565b81548110610b8757610b876153a5565b96506110e9565b506110fc565b50806110f48161543e565b915050611053565b50505050505b92915050565b6002600054141561115b5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b600260008181556001600160a01b038416815260096020526040812091548492915b818110156113055760006002828154811061119a5761119a6153a5565b60009182526020822001546001600160a01b031691506111b982613723565b90506111c4816137f4565b6001600160a01b03808416600090815260046020526040902080546001600160601b0393909316600160a01b0291831682179055611215916112109163ffffffff90811691161761384d565b6136b1565b6001600160a01b038084166000908152600460205260409020805463ffffffff939093166401000000000267ffffffff0000000019909316929092179091558616156112f057604051806040016040528061126f83613859565b6001600160801b0316815286546020909101906112a19061129c908a9087906001600160701b03166138b2565b613859565b6001600160801b039081169091526001600160a01b0380891660009081526006602090815260408083209388168352928152919020835193909101518216600160801b02929091169190911790555b505080806112fd906153e8565b91505061117d565b5061133e9150506001600160a01b037f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf16333085613225565b611348838361393c565b5050600160005550565b600260005414156113a55760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b60026000819055506113ba3382336000613e0b565b506001600055565b6000428211156114145760405162461bcd60e51b815260206004820152601f60248201527f4552433230566f7465733a20626c6f636b206e6f7420796574206d696e6564006044820152606401610c57565b600061142d62093a8061142785826131fa565b9061320d565b6001600160a01b0385166000908152600c60205260408120919250906114539083614518565b80516001600160e01b03169350905082158061149157508161147962093a806011615386565b826020015163ffffffff1661148e9190615455565b11155b156114a157600092505050611102565b806020015163ffffffff168211156114f7576001600160a01b0385166000908152600d602090815260408083208584529091529020546114e190846153bb565b92506114f062093a80836153bb565b91506114a1565b505092915050565b6001546001600160a01b031633146115595760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b6001600160a01b038216600090815260046020526040902054640100000000900463ffffffff16156115cd5760405162461bcd60e51b815260206004820152601560248201527f52657761726420616c72656164792065786973747300000000000000000000006044820152606401610c57565b7f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf6001600160a01b0316826001600160a01b031614156116595760405162461bcd60e51b815260206004820152602160248201527f43616e6e6f7420616464205374616b696e67546f6b656e2061732072657761726044820152601960fa1b6064820152608401610c57565b6002546005116116ab5760405162461bcd60e51b815260206004820152601260248201527f4d61782072657761726473206c656e67746800000000000000000000000000006044820152606401610c57565b6002805460018082019092557f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace01805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039485169081179091556000908152600460209081526040808320805467ffffffffffffffff19166401000000004263ffffffff1690810263ffffffff1916919091171790556005825280832094909516825292909252919020805460ff19169091179055565b600260005414156117b35760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b60026000908155338152600a602052604090208054806118155760405162461bcd60e51b815260206004820152601360248201527f4e6f7468696e6720746f2064656c6567617465000000000000000000000000006044820152606401610c57565b6001600160a01b03831661186b5760405162461bcd60e51b815260206004820152601860248201527f4d7573742064656c656761746520746f20736f6d656f6e6500000000000000006044820152606401610c57565b336000908152600b60205260409020546001600160a01b039081169084168114156118d85760405162461bcd60e51b815260206004820152601960248201527f4d7573742063686f6f7365206e65772064656c656761746565000000000000006044820152606401610c57565b336000818152600b6020526040808220805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03898116918217909255915191939085169290917f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f9190a4600061195762093a8061142781610e754282613219565b905060006119666001856153bb565b905060008086838154811061197d5761197d6153a5565b6000918252602091829020604080518082019091529101546001600160701b0381168252600160701b900463ffffffff169181019190915290505b83816020015163ffffffff161115611af35780516119df906001600160701b031683615455565b91506001600160a01b03851615611a405780516001600160a01b0386166000908152600d602090815260408083208286015163ffffffff168452909152812080546001600160701b0390931692909190611a3a9084906153bb565b90915550505b80516001600160a01b0389166000908152600d602090815260408083208286015163ffffffff168452909152812080546001600160701b0390931692909190611a8a908490615455565b90915550508215611af35782611a9f8161543e565b935050868381548110611ab457611ab46153a5565b6000918252602091829020604080518082019091529101546001600160701b0381168252600160701b900463ffffffff169181019190915290506119b8565b611aff85600084614611565b611b0b88836000614611565b50506001600055505050505050565b6001600160a01b0381166000908152600460205260408120546111029063ffffffff1661384d565b6001546001600160a01b03163314611b9c5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b6101f4821115611bee5760405162461bcd60e51b815260206004820152600d60248201527f6f766572206d61782072617465000000000000000000000000000000000000006044820152606401610c57565b6002811015611c3f5760405162461bcd60e51b815260206004820152600960248201527f6d696e2064656c617900000000000000000000000000000000000000000000006044820152606401610c57565b600f829055601081905560408051838152602081018390527fd30002df16c56a92fd27e996833a22a5aff31b85a1a25107b16dfff3ca2d869c91015b60405180910390a15050565b6001546001600160a01b03163314611ce15760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b6001600160a01b038316600090815260046020526040902054640100000000900463ffffffff16611d545760405162461bcd60e51b815260206004820152601560248201527f52657761726420646f6573206e6f7420657869737400000000000000000000006044820152606401610c57565b6001600160a01b03928316600090815260056020908152604080832094909516825292909252919020805460ff1916911515919091179055565b6001600160a01b0381166000908152600c6020526040812054611102906136b1565b60026000541415611e035760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b600260008181556001600160a01b038416815260096020526040812091548492915b81811015611fa357600060028281548110611e4257611e426153a5565b60009182526020822001546001600160a01b03169150611e6182613723565b9050611e6c816137f4565b6001600160a01b03808416600090815260046020526040902080546001600160601b0393909316600160a01b0291831682179055611eb8916112109163ffffffff90811691161761384d565b6001600160a01b038084166000908152600460205260409020805463ffffffff939093166401000000000267ffffffff000000001990931692909217909155861615611f8e576040518060400160405280611f1283613859565b6001600160801b031681528654602090910190611f3f9061129c908a9087906001600160701b03166138b2565b6001600160801b039081169091526001600160a01b0380891660009081526006602090815260408083209388168352928152919020835193909101518216600160801b02929091169190911790555b50508080611f9b906153e8565b915050611e25565b5050600254905060005b8181101561218e57600060028281548110611fca57611fca6153a5565b60009182526020808320909101546001600160a01b038981168452600683526040808520919092168085529252909120549091506001600160801b03600160801b909104168015612179576001600160a01b038088166000908152600660209081526040808320868516808552925290912080546001600160801b031690557f000000000000000000000000616e8bfa43f920657b3497dbf40d6b1a02d4608d9091161480156120775750855b801561208b57506001600160a01b03871633145b15612117576040516305dc812160e31b81526001600160a01b038881166004830152602482018390527f0000000000000000000000005e5ea2048475854a5702f5b8468a51ba1296efcc1690632ee4090890604401600060405180830381600087803b1580156120fa57600080fd5b505af115801561210e573d6000803e3d6000fd5b5050505061212b565b61212b6001600160a01b03831688836149a5565b816001600160a01b0316876001600160a01b03167f540798df468d7b23d11f156fdb954cb19ad414d150722a7b6d55ba369dea792e8360405161217091815260200190565b60405180910390a35b50508080612186906153e8565b915050611fad565b50506001600055505050565b60006111026121a842613124565b83610f7e565b6000806121c1610f918462093a8061320d565b90504281106122125760405162461bcd60e51b815260206004820152601660248201527f45706f636820697320696e2074686520667574757265000000000000000000006044820152606401610c57565b600061222561102c62093a806011615386565b60085490915060009061223a906001906153bb565b9050600081861161224b578561224d565b815b9050600061225c826001615455565b90505b801561230c57600060086122746001846153bb565b81548110612284576122846153a5565b6000918252602091829020604080518082019091529101546001600160e01b0381168252600160e01b900463ffffffff1691810182905291508614156122ca57506122fa565b84816020015163ffffffff16116122e1575061230c565b80516122f6906001600160e01b031688615455565b9650505b806123048161543e565b91505061225f565b5050505050919050565b6001546001600160a01b031633146123705760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b61237a60006149d5565b565b6002818154811061238c57600080fd5b6000918252602090912001546001600160a01b0316905081565b6123fb6001600160a01b037f000000000000000000000000616e8bfa43f920657b3497dbf40d6b1a02d4608d167f0000000000000000000000005e5ea2048475854a5702f5b8468a51ba1296efcc6000614a34565b61237a6001600160a01b037f000000000000000000000000616e8bfa43f920657b3497dbf40d6b1a02d4608d167f0000000000000000000000005e5ea2048475854a5702f5b8468a51ba1296efcc600019614a34565b600260005414156124a45760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b60026000819055506113ba816000336124cb60105462093a8061320d90919063ffffffff16565b613e0b565b6001546001600160a01b0316331461252a5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b7f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf6001600160a01b0316826001600160a01b031614156125ac5760405162461bcd60e51b815260206004820152601d60248201527f43616e6e6f74207769746864726177207374616b696e6720746f6b656e0000006044820152606401610c57565b6001600160a01b038216600090815260046020526040902054640100000000900463ffffffff16156126205760405162461bcd60e51b815260206004820152601c60248201527f43616e6e6f742077697468647261772072657761726420746f6b656e000000006044820152606401610c57565b6126466126356001546001600160a01b031690565b6001600160a01b03841690836149a5565b604080516001600160a01b0384168152602081018390527f8c1256b8896378cd5044f80c202f9772b9d77dc85c8a6eb51967210b09bfaa289101611c7b565b60004282106126d65760405162461bcd60e51b815260206004820152601f60248201527f4552433230566f7465733a20626c6f636b206e6f7420796574206d696e6564006044820152606401610c57565b6111026106c883613124565b606060138054610ee890615403565b600061110282426113c2565b600a602052816000526040600020818154811061271957600080fd5b6000918252602090912001546001600160701b0381169250600160701b900463ffffffff16905082565b61274e816000611db0565b50565b61237a614b50565b6008818154811061276957600080fd5b6000918252602090912001546001600160e01b0381169150600160e01b900463ffffffff1682565b6001546001600160a01b031633146127eb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b813b8061283a5760405162461bcd60e51b815260206004820152601060248201527f4d75737420626520636f6e7472616374000000000000000000000000000000006044820152606401610c57565b6001600160a01b0383166000818152600e6020908152604091829020805460ff19168615159081179091558251938452908301527f2b7046b0c3f1d2cfa561874048b25b501ea267e88ea19420c5509b4aba05831d910160405180910390a1505050565b600260005414156128f15760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b600260008181556001600160a01b038516815260096020526040812091548592915b81811015612a9157600060028281548110612930576129306153a5565b60009182526020822001546001600160a01b0316915061294f82613723565b905061295a816137f4565b6001600160a01b03808416600090815260046020526040902080546001600160601b0393909316600160a01b02918316821790556129a6916112109163ffffffff90811691161761384d565b6001600160a01b038084166000908152600460205260409020805463ffffffff939093166401000000000267ffffffff000000001990931692909217909155861615612a7c576040518060400160405280612a0083613859565b6001600160801b031681528654602090910190612a2d9061129c908a9087906001600160701b03166138b2565b6001600160801b039081169091526001600160a01b0380891660009081526006602090815260408083209388168352928152919020835193909101518216600160801b02929091169190911790555b50508080612a89906153e8565b915050612913565b50506002549050828114612ad05760405162461bcd60e51b8152600401610c579060208082526004908201526310b0b93960e11b604082015260600190565b60005b81811015612c0f57848482818110612aed57612aed6153a5565b9050602002016020810190612b02919061515d565b15612b0c57612bfd565b600060028281548110612b2157612b216153a5565b60009182526020808320909101546001600160a01b038a81168452600683526040808520919092168085529252909120549091506001600160801b03600160801b909104168015612bfa576001600160a01b03808916600090815260066020908152604080832093861680845293909152902080546001600160801b03169055612bac9089836149a5565b816001600160a01b0316886001600160a01b03167f540798df468d7b23d11f156fdb954cb19ad414d150722a7b6d55ba369dea792e83604051612bf191815260200190565b60405180910390a35b50505b80612c07816153e8565b915050612ad3565b5050600160005550505050565b60026000541415612c6f5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610c57565b600260005560115460ff16612cc65760405162461bcd60e51b815260206004820152601060248201527f4d7573742062652073687574646f776e000000000000000000000000000000006044820152606401610c57565b336000908152600a6020908152604080832080548251818502810185019093528083529192909190849084015b82821015612d3f57600084815260209081902060408051808201909152908401546001600160701b0381168252600160701b900463ffffffff1681830152825260019092019101612cf3565b50503360009081526009602052604090208054939450926001600160701b031691505080612daf5760405162461bcd60e51b815260206004820152600e60248201527f4e6f7468696e67206c6f636b65640000000000000000000000000000000000006044820152606401610c57565b81546dffffffffffffffffffffffffffff191682558251612dcf906136b1565b825463ffffffff91909116600160701b0263ffffffff60701b1990911617825560078054829190600090612e049084906153bb565b9091555050604080518281526000602082015233917f2fd83d5e9f5d240bed47a97a24cf354e4047e25edc2da27b01fd95e5e8a0c9a5910160405180910390a26113486001600160a01b037f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf1633836149a5565b60025460609067ffffffffffffffff811115612e9657612e966153d2565b604051908082528060200260200182016040528015612edb57816020015b6040805180820190915260008082526020820152815260200190600190039081612eb45790505b506001600160a01b0383166000908152600960205260408120825192935091905b81811015612faf57600060028281548110612f1957612f196153a5565b9060005260206000200160009054906101000a90046001600160a01b0316905080858381518110612f4c57612f4c6153a5565b60209081029190910101516001600160a01b0390911690528354612f7c90879083906001600160701b03166138b2565b858381518110612f8e57612f8e6153a5565b60209081029190910181015101525080612fa7816153e8565b915050612efc565b505050919050565b60408051808201909152600080825260208201526001600160a01b0383166000908152600c60205260409020805463ffffffff8416908110612ffb57612ffb6153a5565b6000918252602091829020604080518082019091529101546001600160e01b0381168252600160e01b900463ffffffff16918101919091529392505050565b600061110282613723565b6001546001600160a01b0316331461309f5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b6001600160a01b03811661311b5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152608401610c57565b61274e816149d5565b600061110262093a80610e756008600081548110613144576131446153a5565b600091825260209091200154859063ffffffff600160e01b90910481169061371716565b6001546001600160a01b031633146131c25760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610c57565b6011805460ff191660011790556040517f4426aa1fb73e391071491fcfe21a88b5c38a0a0333a1f6e77161470439704cf890600090a1565b60006132068284615483565b9392505050565b60006132068284615386565b60006132068284615455565b6040516001600160a01b03808516602483015283166044820152606481018290526132a89085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03167fffffffff0000000000000000000000000000000000000000000000000000000090931692909217909152614c36565b50505050565b600080805260096020526002547fec8156718a8372b1db44bb411437d0870f3e3790d4a08526d024ce1b0b668f6b90825b8181101561345d576000600282815481106132fc576132fc6153a5565b60009182526020822001546001600160a01b0316915061331b82613723565b9050613326816137f4565b6001600160a01b03808416600090815260046020526040902080546001600160601b0393909316600160a01b0291831682179055613372916112109163ffffffff90811691161761384d565b6001600160a01b038084166000908152600460205260409020805463ffffffff939093166401000000000267ffffffff0000000019909316929092179091558616156134485760405180604001604052806133cc83613859565b6001600160801b0316815286546020909101906133f99061129c908a9087906001600160701b03166138b2565b6001600160801b039081169091526001600160a01b0380891660009081526006602090815260408083209388168352928152919020835193909101518216600160801b02929091169190911790555b50508080613455906153e8565b9150506132df565b5050506001600160a01b0383166000908152600460205260409020805463ffffffff1642106134d05761349b6134968462093a806131fa565b6137f4565b81546001600160601b0391909116600160401b0273ffffffffffffffffffffffff000000000000000019909116178155613556565b80546000906134ea9063ffffffff90811690429061371716565b825490915060009061350d908390600160401b90046001600160601b031661320d565b905061352361349662093a80610e758885613219565b83546001600160601b0391909116600160401b0273ffffffffffffffffffffffff00000000000000001990911617835550505b805468056bc75e2d63100000600160401b9091046001600160601b0316106135c05760405162461bcd60e51b815260206004820152600b60248201527f21726577617264526174650000000000000000000000000000000000000000006044820152606401610c57565b68056bc75e2d63100000600754101561361b5760405162461bcd60e51b815260206004820152600860248201527f2162616c616e63650000000000000000000000000000000000000000000000006044820152606401610c57565b613624426136b1565b815467ffffffff00000000191664010000000063ffffffff928316021782556136589061121090429062093a809061321916565b815463ffffffff191663ffffffff919091161781556040518381526001600160a01b038516907fac24935fd910bc682b5ccb1a07b718cadf8cf2f6d1404c4f3ddc3662dae40e299060200160405180910390a250505050565b600063ffffffff8211156137075760405162461bcd60e51b815260206004820152601960248201527f417572614d6174683a2075696e743332204f766572666c6f77000000000000006044820152606401610c57565b5090565b60006132068284615497565b600061320682846153bb565b60006007546000141561375c57506001600160a01b0316600090815260046020526040902054600160a01b90046001600160601b031690565b6007546001600160a01b038316600090815260046020526040902054611102916137c591610e7590670de0b6b3a764000090611427906001600160601b03600160401b82041690829063ffffffff64010000000082048116916137bf911661384d565b90613717565b6001600160a01b038416600090815260046020526040902054600160a01b90046001600160601b031690613219565b60006001600160601b038211156137075760405162461bcd60e51b815260206004820152601960248201527f417572614d6174683a2075696e743936204f766572666c6f77000000000000006044820152606401610c57565b60006111024283614d1b565b60006001600160801b038211156137075760405162461bcd60e51b815260206004820152601a60248201527f417572614d6174683a2075696e74313238204f766572666c6f770000000000006044820152606401610c57565b6001600160a01b03808416600090815260066020908152604080832093861683529281528282208351808501909452546001600160801b03808216808652600160801b90920416918401829052919291613933919061392d90670de0b6b3a764000090610e7590613926906137bf8b613723565b889061320d565b90613219565b95945050505050565b336000818152600e6020526040902054839060ff161561398c5760405162461bcd60e51b815260206004820152600b60248201526a189b1858dadb1a5cdd195960aa1b6044820152606401610c57565b806001600160a01b0316826001600160a01b0316146139fc576001600160a01b0381166000908152600e602052604090205460ff16156139fc5760405162461bcd60e51b815260206004820152600b60248201526a189b1858dadb1a5cdd195960aa1b6044820152606401610c57565b60008311613a4c5760405162461bcd60e51b815260206004820152600e60248201527f43616e6e6f74207374616b6520300000000000000000000000000000000000006044820152606401610c57565b60115460ff1615613a9f5760405162461bcd60e51b815260206004820152600860248201527f73687574646f776e0000000000000000000000000000000000000000000000006044820152606401610c57565b6001600160a01b0384166000908152600960205260409020613abf614b50565b6000613aca85614d31565b8254909150613ae2906001600160701b031682614d8a565b82546dffffffffffffffffffffffffffff19166001600160701b0391909116178255600754613b119086613219565b6007556000613b2762093a8061142742826131fa565b90506000613b43613b3c62093a806011615386565b8390613219565b6001600160a01b0389166000908152600a6020526040902054909150801580613bb757506001600160a01b0389166000908152600a602052604090208290613b8c6001846153bb565b81548110613b9c57613b9c6153a5565b600091825260209091200154600160701b900463ffffffff16105b15613c3e576001600160a01b0389166000908152600a6020908152604080832081518083019092526001600160701b03808916835263ffffffff80881684860190815283546001810185559387529490952092519290910180549351909416600160701b0271ffffffffffffffffffffffffffffffffffff19909316911617179055613cb7565b6001600160a01b0389166000908152600a60205260408120613c616001846153bb565b81548110613c7157613c716153a5565b60009182526020909120018054909150613c94906001600160701b031686614d8a565b81546dffffffffffffffffffffffffffff19166001600160701b03919091161790555b6001600160a01b038981166000908152600b6020526040902054168015613d2f576001600160a01b0381166000908152600d60209081526040808320868452909152812080546001600160701b0388169290613d14908490615455565b90915550613d2f9050816001600160701b0387166000614611565b6008805460009190613d43906001906153bb565b81548110613d5357613d536153a5565b60009182526020909120018054909150613d7f906001600160e01b03166001600160701b038816614d96565b81547fffffffff00000000000000000000000000000000000000000000000000000000166001600160e01b0391909116178155604080516001600160701b03881680825260208201526001600160a01b038d16917f1449c6dd7851abc30abf37f57715f492010519147cc2652fbc38202c18a6ee90910160405180910390a25050505050505050505050565b6001600160a01b038416600090815260096020526040812060025486925b81811015613fa757600060028281548110613e4657613e466153a5565b60009182526020822001546001600160a01b03169150613e6582613723565b9050613e70816137f4565b6001600160a01b03808416600090815260046020526040902080546001600160601b0393909316600160a01b0291831682179055613ebc916112109163ffffffff90811691161761384d565b6001600160a01b038084166000908152600460205260409020805463ffffffff939093166401000000000267ffffffff000000001990931692909217909155861615613f92576040518060400160405280613f1683613859565b6001600160801b031681528654602090910190613f439061129c908a9087906001600160701b03166138b2565b6001600160801b039081169091526001600160a01b0380891660009081526006602090815260408083209388168352928152919020835193909101518216600160801b02929091169190911790555b50508080613f9f906153e8565b915050613e29565b5050506001600160a01b0385166000908152600a6020908152604080832060099092528220815491929091818087158015613fdf5750895b613ff257613fed4289613717565b613fff565b613fff4262093a80613219565b9050600083116140515760405162461bcd60e51b815260206004820152600860248201527f6e6f206c6f636b730000000000000000000000000000000000000000000000006044820152606401610c57565b60115460ff16806140965750808661406a6001866153bb565b8154811061407a5761407a6153a5565b600091825260209091200154600160701b900463ffffffff1611155b156141885784546001600160701b031693506140b1836136b1565b855463ffffffff91909116600160701b0263ffffffff60701b1990911617855587156141835760006140ee62093a8061142781610e75428e613717565b9050600061413c62093a80610e758a61410860018a6153bb565b81548110614118576141186153a5565b600091825260209091200154859063ffffffff600160701b90910481169061371716565b9050600061416261415a614151846001615455565b600f549061320d565b612710614d1b565b905061417d612710610e756001600160701b038a168461320d565b94505050505b6142f5565b8454600160701b900463ffffffff16805b848110156142d457828882815481106141b4576141b46153a5565b600091825260209091200154600160701b900463ffffffff1611156141d8576142d4565b61420b8882815481106141ed576141ed6153a5565b6000918252602090912001546001600160701b038881169116614d8a565b955089156142b457600061423662093a8061142762093a80610e758f4261371790919063ffffffff16565b9050600061425662093a80610e758c8681548110614118576141186153a5565b9050600061426b61415a614151846001615455565b90506142ae6142a7612710610e75848f898154811061428c5761428c6153a5565b6000918252602090912001546001600160701b03169061320d565b8890613219565b96505050505b816142be816154bc565b92505080806142cc906153e8565b915050614199565b50855463ffffffff909116600160701b0263ffffffff60701b199091161785555b6000846001600160701b03161161434e5760405162461bcd60e51b815260206004820152600c60248201527f6e6f20657870206c6f636b7300000000000000000000000000000000000000006044820152606401610c57565b8454614363906001600160701b031685614da2565b85546dffffffffffffffffffffffffffff19166001600160701b03918216178655600754614392918616613717565b6007556001600160a01b03808c166000908152600b60205260409020546143bc9116600080614611565b604080516001600160701b03861681528b151560208201526001600160a01b038d16917f2fd83d5e9f5d240bed47a97a24cf354e4047e25edc2da27b01fd95e5e8a0c9a5910160405180910390a281156144b05761442c61441c83614d31565b6001600160701b03861690614da2565b93506144626001600160a01b037f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf168a846149a5565b8a6001600160a01b0316896001600160a01b03167f7e7ff29ed04cfb223bc9b02606f69520517c117ee82c9158ed2d96323c1ef385846040516144a791815260200190565b60405180910390a35b89156144ce576144c98b856001600160701b031661393c565b61450b565b61450b6001600160a01b037f000000000000000000000000c0c293ce456ff0ed870add98a0828dd4d2903dbf168c6001600160701b0387166149a5565b5050505050505050505050565b6040805180820190915260008082526020820152825460005b818110156145955760006145458284614dae565b90508486828154811061455a5761455a6153a5565b600091825260209091200154600160e01b900463ffffffff1611156145815780925061458f565b61458c816001615455565b91505b50614531565b81156145f457846145a76001846153bb565b815481106145b7576145b76153a5565b6000918252602091829020604080518082019091529101546001600160e01b0381168252600160e01b900463ffffffff1691810191909152613933565b604080518082019091526000808252602082015295945050505050565b6001600160a01b038316156149a057600061463762093a8061142781610e754282613219565b6001600160a01b0385166000908152600c60205260409020805491925090156148f6578054600090829061466d906001906153bb565b8154811061467d5761467d6153a5565b6000918252602091829020604080518082019091529101546001600160e01b0381168252600160e01b900463ffffffff1691810182905291508314156147685760405180604001604052806146f4868885600001516001600160e01b03166146e59190615455565b6146ef91906153bb565b614e05565b6001600160e01b0316815260200161470b856136b1565b63ffffffff16905282548390614723906001906153bb565b81548110614733576147336153a5565b60009182526020918290208351939092015163ffffffff16600160e01b026001600160e01b03909316929092179101556148f0565b8261477762093a806011615386565b826020015163ffffffff1661478c9190615455565b11614808578160405180604001604052806147ac87896146ef91906153bb565b6001600160e01b031681526020016147c3866136b1565b63ffffffff9081169091528254600181018455600093845260209384902083519490930151909116600160e01b026001600160e01b03909316929092179101556148f0565b8260005b826020015163ffffffff16821115614862576001600160a01b0388166000908152600d6020908152604080832085845290915290205461484c9082615455565b905061485b62093a80836153bb565b915061480c565b836040518060400160405280614896898b8689600001516001600160e01b031661488c91906153bb565b6146e59190615455565b6001600160e01b031681526020016148ad886136b1565b63ffffffff9081169091528254600181018455600093845260209384902083519490930151909116600160e01b026001600160e01b039093169290921791015550505b50614969565b80604051806040016040528061491186886146ef91906153bb565b6001600160e01b03168152602001614928856136b1565b63ffffffff9081169091528254600181018455600093845260209384902083519490930151909116600160e01b026001600160e01b03909316929092179101555b6040516001600160a01b038616907fa22dbba24a42408e4f1f7e04365c239a252db5a744bd64f75830a9d691b1992190600090a250505b505050565b6040516001600160a01b0383166024820152604481018290526149a090849063a9059cbb60e01b90606401613259565b600180546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b801580614aae5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015614a88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614aac91906154e0565b155b614b205760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527f20746f206e6f6e2d7a65726f20616c6c6f77616e6365000000000000000000006064820152608401610c57565b6040516001600160a01b0383166024820152604481018290526149a090849063095ea7b360e01b90606401613259565b6000614b6362093a8061142742826131fa565b60088054919250600091614b79906001906153bb565b81548110614b8957614b896153a5565b600091825260209091200154600160e01b900463ffffffff16905081811015614c32575b818114614c3257614bc18162093a80613219565b60408051808201909152600080825263ffffffff808416602084019081526008805460018101825593529251925116600160e01b026001600160e01b0392909216919091177ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3909101559050614bad565b5050565b6000614c8b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614e5e9092919063ffffffff16565b8051909150156149a05780806020019051810190614ca991906154f9565b6149a05760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610c57565b6000818310614d2a5781613206565b5090919050565b60006001600160701b038211156137075760405162461bcd60e51b815260206004820152601a60248201527f417572614d6174683a2075696e74313132204f766572666c6f770000000000006044820152606401610c57565b60006132068284615516565b60006132068284615541565b60006132068284615563565b60006002614dbc8184615583565b614dc7600286615583565b614dd19190615455565b614ddb9190615483565b614de6600284615483565b614df1600286615483565b614dfb9190615455565b6132069190615455565b60006001600160e01b038211156137075760405162461bcd60e51b815260206004820152601a60248201527f417572614d6174683a2075696e74323234204f766572666c6f770000000000006044820152606401610c57565b6060614e6d8484600085614e75565b949350505050565b606082471015614eed5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c00000000000000000000000000000000000000000000000000006064820152608401610c57565b843b614f3b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610c57565b600080866001600160a01b03168587604051614f579190615597565b60006040518083038185875af1925050503d8060008114614f94576040519150601f19603f3d011682016040523d82523d6000602084013e614f99565b606091505b5091509150614fa9828286614fb4565b979650505050505050565b60608315614fc3575081613206565b825115614fd35782518084602001fd5b8160405162461bcd60e51b8152600401610c5791906150f0565b80356001600160a01b038116811461500457600080fd5b919050565b60006020828403121561501b57600080fd5b61320682614fed565b60006080820186835260208681850152604086818601526080606086015282865180855260a087019150838801945060005b8181101561508a57855180516001600160701b0316845285015163ffffffff16858401529484019491830191600101615056565b50909a9950505050505050505050565b600080604083850312156150ad57600080fd5b6150b683614fed565b946020939093013593505050565b60005b838110156150df5781810151838201526020016150c7565b838111156132a85750506000910152565b602081526000825180602084015261510f8160408501602087016150c4565b601f01601f19169190910160400192915050565b6000806040838503121561513657600080fd5b8235915061514660208401614fed565b90509250929050565b801515811461274e57600080fd5b60006020828403121561516f57600080fd5b81356132068161514f565b6000806040838503121561518d57600080fd5b61519683614fed565b915061514660208401614fed565b600080604083850312156151b757600080fd5b50508035926020909101359150565b6000806000606084860312156151db57600080fd5b6151e484614fed565b92506151f260208501614fed565b915060408401356152028161514f565b809150509250925092565b6000806040838503121561522057600080fd5b61522983614fed565b915060208301356152398161514f565b809150509250929050565b60006020828403121561525657600080fd5b5035919050565b60008060006040848603121561527257600080fd5b61527b84614fed565b9250602084013567ffffffffffffffff8082111561529857600080fd5b818601915086601f8301126152ac57600080fd5b8135818111156152bb57600080fd5b8760208260051b85010111156152d057600080fd5b6020830194508093505050509250925092565b602080825282518282018190526000919060409081850190868401855b8281101561532e57815180516001600160a01b03168552860151868501529284019290850190600101615300565b5091979650505050505050565b6000806040838503121561534e57600080fd5b61535783614fed565b9150602083013563ffffffff8116811461523957600080fd5b634e487b7160e01b600052601160045260246000fd5b60008160001904831182151516156153a0576153a0615370565b500290565b634e487b7160e01b600052603260045260246000fd5b6000828210156153cd576153cd615370565b500390565b634e487b7160e01b600052604160045260246000fd5b60006000198214156153fc576153fc615370565b5060010190565b600181811c9082168061541757607f821691505b6020821081141561543857634e487b7160e01b600052602260045260246000fd5b50919050565b60008161544d5761544d615370565b506000190190565b6000821982111561546857615468615370565b500190565b634e487b7160e01b600052601260045260246000fd5b6000826154925761549261546d565b500490565b600063ffffffff838116908316818110156154b4576154b4615370565b039392505050565b600063ffffffff808316818114156154d6576154d6615370565b6001019392505050565b6000602082840312156154f257600080fd5b5051919050565b60006020828403121561550b57600080fd5b81516132068161514f565b60006001600160701b0380831681851680830382111561553857615538615370565b01949350505050565b60006001600160e01b0380831681851680830382111561553857615538615370565b60006001600160701b03838116908316818110156154b4576154b4615370565b6000826155925761559261546d565b500690565b600082516155a98184602087016150c4565b919091019291505056fea164736f6c634300080b000a

Verified Source Code Partial Match

Compiler: v0.8.11+commit.d7f03943 EVM: london Optimization: Yes (800 runs)
AuraMath.sol 88 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library AuraMath {
    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a + b;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a - b;
    }

    function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a * b;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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, so we distribute.
        return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
    }

    function to224(uint256 a) internal pure returns (uint224 c) {
        require(a <= type(uint224).max, "AuraMath: uint224 Overflow");
        c = uint224(a);
    }

    function to128(uint256 a) internal pure returns (uint128 c) {
        require(a <= type(uint128).max, "AuraMath: uint128 Overflow");
        c = uint128(a);
    }

    function to112(uint256 a) internal pure returns (uint112 c) {
        require(a <= type(uint112).max, "AuraMath: uint112 Overflow");
        c = uint112(a);
    }

    function to96(uint256 a) internal pure returns (uint96 c) {
        require(a <= type(uint96).max, "AuraMath: uint96 Overflow");
        c = uint96(a);
    }

    function to32(uint256 a) internal pure returns (uint32 c) {
        require(a <= type(uint32).max, "AuraMath: uint32 Overflow");
        c = uint32(a);
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library AuraMath32 {
    function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
        c = a - b;
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
library AuraMath112 {
    function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
        c = a + b;
    }

    function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
        c = a - b;
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
library AuraMath224 {
    function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
        c = a + b;
    }
}
AuraLocker.sol 910 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

import { IERC20 } from "@openzeppelin/contracts-0.8/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts-0.8/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts-0.8/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts-0.8/security/ReentrancyGuard.sol";
import { AuraMath, AuraMath32, AuraMath112, AuraMath224 } from "./AuraMath.sol";
import "./Interfaces.sol";

interface IRewardStaking {
    function stakeFor(address, uint256) external;
}

/**
 * @title   AuraLocker
 * @author  ConvexFinance
 * @notice  Effectively allows for rolling 16 week lockups of CVX, and provides balances available
 *          at each epoch (1 week). Also receives cvxCrv from `CvxStakingProxy` and redistributes
 *          to depositors.
 * @dev     Invdividual and delegatee vote power lookups both use independent accounting mechanisms.
 */
contract AuraLocker is ReentrancyGuard, Ownable, IAuraLocker {
    using AuraMath for uint256;
    using AuraMath224 for uint224;
    using AuraMath112 for uint112;
    using AuraMath32 for uint32;
    using SafeERC20 for IERC20;

    /* ==========     STRUCTS     ========== */

    struct RewardData {
        /// Timestamp for current period finish
        uint32 periodFinish;
        /// Last time any user took action
        uint32 lastUpdateTime;
        /// RewardRate for the rest of the period
        uint96 rewardRate;
        /// Ever increasing rewardPerToken rate, based on % of total supply
        uint96 rewardPerTokenStored;
    }
    struct UserData {
        uint128 rewardPerTokenPaid;
        uint128 rewards;
    }
    struct EarnedData {
        address token;
        uint256 amount;
    }
    struct Balances {
        uint112 locked;
        uint32 nextUnlockIndex;
    }
    struct LockedBalance {
        uint112 amount;
        uint32 unlockTime;
    }
    struct Epoch {
        uint224 supply;
        uint32 date; //epoch start date
    }
    struct DelegateeCheckpoint {
        uint224 votes;
        uint32 epochStart;
    }

    /* ========== STATE VARIABLES ========== */

    // Rewards
    address[] public rewardTokens;
    mapping(address => uint256) public queuedRewards;
    uint256 public constant newRewardRatio = 830;
    //     Core reward data
    mapping(address => RewardData) public rewardData;
    //     Reward token -> distributor -> is approved to add rewards
    mapping(address => mapping(address => bool)) public rewardDistributors;
    //     User -> reward token -> amount
    mapping(address => mapping(address => UserData)) public userData;
    //     Duration that rewards are streamed over
    uint256 public constant rewardsDuration = 86400 * 7;
    //     Duration of lock/earned penalty period
    uint256 public constant lockDuration = rewardsDuration * 17;

    // Balances
    //     Supplies and historic supply
    uint256 public lockedSupply;
    //     Epochs contains only the tokens that were locked at that epoch, not a cumulative supply
    Epoch[] public epochs;
    //     Mappings for balance data
    mapping(address => Balances) public balances;
    mapping(address => LockedBalance[]) public userLocks;

    // Voting
    //     Stored delegations
    mapping(address => address) private _delegates;
    //     Checkpointed votes
    mapping(address => DelegateeCheckpoint[]) private _checkpointedVotes;
    //     Delegatee balances (user -> unlock timestamp -> amount)
    mapping(address => mapping(uint256 => uint256)) public delegateeUnlocks;

    // Config
    //     Blacklisted smart contract interactions
    mapping(address => bool) public blacklist;
    //     Tokens
    IERC20 public immutable stakingToken;
    address public immutable cvxCrv;
    //     Denom for calcs
    uint256 public constant denominator = 10000;
    //     Staking cvxCrv
    address public immutable cvxcrvStaking;
    //     Incentives
    uint256 public kickRewardPerEpoch = 100;
    uint256 public kickRewardEpochDelay = 3;
    //     Shutdown
    bool public isShutdown = false;

    // Basic token data
    string private _name;
    string private _symbol;
    uint8 private immutable _decimals;

    /* ========== EVENTS ========== */

    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
    event DelegateCheckpointed(address indexed delegate);

    event Recovered(address _token, uint256 _amount);
    event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
    event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount);
    event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
    event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
    event RewardAdded(address indexed _token, uint256 _reward);

    event BlacklistModified(address account, bool blacklisted);
    event KickIncentiveSet(uint256 rate, uint256 delay);
    event Shutdown();

    /***************************************
                    CONSTRUCTOR
    ****************************************/

    /**
     * @param _nameArg          Token name, simples
     * @param _symbolArg        Token symbol
     * @param _stakingToken     CVX (0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)
     * @param _cvxCrv           cvxCRV (0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7)
     * @param _cvxCrvStaking    cvxCRV rewards (0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e)
     */
    constructor(
        string memory _nameArg,
        string memory _symbolArg,
        address _stakingToken,
        address _cvxCrv,
        address _cvxCrvStaking
    ) Ownable() {
        _name = _nameArg;
        _symbol = _symbolArg;
        _decimals = 18;

        stakingToken = IERC20(_stakingToken);
        cvxCrv = _cvxCrv;
        cvxcrvStaking = _cvxCrvStaking;

        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
        epochs.push(Epoch({ supply: 0, date: uint32(currentEpoch) }));
    }

    /***************************************
                    MODIFIER
    ****************************************/

    modifier updateReward(address _account) {
        {
            Balances storage userBalance = balances[_account];
            uint256 rewardTokensLength = rewardTokens.length;
            for (uint256 i = 0; i < rewardTokensLength; i++) {
                address token = rewardTokens[i];
                uint256 newRewardPerToken = _rewardPerToken(token);
                rewardData[token].rewardPerTokenStored = newRewardPerToken.to96();
                rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to32();
                if (_account != address(0)) {
                    userData[_account][token] = UserData({
                        rewardPerTokenPaid: newRewardPerToken.to128(),
                        rewards: _earned(_account, token, userBalance.locked).to128()
                    });
                }
            }
        }
        _;
    }

    modifier notBlacklisted(address _sender, address _receiver) {
        require(!blacklist[_sender], "blacklisted");

        if (_sender != _receiver) {
            require(!blacklist[_receiver], "blacklisted");
        }

        _;
    }

    /***************************************
                    ADMIN
    ****************************************/

    function modifyBlacklist(address _account, bool _blacklisted) external onlyOwner {
        uint256 cs;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            cs := extcodesize(_account)
        }
        require(cs != 0, "Must be contract");

        blacklist[_account] = _blacklisted;
        emit BlacklistModified(_account, _blacklisted);
    }

    // Add a new reward token to be distributed to stakers
    function addReward(address _rewardsToken, address _distributor) external onlyOwner {
        require(rewardData[_rewardsToken].lastUpdateTime == 0, "Reward already exists");
        require(_rewardsToken != address(stakingToken), "Cannot add StakingToken as reward");
        require(rewardTokens.length < 5, "Max rewards length");

        rewardTokens.push(_rewardsToken);
        rewardData[_rewardsToken].lastUpdateTime = uint32(block.timestamp);
        rewardData[_rewardsToken].periodFinish = uint32(block.timestamp);
        rewardDistributors[_rewardsToken][_distributor] = true;
    }

    // Modify approval for an address to call notifyRewardAmount
    function approveRewardDistributor(
        address _rewardsToken,
        address _distributor,
        bool _approved
    ) external onlyOwner {
        require(rewardData[_rewardsToken].lastUpdateTime > 0, "Reward does not exist");
        rewardDistributors[_rewardsToken][_distributor] = _approved;
    }

    //set kick incentive
    function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
        require(_rate <= 500, "over max rate"); //max 5% per epoch
        require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
        kickRewardPerEpoch = _rate;
        kickRewardEpochDelay = _delay;

        emit KickIncentiveSet(_rate, _delay);
    }

    //shutdown the contract. unstake all tokens. release all locks
    function shutdown() external onlyOwner {
        isShutdown = true;
        emit Shutdown();
    }

    // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
    function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
        require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
        require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
        IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
        emit Recovered(_tokenAddress, _tokenAmount);
    }

    // Set approvals for staking cvx and cvxcrv
    function setApprovals() external {
        IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
        IERC20(cvxCrv).safeApprove(cvxcrvStaking, type(uint256).max);
    }

    /***************************************
                    ACTIONS
    ****************************************/

    // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
    function lock(address _account, uint256 _amount) external nonReentrant updateReward(_account) {
        //pull tokens
        stakingToken.safeTransferFrom(msg.sender, address(this), _amount);

        //lock
        _lock(_account, _amount);
    }

    //lock tokens
    function _lock(address _account, uint256 _amount) internal notBlacklisted(msg.sender, _account) {
        require(_amount > 0, "Cannot stake 0");
        require(!isShutdown, "shutdown");

        Balances storage bal = balances[_account];

        //must try check pointing epoch first
        _checkpointEpoch();

        //add user balances
        uint112 lockAmount = _amount.to112();
        bal.locked = bal.locked.add(lockAmount);

        //add to total supplies
        lockedSupply = lockedSupply.add(_amount);

        //add user lock records or add to current
        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
        uint256 unlockTime = currentEpoch.add(lockDuration);
        uint256 idx = userLocks[_account].length;
        if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
            userLocks[_account].push(LockedBalance({ amount: lockAmount, unlockTime: uint32(unlockTime) }));
        } else {
            LockedBalance storage userL = userLocks[_account][idx - 1];
            userL.amount = userL.amount.add(lockAmount);
        }

        address delegatee = delegates(_account);
        if (delegatee != address(0)) {
            delegateeUnlocks[delegatee][unlockTime] += lockAmount;
            _checkpointDelegate(delegatee, lockAmount, 0);
        }

        //update epoch supply, epoch checkpointed above so safe to add to latest
        Epoch storage e = epochs[epochs.length - 1];
        e.supply = e.supply.add(lockAmount);

        emit Staked(_account, lockAmount, lockAmount);
    }

    // claim all pending rewards
    function getReward(address _account) external {
        getReward(_account, false);
    }

    // Claim all pending rewards
    function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
        uint256 rewardTokensLength = rewardTokens.length;
        for (uint256 i; i < rewardTokensLength; i++) {
            address _rewardsToken = rewardTokens[i];
            uint256 reward = userData[_account][_rewardsToken].rewards;
            if (reward > 0) {
                userData[_account][_rewardsToken].rewards = 0;
                if (_rewardsToken == cvxCrv && _stake && _account == msg.sender) {
                    IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
                } else {
                    IERC20(_rewardsToken).safeTransfer(_account, reward);
                }
                emit RewardPaid(_account, _rewardsToken, reward);
            }
        }
    }

    function getReward(address _account, bool[] calldata _skipIdx) external nonReentrant updateReward(_account) {
        uint256 rewardTokensLength = rewardTokens.length;
        require(_skipIdx.length == rewardTokensLength, "!arr");
        for (uint256 i; i < rewardTokensLength; i++) {
            if (_skipIdx[i]) continue;
            address _rewardsToken = rewardTokens[i];
            uint256 reward = userData[_account][_rewardsToken].rewards;
            if (reward > 0) {
                userData[_account][_rewardsToken].rewards = 0;
                IERC20(_rewardsToken).safeTransfer(_account, reward);
                emit RewardPaid(_account, _rewardsToken, reward);
            }
        }
    }

    function checkpointEpoch() external {
        _checkpointEpoch();
    }

    //insert a new epoch if needed. fill in any gaps
    function _checkpointEpoch() internal {
        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);

        //first epoch add in constructor, no need to check 0 length
        //check to add
        uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date);
        if (nextEpochDate < currentEpoch) {
            while (nextEpochDate != currentEpoch) {
                nextEpochDate = nextEpochDate.add(rewardsDuration);
                epochs.push(Epoch({ supply: 0, date: uint32(nextEpochDate) }));
            }
        }
    }

    // Withdraw/relock all currently locked tokens where the unlock time has passed
    function processExpiredLocks(bool _relock) external nonReentrant {
        _processExpiredLocks(msg.sender, _relock, msg.sender, 0);
    }

    function kickExpiredLocks(address _account) external nonReentrant {
        //allow kick after grace period of 'kickRewardEpochDelay'
        _processExpiredLocks(_account, false, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
    }

    // Withdraw without checkpointing or accruing any rewards, providing system is shutdown
    function emergencyWithdraw() external nonReentrant {
        require(isShutdown, "Must be shutdown");

        LockedBalance[] memory locks = userLocks[msg.sender];
        Balances storage userBalance = balances[msg.sender];

        uint256 amt = userBalance.locked;
        require(amt > 0, "Nothing locked");

        userBalance.locked = 0;
        userBalance.nextUnlockIndex = locks.length.to32();
        lockedSupply -= amt;

        emit Withdrawn(msg.sender, amt, false);

        stakingToken.safeTransfer(msg.sender, amt);
    }

    // Withdraw all currently locked tokens where the unlock time has passed
    function _processExpiredLocks(
        address _account,
        bool _relock,
        address _rewardAddress,
        uint256 _checkDelay
    ) internal updateReward(_account) {
        LockedBalance[] storage locks = userLocks[_account];
        Balances storage userBalance = balances[_account];
        uint112 locked;
        uint256 length = locks.length;
        uint256 reward = 0;
        uint256 expiryTime = _checkDelay == 0 && _relock
            ? block.timestamp.add(rewardsDuration)
            : block.timestamp.sub(_checkDelay);
        require(length > 0, "no locks");
        // e.g. now = 16
        // if contract is shutdown OR latest lock unlock time (e.g. 17) <= now - (1)
        // e.g. 17 <= (16 + 1)
        if (isShutdown || locks[length - 1].unlockTime <= expiryTime) {
            //if time is beyond last lock, can just bundle everything together
            locked = userBalance.locked;

            //dont delete, just set next index
            userBalance.nextUnlockIndex = length.to32();

            //check for kick reward
            //this wont have the exact reward rate that you would get if looped through
            //but this section is supposed to be for quick and easy low gas processing of all locks
            //we'll assume that if the reward was good enough someone would have processed at an earlier epoch
            if (_checkDelay > 0) {
                uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
                uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
                reward = uint256(locked).mul(rRate).div(denominator);
            }
        } else {
            //use a processed index(nextUnlockIndex) to not loop as much
            //deleting does not change array length
            uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
            for (uint256 i = nextUnlockIndex; i < length; i++) {
                //unlock time must be less or equal to time
                if (locks[i].unlockTime > expiryTime) break;

                //add to cumulative amounts
                locked = locked.add(locks[i].amount);

                //check for kick reward
                //each epoch over due increases reward
                if (_checkDelay > 0) {
                    uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                    uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
                    uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
                    reward = reward.add(uint256(locks[i].amount).mul(rRate).div(denominator));
                }
                //set next unlock index
                nextUnlockIndex++;
            }
            //update next unlock index
            userBalance.nextUnlockIndex = nextUnlockIndex;
        }
        require(locked > 0, "no exp locks");

        //update user balances and total supplies
        userBalance.locked = userBalance.locked.sub(locked);
        lockedSupply = lockedSupply.sub(locked);

        //checkpoint the delegatee
        _checkpointDelegate(delegates(_account), 0, 0);

        emit Withdrawn(_account, locked, _relock);

        //send process incentive
        if (reward > 0) {
            //reduce return amount by the kick reward
            locked = locked.sub(reward.to112());

            //transfer reward
            stakingToken.safeTransfer(_rewardAddress, reward);
            emit KickReward(_rewardAddress, _account, reward);
        }

        //relock or return to user
        if (_relock) {
            _lock(_account, locked);
        } else {
            stakingToken.safeTransfer(_account, locked);
        }
    }

    /***************************************
            DELEGATION & VOTE BALANCE
    ****************************************/

    /**
     * @dev Delegate votes from the sender to `newDelegatee`.
     */
    function delegate(address newDelegatee) external virtual nonReentrant {
        // Step 1: Get lock data
        LockedBalance[] storage locks = userLocks[msg.sender];
        uint256 len = locks.length;
        require(len > 0, "Nothing to delegate");
        require(newDelegatee != address(0), "Must delegate to someone");

        // Step 2: Update delegatee storage
        address oldDelegatee = delegates(msg.sender);
        require(newDelegatee != oldDelegatee, "Must choose new delegatee");
        _delegates[msg.sender] = newDelegatee;

        emit DelegateChanged(msg.sender, oldDelegatee, newDelegatee);

        // Step 3: Move balances around
        //         Delegate for the upcoming epoch
        uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);
        uint256 i = len - 1;
        uint256 futureUnlocksSum = 0;
        LockedBalance memory currentLock = locks[i];
        // Step 3.1: Add future unlocks and sum balances
        while (currentLock.unlockTime > upcomingEpoch) {
            futureUnlocksSum += currentLock.amount;

            if (oldDelegatee != address(0)) {
                delegateeUnlocks[oldDelegatee][currentLock.unlockTime] -= currentLock.amount;
            }
            delegateeUnlocks[newDelegatee][currentLock.unlockTime] += currentLock.amount;

            if (i > 0) {
                i--;
                currentLock = locks[i];
            } else {
                break;
            }
        }

        // Step 3.2: Checkpoint old delegatee
        _checkpointDelegate(oldDelegatee, 0, futureUnlocksSum);

        // Step 3.3: Checkpoint new delegatee
        _checkpointDelegate(newDelegatee, futureUnlocksSum, 0);
    }

    function _checkpointDelegate(
        address _account,
        uint256 _upcomingAddition,
        uint256 _upcomingDeduction
    ) internal {
        // This would only skip on first checkpointing
        if (_account != address(0)) {
            uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);
            DelegateeCheckpoint[] storage ckpts = _checkpointedVotes[_account];
            if (ckpts.length > 0) {
                DelegateeCheckpoint memory prevCkpt = ckpts[ckpts.length - 1];
                // If there has already been a record for the upcoming epoch, no need to deduct the unlocks
                if (prevCkpt.epochStart == upcomingEpoch) {
                    ckpts[ckpts.length - 1] = DelegateeCheckpoint({
                        votes: (prevCkpt.votes + _upcomingAddition - _upcomingDeduction).to224(),
                        epochStart: upcomingEpoch.to32()
                    });
                }
                // else if it has been over 16 weeks since the previous checkpoint, all locks have since expired
                // e.g. week 1 + 17 <= 18
                else if (prevCkpt.epochStart + lockDuration <= upcomingEpoch) {
                    ckpts.push(
                        DelegateeCheckpoint({
                            votes: (_upcomingAddition - _upcomingDeduction).to224(),
                            epochStart: upcomingEpoch.to32()
                        })
                    );
                } else {
                    uint256 nextEpoch = upcomingEpoch;
                    uint256 unlocksSinceLatestCkpt = 0;
                    // Should be maximum 18 iterations
                    while (nextEpoch > prevCkpt.epochStart) {
                        unlocksSinceLatestCkpt += delegateeUnlocks[_account][nextEpoch];
                        nextEpoch -= rewardsDuration;
                    }
                    ckpts.push(
                        DelegateeCheckpoint({
                            votes: (prevCkpt.votes - unlocksSinceLatestCkpt + _upcomingAddition - _upcomingDeduction)
                                .to224(),
                            epochStart: upcomingEpoch.to32()
                        })
                    );
                }
            } else {
                ckpts.push(
                    DelegateeCheckpoint({
                        votes: (_upcomingAddition - _upcomingDeduction).to224(),
                        epochStart: upcomingEpoch.to32()
                    })
                );
            }
            emit DelegateCheckpointed(_account);
        }
    }

    /**
     * @dev Get the address `account` is currently delegating to.
     */
    function delegates(address account) public view virtual returns (address) {
        return _delegates[account];
    }

    /**
     * @dev Gets the current votes balance for `account`
     */
    function getVotes(address account) external view returns (uint256) {
        return getPastVotes(account, block.timestamp);
    }

    /**
     * @dev Get the `pos`-th checkpoint for `account`.
     */
    function checkpoints(address account, uint32 pos) external view virtual returns (DelegateeCheckpoint memory) {
        return _checkpointedVotes[account][pos];
    }

    /**
     * @dev Get number of checkpoints for `account`.
     */
    function numCheckpoints(address account) external view virtual returns (uint32) {
        return _checkpointedVotes[account].length.to32();
    }

    /**
     * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
     */
    function getPastVotes(address account, uint256 timestamp) public view returns (uint256 votes) {
        require(timestamp <= block.timestamp, "ERC20Votes: block not yet mined");
        uint256 epoch = timestamp.div(rewardsDuration).mul(rewardsDuration);
        DelegateeCheckpoint memory ckpt = _checkpointsLookup(_checkpointedVotes[account], epoch);
        votes = ckpt.votes;
        if (votes == 0 || ckpt.epochStart + lockDuration <= epoch) {
            return 0;
        }
        while (epoch > ckpt.epochStart) {
            votes -= delegateeUnlocks[account][epoch];
            epoch -= rewardsDuration;
        }
    }

    /**
     * @dev Retrieve the `totalSupply` at the end of `timestamp`. Note, this value is the sum of all balances.
     * It is but NOT the sum of all the delegated votes!
     */
    function getPastTotalSupply(uint256 timestamp) external view returns (uint256) {
        require(timestamp < block.timestamp, "ERC20Votes: block not yet mined");
        return totalSupplyAtEpoch(findEpochId(timestamp));
    }

    /**
     * @dev Lookup a value in a list of (sorted) checkpoints.
     *      Copied from oz/ERC20Votes.sol
     */
    function _checkpointsLookup(DelegateeCheckpoint[] storage ckpts, uint256 epochStart)
        private
        view
        returns (DelegateeCheckpoint memory)
    {
        uint256 high = ckpts.length;
        uint256 low = 0;
        while (low < high) {
            uint256 mid = AuraMath.average(low, high);
            if (ckpts[mid].epochStart > epochStart) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        return high == 0 ? DelegateeCheckpoint(0, 0) : ckpts[high - 1];
    }

    /***************************************
                VIEWS - BALANCES
    ****************************************/

    // Balance of an account which only includes properly locked tokens as of the most recent eligible epoch
    function balanceOf(address _user) external view returns (uint256 amount) {
        return balanceAtEpochOf(findEpochId(block.timestamp), _user);
    }

    // Balance of an account which only includes properly locked tokens at the given epoch
    function balanceAtEpochOf(uint256 _epoch, address _user) public view returns (uint256 amount) {
        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));
        require(epochStart < block.timestamp, "Epoch is in the future");

        uint256 cutoffEpoch = epochStart.sub(lockDuration);

        LockedBalance[] storage locks = userLocks[_user];

        //need to add up since the range could be in the middle somewhere
        //traverse inversely to make more current queries more gas efficient
        uint256 locksLength = locks.length;
        for (uint256 i = locksLength; i > 0; i--) {
            uint256 lockEpoch = uint256(locks[i - 1].unlockTime).sub(lockDuration);
            //lock epoch must be less or equal to the epoch we're basing from.
            //also not include the current epoch
            if (lockEpoch < epochStart) {
                if (lockEpoch > cutoffEpoch) {
                    amount = amount.add(locks[i - 1].amount);
                } else {
                    //stop now as no futher checks matter
                    break;
                }
            }
        }

        return amount;
    }

    // Information on a user's locked balances
    function lockedBalances(address _user)
        external
        view
        returns (
            uint256 total,
            uint256 unlockable,
            uint256 locked,
            LockedBalance[] memory lockData
        )
    {
        LockedBalance[] storage locks = userLocks[_user];
        Balances storage userBalance = balances[_user];
        uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
        uint256 idx;
        for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
            if (locks[i].unlockTime > block.timestamp) {
                if (idx == 0) {
                    lockData = new LockedBalance[](locks.length - i);
                }
                lockData[idx] = locks[i];
                idx++;
                locked = locked.add(locks[i].amount);
            } else {
                unlockable = unlockable.add(locks[i].amount);
            }
        }
        return (userBalance.locked, unlockable, locked, lockData);
    }

    // Supply of all properly locked balances at most recent eligible epoch
    function totalSupply() external view returns (uint256 supply) {
        return totalSupplyAtEpoch(findEpochId(block.timestamp));
    }

    // Supply of all properly locked balances at the given epoch
    function totalSupplyAtEpoch(uint256 _epoch) public view returns (uint256 supply) {
        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));
        require(epochStart < block.timestamp, "Epoch is in the future");

        uint256 cutoffEpoch = epochStart.sub(lockDuration);
        uint256 lastIndex = epochs.length - 1;

        uint256 epochIndex = _epoch > lastIndex ? lastIndex : _epoch;

        for (uint256 i = epochIndex + 1; i > 0; i--) {
            Epoch memory e = epochs[i - 1];
            if (e.date == epochStart) {
                continue;
            } else if (e.date <= cutoffEpoch) {
                break;
            } else {
                supply += e.supply;
            }
        }
    }

    // Get an epoch index based on timestamp
    function findEpochId(uint256 _time) public view returns (uint256 epoch) {
        return _time.sub(epochs[0].date).div(rewardsDuration);
    }

    /***************************************
                VIEWS - GENERAL
    ****************************************/

    // Number of epochs
    function epochCount() external view returns (uint256) {
        return epochs.length;
    }

    function decimals() external view returns (uint8) {
        return _decimals;
    }

    function name() external view returns (string memory) {
        return _name;
    }

    function symbol() external view returns (string memory) {
        return _symbol;
    }

    /***************************************
                VIEWS - REWARDS
    ****************************************/

    // Address and claimable amount of all reward tokens for the given account
    function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
        userRewards = new EarnedData[](rewardTokens.length);
        Balances storage userBalance = balances[_account];
        uint256 userRewardsLength = userRewards.length;
        for (uint256 i = 0; i < userRewardsLength; i++) {
            address token = rewardTokens[i];
            userRewards[i].token = token;
            userRewards[i].amount = _earned(_account, token, userBalance.locked);
        }
        return userRewards;
    }

    function lastTimeRewardApplicable(address _rewardsToken) external view returns (uint256) {
        return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
    }

    function rewardPerToken(address _rewardsToken) external view returns (uint256) {
        return _rewardPerToken(_rewardsToken);
    }

    function _earned(
        address _user,
        address _rewardsToken,
        uint256 _balance
    ) internal view returns (uint256) {
        UserData memory data = userData[_user][_rewardsToken];
        return _balance.mul(_rewardPerToken(_rewardsToken).sub(data.rewardPerTokenPaid)).div(1e18).add(data.rewards);
    }

    function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
        return AuraMath.min(block.timestamp, _finishTime);
    }

    function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
        if (lockedSupply == 0) {
            return rewardData[_rewardsToken].rewardPerTokenStored;
        }
        return
            uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
                _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
                    .sub(rewardData[_rewardsToken].lastUpdateTime)
                    .mul(rewardData[_rewardsToken].rewardRate)
                    .mul(1e18)
                    .div(lockedSupply)
            );
    }

    /***************************************
                REWARD FUNDING
    ****************************************/

    function queueNewRewards(address _rewardsToken, uint256 _rewards) external nonReentrant {
        require(rewardDistributors[_rewardsToken][msg.sender], "!authorized");
        require(_rewards > 0, "No reward");

        RewardData storage rdata = rewardData[_rewardsToken];

        IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _rewards);

        _rewards = _rewards.add(queuedRewards[_rewardsToken]);
        require(_rewards < 1e25, "!rewards");

        if (block.timestamp >= rdata.periodFinish) {
            _notifyReward(_rewardsToken, _rewards);
            queuedRewards[_rewardsToken] = 0;
            return;
        }

        //et = now - (finish-duration)
        uint256 elapsedTime = block.timestamp.sub(rdata.periodFinish.sub(rewardsDuration.to32()));
        //current at now: rewardRate * elapsedTime
        uint256 currentAtNow = rdata.rewardRate * elapsedTime;
        uint256 queuedRatio = currentAtNow.mul(1000).div(_rewards);
        if (queuedRatio < newRewardRatio) {
            _notifyReward(_rewardsToken, _rewards);
            queuedRewards[_rewardsToken] = 0;
        } else {
            queuedRewards[_rewardsToken] = _rewards;
        }
    }

    function _notifyReward(address _rewardsToken, uint256 _reward) internal updateReward(address(0)) {
        RewardData storage rdata = rewardData[_rewardsToken];

        if (block.timestamp >= rdata.periodFinish) {
            rdata.rewardRate = _reward.div(rewardsDuration).to96();
        } else {
            uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
            uint256 leftover = remaining.mul(rdata.rewardRate);
            rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to96();
        }

        // Equivalent to 10 million tokens over a weeks duration
        require(rdata.rewardRate < 1e20, "!rewardRate");
        require(lockedSupply >= 1e20, "!balance");

        rdata.lastUpdateTime = block.timestamp.to32();
        rdata.periodFinish = block.timestamp.add(rewardsDuration).to32();

        emit RewardAdded(_rewardsToken, _reward);
    }
}
Interfaces.sol 144 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

interface IPriceOracle {
    struct OracleAverageQuery {
        Variable variable;
        uint256 secs;
        uint256 ago;
    }
    enum Variable {
        PAIR_PRICE,
        BPT_PRICE,
        INVARIANT
    }

    function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
        external
        view
        returns (uint256[] memory results);
}

interface IVault {
    enum PoolSpecialization {
        GENERAL,
        MINIMAL_SWAP_INFO,
        TWO_TOKEN
    }
    enum JoinKind {
        INIT,
        EXACT_TOKENS_IN_FOR_BPT_OUT,
        TOKEN_IN_FOR_EXACT_BPT_OUT,
        ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
    }

    enum SwapKind {
        GIVEN_IN,
        GIVEN_OUT
    }

    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        IAsset assetIn;
        IAsset assetOut;
        uint256 amount;
        bytes userData;
    }

    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }

    struct JoinPoolRequest {
        IAsset[] assets;
        uint256[] maxAmountsIn;
        bytes userData;
        bool fromInternalBalance;
    }

    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);

    function getPoolTokens(bytes32 poolId)
        external
        view
        returns (
            address[] memory tokens,
            uint256[] memory balances,
            uint256 lastChangeBlock
        );

    function joinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        JoinPoolRequest memory request
    ) external payable;

    function swap(
        SingleSwap memory singleSwap,
        FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external returns (uint256 amountCalculated);

    function exitPool(
        bytes32 poolId,
        address sender,
        address payable recipient,
        ExitPoolRequest memory request
    ) external;

    struct ExitPoolRequest {
        IAsset[] assets;
        uint256[] minAmountsOut;
        bytes userData;
        bool toInternalBalance;
    }
    enum ExitKind {
        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
        EXACT_BPT_IN_FOR_TOKENS_OUT,
        BPT_IN_FOR_EXACT_TOKENS_OUT,
        MANAGEMENT_FEE_TOKENS_OUT // for ManagedPool
    }
}

interface IAsset {
    // solhint-disable-previous-line no-empty-blocks
}

interface IAuraLocker {
    function lock(address _account, uint256 _amount) external;

    function checkpointEpoch() external;

    function epochCount() external view returns (uint256);

    function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);

    function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply);

    function queueNewRewards(address _rewardsToken, uint256 reward) external;

    function getReward(address _account, bool _stake) external;

    function getReward(address _account) external;
}

interface IExtraRewardsDistributor {
    function addReward(address _token, uint256 _amount) external;
}

interface ICrvDepositorWrapper {
    function getMinOut(uint256, uint256) external view returns (uint256);

    function deposit(
        uint256,
        uint256,
        bool,
        address _stakeAddress
    ) external;
}
Address.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

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

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

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

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

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

pragma solidity ^0.8.0;

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

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

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
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);
}
ReentrancyGuard.sol 63 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}
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");
        }
    }
}
AuraLocker.sol 907 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

import { IERC20 } from "@openzeppelin/contracts-0.8/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts-0.8/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts-0.8/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts-0.8/security/ReentrancyGuard.sol";
import { AuraMath, AuraMath32, AuraMath112, AuraMath224 } from "../utils/AuraMath.sol";
import { IAuraLocker } from "../interfaces/IAuraLocker.sol";
import { IRewardStaking } from "../interfaces/IRewardStaking.sol";

/**
 * @title   AuraLocker
 * @author  ConvexFinance
 * @notice  Effectively allows for rolling 16 week lockups of CVX, and provides balances available
 *          at each epoch (1 week). Also receives cvxCrv from `CvxStakingProxy` and redistributes
 *          to depositors.
 * @dev     Individual and delegatee vote power lookups both use independent accounting mechanisms.
 */
contract AuraLocker is ReentrancyGuard, Ownable, IAuraLocker {
    using AuraMath for uint256;
    using AuraMath224 for uint224;
    using AuraMath112 for uint112;
    using AuraMath32 for uint32;
    using SafeERC20 for IERC20;

    /* ==========     STRUCTS     ========== */

    struct RewardData {
        /// Timestamp for current period finish
        uint32 periodFinish;
        /// Last time any user took action
        uint32 lastUpdateTime;
        /// RewardRate for the rest of the period
        uint96 rewardRate;
        /// Ever increasing rewardPerToken rate, based on % of total supply
        uint96 rewardPerTokenStored;
    }
    struct UserData {
        uint128 rewardPerTokenPaid;
        uint128 rewards;
    }
    struct EarnedData {
        address token;
        uint256 amount;
    }
    struct Balances {
        uint112 locked;
        uint32 nextUnlockIndex;
    }
    struct LockedBalance {
        uint112 amount;
        uint32 unlockTime;
    }
    struct Epoch {
        uint224 supply;
        uint32 date; //epoch start date
    }
    struct DelegateeCheckpoint {
        uint224 votes;
        uint32 epochStart;
    }

    /* ========== STATE VARIABLES ========== */

    // Rewards
    address[] public rewardTokens;
    mapping(address => uint256) public queuedRewards;
    uint256 public constant newRewardRatio = 830;
    //     Core reward data
    mapping(address => RewardData) public rewardData;
    //     Reward token -> distributor -> is approved to add rewards
    mapping(address => mapping(address => bool)) public rewardDistributors;
    //     User -> reward token -> amount
    mapping(address => mapping(address => UserData)) public userData;
    //     Duration that rewards are streamed over
    uint256 public constant rewardsDuration = 86400 * 7;
    //     Duration of lock/earned penalty period
    uint256 public constant lockDuration = rewardsDuration * 17;

    // Balances
    //     Supplies and historic supply
    uint256 public lockedSupply;
    //     Epochs contains only the tokens that were locked at that epoch, not a cumulative supply
    Epoch[] public epochs;
    //     Mappings for balance data
    mapping(address => Balances) public balances;
    mapping(address => LockedBalance[]) public userLocks;

    // Voting
    //     Stored delegations
    mapping(address => address) private _delegates;
    //     Checkpointed votes
    mapping(address => DelegateeCheckpoint[]) private _checkpointedVotes;
    //     Delegatee balances (user -> unlock timestamp -> amount)
    mapping(address => mapping(uint256 => uint256)) public delegateeUnlocks;

    // Config
    //     Blacklisted smart contract interactions
    mapping(address => bool) public blacklist;
    //     Tokens
    IERC20 public immutable stakingToken;
    address public immutable cvxCrv;
    //     Denom for calcs
    uint256 public constant denominator = 10000;
    //     Staking cvxCrv
    address public immutable cvxcrvStaking;
    //     Incentives
    uint256 public kickRewardPerEpoch = 100;
    uint256 public kickRewardEpochDelay = 3;
    //     Shutdown
    bool public isShutdown = false;

    // Basic token data
    string private _name;
    string private _symbol;
    uint8 private immutable _decimals;

    /* ========== EVENTS ========== */

    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
    event DelegateCheckpointed(address indexed delegate);

    event Recovered(address _token, uint256 _amount);
    event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
    event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount);
    event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
    event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
    event RewardAdded(address indexed _token, uint256 _reward);

    event BlacklistModified(address account, bool blacklisted);
    event KickIncentiveSet(uint256 rate, uint256 delay);
    event Shutdown();

    /***************************************
                    CONSTRUCTOR
    ****************************************/

    /**
     * @param _nameArg          Token name, simples
     * @param _symbolArg        Token symbol
     * @param _stakingToken     CVX (0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)
     * @param _cvxCrv           cvxCRV (0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7)
     * @param _cvxCrvStaking    cvxCRV rewards (0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e)
     */
    constructor(
        string memory _nameArg,
        string memory _symbolArg,
        address _stakingToken,
        address _cvxCrv,
        address _cvxCrvStaking
    ) Ownable() {
        _name = _nameArg;
        _symbol = _symbolArg;
        _decimals = 18;

        stakingToken = IERC20(_stakingToken);
        cvxCrv = _cvxCrv;
        cvxcrvStaking = _cvxCrvStaking;

        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
        epochs.push(Epoch({ supply: 0, date: uint32(currentEpoch) }));
    }

    /***************************************
                    MODIFIER
    ****************************************/

    modifier updateReward(address _account) {
        {
            Balances storage userBalance = balances[_account];
            uint256 rewardTokensLength = rewardTokens.length;
            for (uint256 i = 0; i < rewardTokensLength; i++) {
                address token = rewardTokens[i];
                uint256 newRewardPerToken = _rewardPerToken(token);
                rewardData[token].rewardPerTokenStored = newRewardPerToken.to96();
                rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to32();
                if (_account != address(0)) {
                    userData[_account][token] = UserData({
                        rewardPerTokenPaid: newRewardPerToken.to128(),
                        rewards: _earned(_account, token, userBalance.locked).to128()
                    });
                }
            }
        }
        _;
    }

    modifier notBlacklisted(address _sender, address _receiver) {
        require(!blacklist[_sender], "blacklisted");

        if (_sender != _receiver) {
            require(!blacklist[_receiver], "blacklisted");
        }

        _;
    }

    /***************************************
                    ADMIN
    ****************************************/

    function modifyBlacklist(address _account, bool _blacklisted) external onlyOwner {
        uint256 cs;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            cs := extcodesize(_account)
        }
        require(cs != 0, "Must be contract");

        blacklist[_account] = _blacklisted;
        emit BlacklistModified(_account, _blacklisted);
    }

    // Add a new reward token to be distributed to stakers
    function addReward(address _rewardsToken, address _distributor) external onlyOwner {
        require(rewardData[_rewardsToken].lastUpdateTime == 0, "Reward already exists");
        require(_rewardsToken != address(stakingToken), "Cannot add StakingToken as reward");
        require(rewardTokens.length < 5, "Max rewards length");

        rewardTokens.push(_rewardsToken);
        rewardData[_rewardsToken].lastUpdateTime = uint32(block.timestamp);
        rewardData[_rewardsToken].periodFinish = uint32(block.timestamp);
        rewardDistributors[_rewardsToken][_distributor] = true;
    }

    // Modify approval for an address to call notifyRewardAmount
    function approveRewardDistributor(
        address _rewardsToken,
        address _distributor,
        bool _approved
    ) external onlyOwner {
        require(rewardData[_rewardsToken].lastUpdateTime > 0, "Reward does not exist");
        rewardDistributors[_rewardsToken][_distributor] = _approved;
    }

    //set kick incentive
    function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
        require(_rate <= 500, "over max rate"); //max 5% per epoch
        require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
        kickRewardPerEpoch = _rate;
        kickRewardEpochDelay = _delay;

        emit KickIncentiveSet(_rate, _delay);
    }

    //shutdown the contract. unstake all tokens. release all locks
    function shutdown() external onlyOwner {
        isShutdown = true;
        emit Shutdown();
    }

    // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
    function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
        require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
        require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
        IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
        emit Recovered(_tokenAddress, _tokenAmount);
    }

    // Set approvals for staking cvx and cvxcrv
    function setApprovals() external {
        IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
        IERC20(cvxCrv).safeApprove(cvxcrvStaking, type(uint256).max);
    }

    /***************************************
                    ACTIONS
    ****************************************/

    // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
    function lock(address _account, uint256 _amount) external nonReentrant updateReward(_account) {
        //pull tokens
        stakingToken.safeTransferFrom(msg.sender, address(this), _amount);

        //lock
        _lock(_account, _amount);
    }

    //lock tokens
    function _lock(address _account, uint256 _amount) internal notBlacklisted(msg.sender, _account) {
        require(_amount > 0, "Cannot stake 0");
        require(!isShutdown, "shutdown");

        Balances storage bal = balances[_account];

        //must try check pointing epoch first
        _checkpointEpoch();

        //add user balances
        uint112 lockAmount = _amount.to112();
        bal.locked = bal.locked.add(lockAmount);

        //add to total supplies
        lockedSupply = lockedSupply.add(_amount);

        //add user lock records or add to current
        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
        uint256 unlockTime = currentEpoch.add(lockDuration);
        uint256 idx = userLocks[_account].length;
        if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
            userLocks[_account].push(LockedBalance({ amount: lockAmount, unlockTime: uint32(unlockTime) }));
        } else {
            LockedBalance storage userL = userLocks[_account][idx - 1];
            userL.amount = userL.amount.add(lockAmount);
        }

        address delegatee = delegates(_account);
        if (delegatee != address(0)) {
            delegateeUnlocks[delegatee][unlockTime] += lockAmount;
            _checkpointDelegate(delegatee, lockAmount, 0);
        }

        //update epoch supply, epoch checkpointed above so safe to add to latest
        Epoch storage e = epochs[epochs.length - 1];
        e.supply = e.supply.add(lockAmount);

        emit Staked(_account, lockAmount, lockAmount);
    }

    // claim all pending rewards
    function getReward(address _account) external {
        getReward(_account, false);
    }

    // Claim all pending rewards
    function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
        uint256 rewardTokensLength = rewardTokens.length;
        for (uint256 i; i < rewardTokensLength; i++) {
            address _rewardsToken = rewardTokens[i];
            uint256 reward = userData[_account][_rewardsToken].rewards;
            if (reward > 0) {
                userData[_account][_rewardsToken].rewards = 0;
                if (_rewardsToken == cvxCrv && _stake && _account == msg.sender) {
                    IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
                } else {
                    IERC20(_rewardsToken).safeTransfer(_account, reward);
                }
                emit RewardPaid(_account, _rewardsToken, reward);
            }
        }
    }

    function getReward(address _account, bool[] calldata _skipIdx) external nonReentrant updateReward(_account) {
        uint256 rewardTokensLength = rewardTokens.length;
        require(_skipIdx.length == rewardTokensLength, "!arr");
        for (uint256 i; i < rewardTokensLength; i++) {
            if (_skipIdx[i]) continue;
            address _rewardsToken = rewardTokens[i];
            uint256 reward = userData[_account][_rewardsToken].rewards;
            if (reward > 0) {
                userData[_account][_rewardsToken].rewards = 0;
                IERC20(_rewardsToken).safeTransfer(_account, reward);
                emit RewardPaid(_account, _rewardsToken, reward);
            }
        }
    }

    function checkpointEpoch() external {
        _checkpointEpoch();
    }

    //insert a new epoch if needed. fill in any gaps
    function _checkpointEpoch() internal {
        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);

        //first epoch add in constructor, no need to check 0 length
        //check to add
        uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date);
        if (nextEpochDate < currentEpoch) {
            while (nextEpochDate != currentEpoch) {
                nextEpochDate = nextEpochDate.add(rewardsDuration);
                epochs.push(Epoch({ supply: 0, date: uint32(nextEpochDate) }));
            }
        }
    }

    // Withdraw/relock all currently locked tokens where the unlock time has passed
    function processExpiredLocks(bool _relock) external nonReentrant {
        _processExpiredLocks(msg.sender, _relock, msg.sender, 0);
    }

    function kickExpiredLocks(address _account) external nonReentrant {
        //allow kick after grace period of 'kickRewardEpochDelay'
        _processExpiredLocks(_account, false, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
    }

    // Withdraw without checkpointing or accruing any rewards, providing system is shutdown
    function emergencyWithdraw() external nonReentrant {
        require(isShutdown, "Must be shutdown");

        LockedBalance[] memory locks = userLocks[msg.sender];
        Balances storage userBalance = balances[msg.sender];

        uint256 amt = userBalance.locked;
        require(amt > 0, "Nothing locked");

        userBalance.locked = 0;
        userBalance.nextUnlockIndex = locks.length.to32();
        lockedSupply -= amt;

        emit Withdrawn(msg.sender, amt, false);

        stakingToken.safeTransfer(msg.sender, amt);
    }

    // Withdraw all currently locked tokens where the unlock time has passed
    function _processExpiredLocks(
        address _account,
        bool _relock,
        address _rewardAddress,
        uint256 _checkDelay
    ) internal updateReward(_account) {
        LockedBalance[] storage locks = userLocks[_account];
        Balances storage userBalance = balances[_account];
        uint112 locked;
        uint256 length = locks.length;
        uint256 reward = 0;
        uint256 expiryTime = _checkDelay == 0 && _relock
            ? block.timestamp.add(rewardsDuration)
            : block.timestamp.sub(_checkDelay);
        require(length > 0, "no locks");
        // e.g. now = 16
        // if contract is shutdown OR latest lock unlock time (e.g. 17) <= now - (1)
        // e.g. 17 <= (16 + 1)
        if (isShutdown || locks[length - 1].unlockTime <= expiryTime) {
            //if time is beyond last lock, can just bundle everything together
            locked = userBalance.locked;

            //dont delete, just set next index
            userBalance.nextUnlockIndex = length.to32();

            //check for kick reward
            //this wont have the exact reward rate that you would get if looped through
            //but this section is supposed to be for quick and easy low gas processing of all locks
            //we'll assume that if the reward was good enough someone would have processed at an earlier epoch
            if (_checkDelay > 0) {
                uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
                uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
                reward = uint256(locked).mul(rRate).div(denominator);
            }
        } else {
            //use a processed index(nextUnlockIndex) to not loop as much
            //deleting does not change array length
            uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
            for (uint256 i = nextUnlockIndex; i < length; i++) {
                //unlock time must be less or equal to time
                if (locks[i].unlockTime > expiryTime) break;

                //add to cumulative amounts
                locked = locked.add(locks[i].amount);

                //check for kick reward
                //each epoch over due increases reward
                if (_checkDelay > 0) {
                    uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                    uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
                    uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);
                    reward = reward.add(uint256(locks[i].amount).mul(rRate).div(denominator));
                }
                //set next unlock index
                nextUnlockIndex++;
            }
            //update next unlock index
            userBalance.nextUnlockIndex = nextUnlockIndex;
        }
        require(locked > 0, "no exp locks");

        //update user balances and total supplies
        userBalance.locked = userBalance.locked.sub(locked);
        lockedSupply = lockedSupply.sub(locked);

        //checkpoint the delegatee
        _checkpointDelegate(delegates(_account), 0, 0);

        emit Withdrawn(_account, locked, _relock);

        //send process incentive
        if (reward > 0) {
            //reduce return amount by the kick reward
            locked = locked.sub(reward.to112());

            //transfer reward
            stakingToken.safeTransfer(_rewardAddress, reward);
            emit KickReward(_rewardAddress, _account, reward);
        }

        //relock or return to user
        if (_relock) {
            _lock(_account, locked);
        } else {
            stakingToken.safeTransfer(_account, locked);
        }
    }

    /***************************************
            DELEGATION & VOTE BALANCE
    ****************************************/

    /**
     * @dev Delegate votes from the sender to `newDelegatee`.
     */
    function delegate(address newDelegatee) external virtual nonReentrant {
        // Step 1: Get lock data
        LockedBalance[] storage locks = userLocks[msg.sender];
        uint256 len = locks.length;
        require(len > 0, "Nothing to delegate");
        require(newDelegatee != address(0), "Must delegate to someone");

        // Step 2: Update delegatee storage
        address oldDelegatee = delegates(msg.sender);
        require(newDelegatee != oldDelegatee, "Must choose new delegatee");
        _delegates[msg.sender] = newDelegatee;

        emit DelegateChanged(msg.sender, oldDelegatee, newDelegatee);

        // Step 3: Move balances around
        //         Delegate for the upcoming epoch
        uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);
        uint256 i = len - 1;
        uint256 futureUnlocksSum = 0;
        LockedBalance memory currentLock = locks[i];
        // Step 3.1: Add future unlocks and sum balances
        while (currentLock.unlockTime > upcomingEpoch) {
            futureUnlocksSum += currentLock.amount;

            if (oldDelegatee != address(0)) {
                delegateeUnlocks[oldDelegatee][currentLock.unlockTime] -= currentLock.amount;
            }
            delegateeUnlocks[newDelegatee][currentLock.unlockTime] += currentLock.amount;

            if (i > 0) {
                i--;
                currentLock = locks[i];
            } else {
                break;
            }
        }

        // Step 3.2: Checkpoint old delegatee
        _checkpointDelegate(oldDelegatee, 0, futureUnlocksSum);

        // Step 3.3: Checkpoint new delegatee
        _checkpointDelegate(newDelegatee, futureUnlocksSum, 0);
    }

    function _checkpointDelegate(
        address _account,
        uint256 _upcomingAddition,
        uint256 _upcomingDeduction
    ) internal {
        // This would only skip on first checkpointing
        if (_account != address(0)) {
            uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);
            DelegateeCheckpoint[] storage ckpts = _checkpointedVotes[_account];
            if (ckpts.length > 0) {
                DelegateeCheckpoint memory prevCkpt = ckpts[ckpts.length - 1];
                // If there has already been a record for the upcoming epoch, no need to deduct the unlocks
                if (prevCkpt.epochStart == upcomingEpoch) {
                    ckpts[ckpts.length - 1] = DelegateeCheckpoint({
                        votes: (prevCkpt.votes + _upcomingAddition - _upcomingDeduction).to224(),
                        epochStart: upcomingEpoch.to32()
                    });
                }
                // else if it has been over 16 weeks since the previous checkpoint, all locks have since expired
                // e.g. week 1 + 17 <= 18
                else if (prevCkpt.epochStart + lockDuration <= upcomingEpoch) {
                    ckpts.push(
                        DelegateeCheckpoint({
                            votes: (_upcomingAddition - _upcomingDeduction).to224(),
                            epochStart: upcomingEpoch.to32()
                        })
                    );
                } else {
                    uint256 nextEpoch = upcomingEpoch;
                    uint256 unlocksSinceLatestCkpt = 0;
                    // Should be maximum 18 iterations
                    while (nextEpoch > prevCkpt.epochStart) {
                        unlocksSinceLatestCkpt += delegateeUnlocks[_account][nextEpoch];
                        nextEpoch -= rewardsDuration;
                    }
                    ckpts.push(
                        DelegateeCheckpoint({
                            votes: (prevCkpt.votes - unlocksSinceLatestCkpt + _upcomingAddition - _upcomingDeduction)
                                .to224(),
                            epochStart: upcomingEpoch.to32()
                        })
                    );
                }
            } else {
                ckpts.push(
                    DelegateeCheckpoint({
                        votes: (_upcomingAddition - _upcomingDeduction).to224(),
                        epochStart: upcomingEpoch.to32()
                    })
                );
            }
            emit DelegateCheckpointed(_account);
        }
    }

    /**
     * @dev Get the address `account` is currently delegating to.
     */
    function delegates(address account) public view virtual returns (address) {
        return _delegates[account];
    }

    /**
     * @dev Gets the current votes balance for `account`
     */
    function getVotes(address account) external view returns (uint256) {
        return getPastVotes(account, block.timestamp);
    }

    /**
     * @dev Get the `pos`-th checkpoint for `account`.
     */
    function checkpoints(address account, uint32 pos) external view virtual returns (DelegateeCheckpoint memory) {
        return _checkpointedVotes[account][pos];
    }

    /**
     * @dev Get number of checkpoints for `account`.
     */
    function numCheckpoints(address account) external view virtual returns (uint32) {
        return _checkpointedVotes[account].length.to32();
    }

    /**
     * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
     */
    function getPastVotes(address account, uint256 timestamp) public view returns (uint256 votes) {
        require(timestamp <= block.timestamp, "ERC20Votes: block not yet mined");
        uint256 epoch = timestamp.div(rewardsDuration).mul(rewardsDuration);
        DelegateeCheckpoint memory ckpt = _checkpointsLookup(_checkpointedVotes[account], epoch);
        votes = ckpt.votes;
        if (votes == 0 || ckpt.epochStart + lockDuration <= epoch) {
            return 0;
        }
        while (epoch > ckpt.epochStart) {
            votes -= delegateeUnlocks[account][epoch];
            epoch -= rewardsDuration;
        }
    }

    /**
     * @dev Retrieve the `totalSupply` at the end of `timestamp`. Note, this value is the sum of all balances.
     * It is but NOT the sum of all the delegated votes!
     */
    function getPastTotalSupply(uint256 timestamp) external view returns (uint256) {
        require(timestamp < block.timestamp, "ERC20Votes: block not yet mined");
        return totalSupplyAtEpoch(findEpochId(timestamp));
    }

    /**
     * @dev Lookup a value in a list of (sorted) checkpoints.
     *      Copied from oz/ERC20Votes.sol
     */
    function _checkpointsLookup(DelegateeCheckpoint[] storage ckpts, uint256 epochStart)
        private
        view
        returns (DelegateeCheckpoint memory)
    {
        uint256 high = ckpts.length;
        uint256 low = 0;
        while (low < high) {
            uint256 mid = AuraMath.average(low, high);
            if (ckpts[mid].epochStart > epochStart) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        return high == 0 ? DelegateeCheckpoint(0, 0) : ckpts[high - 1];
    }

    /***************************************
                VIEWS - BALANCES
    ****************************************/

    // Balance of an account which only includes properly locked tokens as of the most recent eligible epoch
    function balanceOf(address _user) external view returns (uint256 amount) {
        return balanceAtEpochOf(findEpochId(block.timestamp), _user);
    }

    // Balance of an account which only includes properly locked tokens at the given epoch
    function balanceAtEpochOf(uint256 _epoch, address _user) public view returns (uint256 amount) {
        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));
        require(epochStart < block.timestamp, "Epoch is in the future");

        uint256 cutoffEpoch = epochStart.sub(lockDuration);

        LockedBalance[] storage locks = userLocks[_user];

        //need to add up since the range could be in the middle somewhere
        //traverse inversely to make more current queries more gas efficient
        uint256 locksLength = locks.length;
        for (uint256 i = locksLength; i > 0; i--) {
            uint256 lockEpoch = uint256(locks[i - 1].unlockTime).sub(lockDuration);
            //lock epoch must be less or equal to the epoch we're basing from.
            //also not include the current epoch
            if (lockEpoch < epochStart) {
                if (lockEpoch > cutoffEpoch) {
                    amount = amount.add(locks[i - 1].amount);
                } else {
                    //stop now as no futher checks matter
                    break;
                }
            }
        }

        return amount;
    }

    // Information on a user's locked balances
    function lockedBalances(address _user)
        external
        view
        returns (
            uint256 total,
            uint256 unlockable,
            uint256 locked,
            LockedBalance[] memory lockData
        )
    {
        LockedBalance[] storage locks = userLocks[_user];
        Balances storage userBalance = balances[_user];
        uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
        uint256 idx;
        for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
            if (locks[i].unlockTime > block.timestamp) {
                if (idx == 0) {
                    lockData = new LockedBalance[](locks.length - i);
                }
                lockData[idx] = locks[i];
                idx++;
                locked = locked.add(locks[i].amount);
            } else {
                unlockable = unlockable.add(locks[i].amount);
            }
        }
        return (userBalance.locked, unlockable, locked, lockData);
    }

    // Supply of all properly locked balances at most recent eligible epoch
    function totalSupply() external view returns (uint256 supply) {
        return totalSupplyAtEpoch(findEpochId(block.timestamp));
    }

    // Supply of all properly locked balances at the given epoch
    function totalSupplyAtEpoch(uint256 _epoch) public view returns (uint256 supply) {
        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));
        require(epochStart < block.timestamp, "Epoch is in the future");

        uint256 cutoffEpoch = epochStart.sub(lockDuration);
        uint256 lastIndex = epochs.length - 1;

        uint256 epochIndex = _epoch > lastIndex ? lastIndex : _epoch;

        for (uint256 i = epochIndex + 1; i > 0; i--) {
            Epoch memory e = epochs[i - 1];
            if (e.date == epochStart) {
                continue;
            } else if (e.date <= cutoffEpoch) {
                break;
            } else {
                supply += e.supply;
            }
        }
    }

    // Get an epoch index based on timestamp
    function findEpochId(uint256 _time) public view returns (uint256 epoch) {
        return _time.sub(epochs[0].date).div(rewardsDuration);
    }

    /***************************************
                VIEWS - GENERAL
    ****************************************/

    // Number of epochs
    function epochCount() external view returns (uint256) {
        return epochs.length;
    }

    function decimals() external view returns (uint8) {
        return _decimals;
    }

    function name() external view returns (string memory) {
        return _name;
    }

    function symbol() external view returns (string memory) {
        return _symbol;
    }

    /***************************************
                VIEWS - REWARDS
    ****************************************/

    // Address and claimable amount of all reward tokens for the given account
    function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {
        userRewards = new EarnedData[](rewardTokens.length);
        Balances storage userBalance = balances[_account];
        uint256 userRewardsLength = userRewards.length;
        for (uint256 i = 0; i < userRewardsLength; i++) {
            address token = rewardTokens[i];
            userRewards[i].token = token;
            userRewards[i].amount = _earned(_account, token, userBalance.locked);
        }
        return userRewards;
    }

    function lastTimeRewardApplicable(address _rewardsToken) external view returns (uint256) {
        return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
    }

    function rewardPerToken(address _rewardsToken) external view returns (uint256) {
        return _rewardPerToken(_rewardsToken);
    }

    function _earned(
        address _user,
        address _rewardsToken,
        uint256 _balance
    ) internal view returns (uint256) {
        UserData memory data = userData[_user][_rewardsToken];
        return _balance.mul(_rewardPerToken(_rewardsToken).sub(data.rewardPerTokenPaid)).div(1e18).add(data.rewards);
    }

    function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
        return AuraMath.min(block.timestamp, _finishTime);
    }

    function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {
        if (lockedSupply == 0) {
            return rewardData[_rewardsToken].rewardPerTokenStored;
        }
        return
            uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
                _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)
                    .sub(rewardData[_rewardsToken].lastUpdateTime)
                    .mul(rewardData[_rewardsToken].rewardRate)
                    .mul(1e18)
                    .div(lockedSupply)
            );
    }

    /***************************************
                REWARD FUNDING
    ****************************************/

    function queueNewRewards(address _rewardsToken, uint256 _rewards) external nonReentrant {
        require(rewardDistributors[_rewardsToken][msg.sender], "!authorized");
        require(_rewards > 0, "No reward");

        RewardData storage rdata = rewardData[_rewardsToken];

        IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _rewards);

        _rewards = _rewards.add(queuedRewards[_rewardsToken]);
        require(_rewards < 1e25, "!rewards");

        if (block.timestamp >= rdata.periodFinish) {
            _notifyReward(_rewardsToken, _rewards);
            queuedRewards[_rewardsToken] = 0;
            return;
        }

        //et = now - (finish-duration)
        uint256 elapsedTime = block.timestamp.sub(rdata.periodFinish.sub(rewardsDuration.to32()));
        //current at now: rewardRate * elapsedTime
        uint256 currentAtNow = rdata.rewardRate * elapsedTime;
        uint256 queuedRatio = currentAtNow.mul(1000).div(_rewards);
        if (queuedRatio < newRewardRatio) {
            _notifyReward(_rewardsToken, _rewards);
            queuedRewards[_rewardsToken] = 0;
        } else {
            queuedRewards[_rewardsToken] = _rewards;
        }
    }

    function _notifyReward(address _rewardsToken, uint256 _reward) internal updateReward(address(0)) {
        RewardData storage rdata = rewardData[_rewardsToken];

        if (block.timestamp >= rdata.periodFinish) {
            rdata.rewardRate = _reward.div(rewardsDuration).to96();
        } else {
            uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
            uint256 leftover = remaining.mul(rdata.rewardRate);
            rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to96();
        }

        // Equivalent to 10 million tokens over a weeks duration
        require(rdata.rewardRate < 1e20, "!rewardRate");
        require(lockedSupply >= 1e20, "!balance");

        rdata.lastUpdateTime = block.timestamp.to32();
        rdata.periodFinish = block.timestamp.add(rewardsDuration).to32();

        emit RewardAdded(_rewardsToken, _reward);
    }
}
IAuraLocker.sol 22 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

interface IAuraLocker {
    function isShutdown() external view returns (bool);

    function lock(address _account, uint256 _amount) external;

    function checkpointEpoch() external;

    function epochCount() external view returns (uint256);

    function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);

    function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply);

    function queueNewRewards(address _rewardsToken, uint256 reward) external;

    function getReward(address _account, bool _stake) external;

    function getReward(address _account) external;
}
IRewardStaking.sol 14 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

interface IRewardStaking {
    function getReward(address _account, bool _claimExtras) external;

    function getReward(address _account) external;

    function getReward(address _account, address _token) external;

    function stakeFor(address, uint256) external;

    function processIdleRewards() external;
}
AuraMath.sol 88 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library AuraMath {
    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a + b;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a - b;
    }

    function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a * b;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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, so we distribute.
        return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
    }

    function to224(uint256 a) internal pure returns (uint224 c) {
        require(a <= type(uint224).max, "AuraMath: uint224 Overflow");
        c = uint224(a);
    }

    function to128(uint256 a) internal pure returns (uint128 c) {
        require(a <= type(uint128).max, "AuraMath: uint128 Overflow");
        c = uint128(a);
    }

    function to112(uint256 a) internal pure returns (uint112 c) {
        require(a <= type(uint112).max, "AuraMath: uint112 Overflow");
        c = uint112(a);
    }

    function to96(uint256 a) internal pure returns (uint96 c) {
        require(a <= type(uint96).max, "AuraMath: uint96 Overflow");
        c = uint96(a);
    }

    function to32(uint256 a) internal pure returns (uint32 c) {
        require(a <= type(uint32).max, "AuraMath: uint32 Overflow");
        c = uint32(a);
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library AuraMath32 {
    function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
        c = a - b;
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
library AuraMath112 {
    function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
        c = a + b;
    }

    function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
        c = a - b;
    }
}

/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
library AuraMath224 {
    function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
        c = a + b;
    }
}

Read Contract

balanceAtEpochOf 0x1c607395 → uint256
balanceOf 0x70a08231 → uint256
balances 0x27e235e3 → uint112, uint32
blacklist 0xf9f92be4 → bool
checkpoints 0xf1127ed8 → tuple
claimableRewards 0xdc01f60d → tuple[]
cvxCrv 0x82480df9 → address
cvxcrvStaking 0xae8d4825 → address
decimals 0x313ce567 → uint8
delegateeUnlocks 0xb79c0303 → uint256
delegates 0x587cde1e → address
denominator 0x96ce0795 → uint256
epochCount 0x829965cc → uint256
epochs 0xc6b61e4c → uint224, uint32
findEpochId 0xf8261597 → uint256
getPastTotalSupply 0x8e539e8c → uint256
getPastVotes 0x3a46b1a8 → uint256
getVotes 0x9ab24eb0 → uint256
isShutdown 0xbf86d690 → bool
kickRewardEpochDelay 0xe432488d → uint256
kickRewardPerEpoch 0x9bdc7467 → uint256
lastTimeRewardApplicable 0x638634ee → uint256
lockDuration 0x04554443 → uint256
lockedBalances 0x0483a7f6 → uint256, uint256, uint256, tuple[]
lockedSupply 0xca5c7b91 → uint256
name 0x06fdde03 → string
newRewardRatio 0x6c8bcee8 → uint256
numCheckpoints 0x6fcfff45 → uint32
owner 0x8da5cb5b → address
queuedRewards 0xb53a6a71 → uint256
rewardData 0x48e5d9f8 → uint32, uint32, uint96, uint96
rewardDistributors 0x39fc9713 → bool
rewardPerToken 0xf1229777 → uint256
rewardTokens 0x7bb7bed1 → address
rewardsDuration 0x386a9525 → uint256
stakingToken 0x72f702f3 → address
symbol 0x95d89b41 → string
totalSupply 0x18160ddd → uint256
totalSupplyAtEpoch 0x70b36d79 → uint256
userData 0x768e5b27 → uint128, uint128
userLocks 0xaa33fedb → uint112, uint32

Write Contract 19 functions

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

addReward 0x40b47e1a
address _rewardsToken
address _distributor
approveRewardDistributor 0x6724c910
address _rewardsToken
address _distributor
bool _approved
checkpointEpoch 0xc1009f4b
No parameters
delegate 0x5c19a95c
address newDelegatee
emergencyWithdraw 0xdb2e21bc
No parameters
getReward 0x7050ccd9
address _account
bool _stake
getReward 0xc00007b0
address _account
getReward 0xd336ecfb
address _account
bool[] _skipIdx
kickExpiredLocks 0x887c7dc5
address _account
lock 0x282d3fdf
address _account
uint256 _amount
modifyBlacklist 0xcc6df138
address _account
bool _blacklisted
processExpiredLocks 0x312ff839
bool _relock
queueNewRewards 0x04d0c2c5
address _rewardsToken
uint256 _rewards
recoverERC20 0x8980f11f
address _tokenAddress
uint256 _tokenAmount
renounceOwnership 0x715018a6
No parameters
setApprovals 0x8757b15b
No parameters
setKickIncentive 0x63f1c8e2
uint256 _rate
uint256 _delay
shutdown 0xfc0e74d1
No parameters
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address