Address Contract Partially Verified
Address
0x5A7b3CDe8aC8d780AF4797BF1517464aC54Ca033
Balance
0 ETH
Nonce
1
Code Size
12651 bytes
Creator
0x207E8047...82f8 at tx 0xbbb2e0ab...4225a8
Indexed Transactions
0
Contract Bytecode
12651 bytes
0x6080604052600436106101dc5760003560e01c80639010d07c11610102578063c02d4c8e11610095578063ddd5e1b211610064578063ddd5e1b21461069d578063ec87621c146106bd578063ee99205c146106f1578063fe3af1c11461071e57610213565b8063c02d4c8e14610632578063ca15c87314610647578063d547741f14610667578063d54ad2a11461068757610213565b8063ae5cf272116100d1578063ae5cf272146105d2578063b2d42b46146105e8578063b5475cf6146105fd578063b69ef8a81461061d57610213565b80639010d07c146104a257806391d14854146104c25780639a6e6ed114610515578063a217fddf146105bd57610213565b806329e848671161017a5780634d13bfa6116101495780634d13bfa6146104215780634f588bf1146104295780636a84a985146104605780637dc0d1d01461047557610213565b806329e848671461036f5780632d830ce3146103c15780632f2ff15d146103e157806336568abe1461040157610213565b80631e846464116101b65780631e846464146102b3578063248a9ca3146102d3578063278c5acd1461030357806328ad3aac1461034d57610213565b806301ffc9a714610245578063106b263c1461027a5780631453444d1461029d57610213565b36610213576040517f34352c7300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f34352c7300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b34801561025157600080fd5b50610265610260366004612a99565b610752565b60405190151581526020015b60405180910390f35b34801561028657600080fd5b5061028f6107ae565b604051908152602001610271565b3480156102a957600080fd5b5061028f60cb5481565b3480156102bf57600080fd5b506102656102ce366004612adb565b6107fe565b3480156102df57600080fd5b5061028f6102ee366004612adb565b60009081526065602052604090206001015490565b34801561030f57600080fd5b5060cf5461032c906fffffffffffffffffffffffffffffffff1681565b6040516fffffffffffffffffffffffffffffffff9091168152602001610271565b34801561035957600080fd5b5061036d610368366004612adb565b610d56565b005b34801561037b57600080fd5b5060ce5461039c9073ffffffffffffffffffffffffffffffffffffffff1681565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610271565b3480156103cd57600080fd5b5061036d6103dc366004612b55565b610e19565b3480156103ed57600080fd5b5061036d6103fc366004612c30565b611095565b34801561040d57600080fd5b5061036d61041c366004612c30565b6110bf565b61036d61116e565b34801561043557600080fd5b50610449610444366004612adb565b6111d8565b604080519215158352602083019190915201610271565b34801561046c57600080fd5b5060d05461028f565b34801561048157600080fd5b5060ca5461039c9073ffffffffffffffffffffffffffffffffffffffff1681565b3480156104ae57600080fd5b5061039c6104bd366004612c60565b611318565b3480156104ce57600080fd5b506102656104dd366004612c30565b600091825260656020908152604080842073ffffffffffffffffffffffffffffffffffffffff93909316845291905290205460ff1690565b34801561052157600080fd5b50610535610530366004612adb565b611337565b6040516102719190600060c08201905067ffffffffffffffff835116825273ffffffffffffffffffffffffffffffffffffffff602084015116602083015260408301516fffffffffffffffffffffffffffffffff80821660408501528060608601511660608501528060808601511660808501528060a08601511660a0850152505092915050565b3480156105c957600080fd5b5061028f600081565b3480156105de57600080fd5b5061028f60cd5481565b3480156105f457600080fd5b5061036d61142f565b34801561060957600080fd5b5061028f610618366004612ca0565b611538565b34801561062957600080fd5b5061028f6117c2565b34801561063e57600080fd5b5061028f6117e0565b34801561065357600080fd5b5061028f610662366004612adb565b611823565b34801561067357600080fd5b5061036d610682366004612c30565b61183a565b34801561069357600080fd5b5061028f60cc5481565b3480156106a957600080fd5b5061036d6106b8366004612c30565b61185f565b3480156106c957600080fd5b5061028f7f241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b0881565b3480156106fd57600080fd5b5060c95461039c9073ffffffffffffffffffffffffffffffffffffffff1681565b34801561072a57600080fd5b5061028f7fef6d3da212345543d99125b43af0bc451d30ffaf90d4560558d702b21179a70f81565b60007fffffffff0000000000000000000000000000000000000000000000000000000082167f5a05180f0000000000000000000000000000000000000000000000000000000014806107a857506107a882611ca0565b92915050565b60cb5460cf546000916fffffffffffffffffffffffffffffffff90911611156107f85760cb5460cf546107f391906fffffffffffffffffffffffffffffffff16612d1a565b905090565b50600090565b60007fef6d3da212345543d99125b43af0bc451d30ffaf90d4560558d702b21179a70f61082a81611d37565b60d0546000819003610840576000925050610d50565b8381101561084c578093505b60008467ffffffffffffffff81111561086757610867612af4565b6040519080825280602002602001820160405280156108e557816020015b6040805160c08101825260008082526020808301829052928201819052606082018190526080820181905260a082015282527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092019101816108855790505b5090506000805b86821015610b4e5760d080546000919061090890600190612d1a565b8154811061091857610918612d2d565b60009182526020918290206040805160c0810182526003909302909101805467ffffffffffffffff8116845273ffffffffffffffffffffffffffffffffffffffff68010000000000000000909104169383019390935260018301546fffffffffffffffffffffffffffffffff80821692840192909252700100000000000000000000000000000000908190048216606084015260029093015480821660808401529290920490911660a082015290506109d081611d44565b156109db5750610b4e565b60d08054806109ec576109ec612d5c565b60008281526020812060037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9093019283020180547fffffffff000000000000000000000000000000000000000000000000000000001681556001810182905560020155905583518190859085908110610a6857610a68612d2d565b602002602001018190525082610a7d90612d8b565b9250806080015182610a8f9190612dc3565b9150806020015173ffffffffffffffffffffffffffffffffffffffff1681604001516fffffffffffffffffffffffffffffffff167ff8d5df096390c80d709314ba3a8e55a91854bab1fbf8cce78081bdd48eb49aed836060015184608001518560a001518660000151604051610b4094939291906fffffffffffffffffffffffffffffffff948516815292841660208401529216604082015267ffffffffffffffff91909116606082015260800190565b60405180910390a3506108ec565b6fffffffffffffffffffffffffffffffff811615610bc45760cf8054829190600090610b8d9084906fffffffffffffffffffffffffffffffff16612dec565b92506101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055505b60d054600090808203610bda5760009150610cb6565b600060d0610be9600184612d1a565b81548110610bf957610bf9612d2d565b60009182526020918290206040805160c0810182526003909302909101805467ffffffffffffffff8116845273ffffffffffffffffffffffffffffffffffffffff68010000000000000000909104169383019390935260018301546fffffffffffffffffffffffffffffffff80821692840192909252700100000000000000000000000000000000908190048216606084015260029093015480821660808401529290920490911660a08201529050610cb181611d44565b159250505b60005b84811015610d465760ce548651610d349173ffffffffffffffffffffffffffffffffffffffff1690889084908110610cf357610cf3612d2d565b602002602001015160200151888481518110610d1157610d11612d2d565b6020026020010151606001516fffffffffffffffffffffffffffffffff16611e0b565b80610d3e81612d8b565b915050610cb9565b5090965050505050505b50919050565b7f241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b08610d8081611d37565b60cd82905560408051602081018490527f28ad3aac00000000000000000000000000000000000000000000000000000000917f01d854e8dde9402801a4c6f2840193465752abfad61e0bb7c4258d526ae42e749101604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081840301815290829052610e0d91612e83565b60405180910390a25050565b600054610100900460ff1615808015610e395750600054600160ff909116105b80610e535750303b158015610e53575060005460ff166001145b610ee4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a656400000000000000000000000000000000000060648201526084015b60405180910390fd5b600080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790558015610f4257600080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff166101001790555b610f4a611e98565b8151610f5890600090611f2f565b60c082015160cd55608082015160c9805473ffffffffffffffffffffffffffffffffffffffff9283167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560a084015160ca8054918416918316919091179055606084015160ce80549190931691161790556020820151611000907f241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b0890611f2f565b61102e7fef6d3da212345543d99125b43af0bc451d30ffaf90d4560558d702b21179a70f8360400151611f2f565b801561109157600080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050565b6000828152606560205260409020600101546110b081611d37565b6110ba8383611f2f565b505050565b73ffffffffffffffffffffffffffffffffffffffff81163314611164576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c6600000000000000000000000000000000006064820152608401610edb565b6110918282611f51565b60c95473ffffffffffffffffffffffffffffffffffffffff1633146111bf576040517f135420fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b3460cb60008282546111d19190612ef0565b9091555050565b600080600060d084815481106111f0576111f0612d2d565b600091825260208083206040805160c0810182526003909402909101805467ffffffffffffffff8116855273ffffffffffffffffffffffffffffffffffffffff68010000000000000000909104169284019290925260018201546fffffffffffffffffffffffffffffffff8082169285019290925270010000000000000000000000000000000090819004821660608501526002909201548082166080850152919091041660a082015291506112a582611d44565b905060008083608001518460a001516112be9190612dec565b6fffffffffffffffffffffffffffffffff16905060cb5481101561130c576113098160cb546112ed9190612d1a565b85608001516fffffffffffffffffffffffffffffffff16611f73565b91505b50909590945092505050565b60008281526097602052604081206113309083611f89565b9392505050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915260d0828154811061137c5761137c612d2d565b60009182526020918290206040805160c0810182526003909302909101805467ffffffffffffffff8116845273ffffffffffffffffffffffffffffffffffffffff68010000000000000000909104169383019390935260018301546fffffffffffffffffffffffffffffffff80821692840192909252700100000000000000000000000000000000908190048216606084015260029093015480821660808401529290920490911660a082015292915050565b60c95473ffffffffffffffffffffffffffffffffffffffff163314611480576040517f135420fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600061148a6117e0565b9050806000036114975750565b8060cb60008282546114a99190612d1a565b909155505060c954604080517fc151aa72000000000000000000000000000000000000000000000000000000008152905173ffffffffffffffffffffffffffffffffffffffff9092169163c151aa72918491600480830192600092919082900301818588803b15801561151b57600080fd5b505af115801561152f573d6000803e3d6000fd5b5050505050505b565b60c95460009073ffffffffffffffffffffffffffffffffffffffff16331461158c576040517f135420fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60cf546000906115af9084906fffffffffffffffffffffffffffffffff16612dc3565b60d080546040805160c08101825267ffffffffffffffff43818116835273ffffffffffffffffffffffffffffffffffffffff808d16602085018181526fffffffffffffffffffffffffffffffff8089168789019081528f8216606089019081528f831660808a01908152838e1660a08b0181815260018e018f5560009e909e528a5160038e027fe89d44c8fd6a9bac8af33ce47f56337617d449bf7ff3956b618c646de829cbcb810180549851909a1668010000000000000000027fffffffff0000000000000000000000000000000000000000000000000000000090981691909b161795909517909655905190518216700100000000000000000000000000000000908102918316919091177fe89d44c8fd6a9bac8af33ce47f56337617d449bf7ff3956b618c646de829cbcc88015593519951811690930298909216979097177fe89d44c8fd6a9bac8af33ce47f56337617d449bf7ff3956b618c646de829cbcd9093019290925560cf80547fffffffffffffffffffffffffffffffff00000000000000000000000000000000169092179091559151949550919391929184917fed5afdabca1838de7f5496f997e6e788ad3207f6299f64700e63435813b7ade4916117b0918b918b918a916fffffffffffffffffffffffffffffffff9485168152928416602084015292166040820152606081019190915260800190565b60405180910390a35095945050505050565b600060cc5460cb5411156107f85760cc5460cb546107f39190612d1a565b60cf5460cb546000916fffffffffffffffffffffffffffffffff1610156107f85760cf5460cb546107f3916fffffffffffffffffffffffffffffffff1690612d1a565b60008181526097602052604081206107a890611f95565b60008281526065602052604090206001015461185581611d37565b6110ba8383611f51565b60c95473ffffffffffffffffffffffffffffffffffffffff1633146118b0576040517f135420fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060d083815481106118c5576118c5612d2d565b60009182526020918290206040805160c0810182526003909302909101805467ffffffffffffffff8116845273ffffffffffffffffffffffffffffffffffffffff680100000000000000009091041693830184905260018101546fffffffffffffffffffffffffffffffff8082169385019390935270010000000000000000000000000000000090819004831660608501526002909101548083166080850152041660a082015291506119a4576040517f646cf55800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b806020015173ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614611a0d576040517fe39da59e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611a1681611d44565b611a4c576040517f1bee0d5a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60cb548160a001516fffffffffffffffffffffffffffffffff161115611ac05760a081015160cb546040517f8c9053680000000000000000000000000000000000000000000000000000000081526fffffffffffffffffffffffffffffffff90921660048301526024820152604401610edb565b60d08381548110611ad357611ad3612d2d565b60009182526020822060039091020180547fffffffff0000000000000000000000000000000000000000000000000000000016815560018101829055600201819055608082015160cc80546fffffffffffffffffffffffffffffffff92909216929091611b41908490612ef0565b925050819055508173ffffffffffffffffffffffffffffffffffffffff16837f5de6f9e4fdf1b740a7ba3b485303743eec250be281a2dd4df046c7fcecbdb04d836060015184608001518560a001518660000151604051611bdd94939291906fffffffffffffffffffffffffffffffff948516815292841660208401529216604082015267ffffffffffffffff91909116606082015260800190565b60405180910390a360ce5460608201516040517f42966c680000000000000000000000000000000000000000000000000000000081526fffffffffffffffffffffffffffffffff909116600482015273ffffffffffffffffffffffffffffffffffffffff909116906342966c6890602401600060405180830381600087803b158015611c6857600080fd5b505af1158015611c7c573d6000803e3d6000fd5b505050506110ba8282608001516fffffffffffffffffffffffffffffffff16611f9f565b60007fffffffff0000000000000000000000000000000000000000000000000000000082167f7965db0b0000000000000000000000000000000000000000000000000000000014806107a857507f01ffc9a7000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008316146107a8565b611d4181336120f9565b50565b60ca54604080517ff3a009a0000000000000000000000000000000000000000000000000000000008152905160009273ffffffffffffffffffffffffffffffffffffffff169163f3a009a0916004808301926101009291908290030181865afa158015611db5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dd99190612f26565b6020015167ffffffffffffffff1660cd54836000015167ffffffffffffffff16611e039190612ef0565b111592915050565b6040805173ffffffffffffffffffffffffffffffffffffffff8416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001790526110ba9084906121b3565b600054610100900460ff16611536576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201527f6e697469616c697a696e670000000000000000000000000000000000000000006064820152608401610edb565b611f3982826122c2565b60008281526097602052604090206110ba90826123b6565b611f5b82826123d8565b60008281526097602052604090206110ba9082612493565b6000818310611f825781611330565b5090919050565b600061133083836124b5565b60006107a8825490565b80471015612009576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e63650000006044820152606401610edb565b60008273ffffffffffffffffffffffffffffffffffffffff168260405160006040518083038185875af1925050503d8060008114612063576040519150601f19603f3d011682016040523d82523d6000602084013e612068565b606091505b50509050806110ba576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d617920686176652072657665727465640000000000006064820152608401610edb565b600082815260656020908152604080832073ffffffffffffffffffffffffffffffffffffffff8516845290915290205460ff1661109157612139816124df565b6121448360206124fe565b604051602001612155929190613017565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0818403018152908290527f08c379a0000000000000000000000000000000000000000000000000000000008252610edb91600401613098565b6000612215826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff166127419092919063ffffffff16565b905080516000148061223657508080602001905181019061223691906130ab565b6110ba576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610edb565b600082815260656020908152604080832073ffffffffffffffffffffffffffffffffffffffff8516845290915290205460ff1661109157600082815260656020908152604080832073ffffffffffffffffffffffffffffffffffffffff85168452909152902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790556123583390565b73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60006113308373ffffffffffffffffffffffffffffffffffffffff8416612758565b600082815260656020908152604080832073ffffffffffffffffffffffffffffffffffffffff8516845290915290205460ff161561109157600082815260656020908152604080832073ffffffffffffffffffffffffffffffffffffffff8516808552925280832080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60006113308373ffffffffffffffffffffffffffffffffffffffff84166127a7565b60008260000182815481106124cc576124cc612d2d565b9060005260206000200154905092915050565b60606107a873ffffffffffffffffffffffffffffffffffffffff831660145b6060600061250d8360026130cd565b612518906002612ef0565b67ffffffffffffffff81111561253057612530612af4565b6040519080825280601f01601f19166020018201604052801561255a576020820181803683370190505b5090507f30000000000000000000000000000000000000000000000000000000000000008160008151811061259157612591612d2d565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053507f7800000000000000000000000000000000000000000000000000000000000000816001815181106125f4576125f4612d2d565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060006126308460026130cd565b61263b906001612ef0565b90505b60018111156126d8577f303132333435363738396162636465660000000000000000000000000000000085600f166010811061267c5761267c612d2d565b1a60f81b82828151811061269257612692612d2d565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060049490941c936126d1816130e4565b905061263e565b508315611330576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610edb565b606061275084846000856128a1565b949350505050565b600081815260018301602052604081205461279f575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556107a8565b5060006107a8565b600081815260018301602052604081205480156128905760006127cb600183612d1a565b85549091506000906127df90600190612d1a565b90508181146128445760008660000182815481106127ff576127ff612d2d565b906000526020600020015490508087600001848154811061282257612822612d2d565b6000918252602080832090910192909255918252600188019052604090208390555b855486908061285557612855612d5c565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506107a8565b60009150506107a8565b5092915050565b606082471015612933576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c00000000000000000000000000000000000000000000000000006064820152608401610edb565b6000808673ffffffffffffffffffffffffffffffffffffffff16858760405161295c9190613119565b60006040518083038185875af1925050503d8060008114612999576040519150601f19603f3d011682016040523d82523d6000602084013e61299e565b606091505b50915091506129af878383876129ba565b979650505050505050565b60608315612a50578251600003612a495773ffffffffffffffffffffffffffffffffffffffff85163b612a49576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610edb565b5081612750565b6127508383815115612a655781518083602001fd5b806040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610edb9190613098565b600060208284031215612aab57600080fd5b81357fffffffff000000000000000000000000000000000000000000000000000000008116811461133057600080fd5b600060208284031215612aed57600080fd5b5035919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b73ffffffffffffffffffffffffffffffffffffffff81168114611d4157600080fd5b8035612b5081612b23565b919050565b600060e08284031215612b6757600080fd5b60405160e0810181811067ffffffffffffffff82111715612bb1577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6040528235612bbf81612b23565b81526020830135612bcf81612b23565b60208201526040830135612be281612b23565b60408201526060830135612bf581612b23565b6060820152612c0660808401612b45565b6080820152612c1760a08401612b45565b60a082015260c083013560c08201528091505092915050565b60008060408385031215612c4357600080fd5b823591506020830135612c5581612b23565b809150509250929050565b60008060408385031215612c7357600080fd5b50508035926020909101359150565b6fffffffffffffffffffffffffffffffff81168114611d4157600080fd5b600080600060608486031215612cb557600080fd5b8335612cc081612b23565b92506020840135612cd081612c82565b91506040840135612ce081612c82565b809150509250925092565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b818103818111156107a8576107a8612ceb565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603160045260246000fd5b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203612dbc57612dbc612ceb565b5060010190565b6fffffffffffffffffffffffffffffffff81811683821601908082111561289a5761289a612ceb565b6fffffffffffffffffffffffffffffffff82811682821603908082111561289a5761289a612ceb565b60005b83811015612e30578181015183820152602001612e18565b50506000910152565b60008151808452612e51816020860160208601612e15565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b60408152602460408201527f7365744e756d6265724f66426c6f636b73546f46696e616c697a652875696e7460608201527f3235362900000000000000000000000000000000000000000000000000000000608082015260a06020820152600061133060a0830184612e39565b808201808211156107a8576107a8612ceb565b805167ffffffffffffffff81168114612b5057600080fd5b8051612b5081612c82565b6000610100808385031215612f3a57600080fd5b6040519081019067ffffffffffffffff82118183101715612f84577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b81604052612f9184612f03565b8152612f9f60208501612f03565b6020820152612fb060408501612f03565b6040820152612fc160608501612f03565b606082015260808401519150612fd682612c82565b816080820152612fe860a08501612f1b565b60a0820152612ff960c08501612f1b565b60c082015261300a60e08501612f1b565b60e0820152949350505050565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161304f816017850160208801612e15565b7f206973206d697373696e6720726f6c6520000000000000000000000000000000601791840191820152835161308c816028840160208801612e15565b01602801949350505050565b6020815260006113306020830184612e39565b6000602082840312156130bd57600080fd5b8151801515811461133057600080fd5b80820281158282048414176107a8576107a8612ceb565b6000816130f3576130f3612ceb565b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b6000825161312b818460208701612e15565b919091019291505056fea2646970667358221220ec1ddad0817e188696169f9f1509d86834039ef60b7736295c0b44219de2081764736f6c63430008140033
Verified Source Code Partial Match
Compiler: v0.8.20+commit.a1b79de6
EVM: paris
Optimization: Yes (1000000 runs)
Staking.sol 730 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Initializable} from "openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlEnumerableUpgradeable} from
"openzeppelin-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {Math} from "openzeppelin/utils/math/Math.sol";
import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
import {SafeERC20Upgradeable} from "openzeppelin-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {ProtocolEvents} from "./interfaces/ProtocolEvents.sol";
import {IDepositContract} from "./interfaces/IDepositContract.sol";
import {IMETH} from "./interfaces/IMETH.sol";
import {IOracleReadRecord, OracleRecord} from "./interfaces/IOracle.sol";
import {IPauserRead} from "./interfaces/IPauser.sol";
import {IStaking, IStakingReturnsWrite, IStakingInitiationRead} from "./interfaces/IStaking.sol";
import {UnstakeRequest, IUnstakeRequestsManager} from "./interfaces/IUnstakeRequestsManager.sol";
/// @notice Events emitted by the staking contract.
interface StakingEvents {
/// @notice Emitted when a user stakes ETH and receives mETH.
/// @param staker The address of the user staking ETH.
/// @param ethAmount The amount of ETH staked.
/// @param mETHAmount The amount of mETH received.
event Staked(address indexed staker, uint256 ethAmount, uint256 mETHAmount);
/// @notice Emitted when a user unstakes mETH in exchange for ETH.
/// @param id The ID of the unstake request.
/// @param staker The address of the user unstaking mETH.
/// @param ethAmount The amount of ETH that the staker will receive.
/// @param mETHLocked The amount of mETH that will be burned.
event UnstakeRequested(uint256 indexed id, address indexed staker, uint256 ethAmount, uint256 mETHLocked);
/// @notice Emitted when a user claims their unstake request.
/// @param id The ID of the unstake request.
/// @param staker The address of the user claiming their unstake request.
event UnstakeRequestClaimed(uint256 indexed id, address indexed staker);
/// @notice Emitted when a validator has been initiated (i.e. the protocol has deposited into the deposit contract).
/// @param id The ID of the validator which is the hash of its pubkey.
/// @param operatorID The ID of the node operator to which the validator belongs to.
/// @param pubkey The pubkey of the validator.
/// @param amountDeposited The amount of ETH deposited into the deposit contract for that validator.
event ValidatorInitiated(bytes32 indexed id, uint256 indexed operatorID, bytes pubkey, uint256 amountDeposited);
/// @notice Emitted when the protocol has allocated ETH to the UnstakeRequestsManager.
/// @param amount The amount of ETH allocated to the UnstakeRequestsManager.
event AllocatedETHToUnstakeRequestsManager(uint256 amount);
/// @notice Emitted when the protocol has allocated ETH to use for deposits into the deposit contract.
/// @param amount The amount of ETH allocated to deposits.
event AllocatedETHToDeposits(uint256 amount);
/// @notice Emitted when the protocol has received returns from the returns aggregator.
/// @param amount The amount of ETH received.
event ReturnsReceived(uint256 amount);
}
/// @title Staking
/// @notice Manages stake and unstake requests by users, keeps track of the total amount of ETH controlled by the
/// protocol, and initiates new validators.
contract Staking is Initializable, AccessControlEnumerableUpgradeable, IStaking, StakingEvents, ProtocolEvents {
// Errors.
error DoesNotReceiveETH();
error InvalidConfiguration();
error MaximumValidatorDepositExceeded();
error MaximumMETHSupplyExceeded();
error MinimumStakeBoundNotSatisfied();
error MinimumUnstakeBoundNotSatisfied();
error MinimumValidatorDepositNotSatisfied();
error NotEnoughDepositETH();
error NotEnoughUnallocatedETH();
error NotReturnsAggregator();
error NotUnstakeRequestsManager();
error Paused();
error PreviouslyUsedValidator();
error ZeroAddress();
error InvalidDepositRoot(bytes32);
error StakeBelowMinimumMETHAmount(uint256 methAmount, uint256 expectedMinimum);
error UnstakeBelowMinimumETHAmount(uint256 ethAmount, uint256 expectedMinimum);
error InvalidWithdrawalCredentialsWrongLength(uint256);
error InvalidWithdrawalCredentialsNotETH1(bytes12);
error InvalidWithdrawalCredentialsWrongAddress(address);
/// @notice Role allowed trigger administrative tasks such as allocating funds to / withdrawing surplusses from the
/// UnstakeRequestsManager and setting various parameters on the contract.
bytes32 public constant STAKING_MANAGER_ROLE = keccak256("STAKING_MANAGER_ROLE");
/// @notice Role allowed to allocate funds to unstake requests manager and reserve funds to deposit into the
/// validators.
bytes32 public constant ALLOCATOR_SERVICE_ROLE = keccak256("ALLOCATER_SERVICE_ROLE");
/// @notice Role allowed to initiate new validators by sending funds from the allocatedETHForDeposits balance
/// to the beacon chain deposit contract.
bytes32 public constant INITIATOR_SERVICE_ROLE = keccak256("INITIATOR_SERVICE_ROLE");
/// @notice Role to manage the staking allowlist.
bytes32 public constant STAKING_ALLOWLIST_MANAGER_ROLE = keccak256("STAKING_ALLOWLIST_MANAGER_ROLE");
/// @notice Role allowed to stake ETH when allowlist is enabled.
bytes32 public constant STAKING_ALLOWLIST_ROLE = keccak256("STAKING_ALLOWLIST_ROLE");
/// @notice Role allowed to top up the unallocated ETH in the protocol.
bytes32 public constant TOP_UP_ROLE = keccak256("TOP_UP_ROLE");
/// @notice Payload struct submitted for validator initiation.
/// @dev See also {initiateValidatorsWithDeposits}.
struct ValidatorParams {
uint256 operatorID;
uint256 depositAmount;
bytes pubkey;
bytes withdrawalCredentials;
bytes signature;
bytes32 depositDataRoot;
}
/// @notice Keeps track of already initiated validators.
/// @dev This is tracked to ensure that we never deposit for the same validator public key twice, which is a base
/// assumption of this contract and the related off-chain accounting.
mapping(bytes pubkey => bool exists) public usedValidators;
/// @inheritdoc IStakingInitiationRead
/// @dev This is needed to account for ETH that is still in flight, i.e. that has been sent to the deposit contract
/// but has not been processed by the beacon chain yet. Once the off-chain oracle detects those deposits, they are
/// recorded as `totalDepositsProcessed` in the oracle contract to avoid double counting. See also
/// {totalControlled}.
uint256 public totalDepositedInValidators;
/// @inheritdoc IStakingInitiationRead
uint256 public numInitiatedValidators;
/// @notice The amount of ETH that is used to allocate to deposits and fill the pending unstake requests.
uint256 public unallocatedETH;
/// @notice The amount of ETH that is used deposit into validators.
uint256 public allocatedETHForDeposits;
/// @notice The minimum amount of ETH users can stake.
uint256 public minimumStakeBound;
/// @notice The minimum amount of mETH users can unstake.
uint256 public minimumUnstakeBound;
/// @notice When staking on Ethereum, validators must go through an entry queue to bring money into the system, and
/// an exit queue to bring it back out. The entry queue increases in size as more people want to stake. While the
/// money is in the entry queue, it is not earning any rewards. When a validator is active, or in the exit queue, it
/// is earning rewards. Once a validator enters the entry queue, the only way that the money can be retrieved is by
/// waiting for it to become active and then to exit it again. As of July 2023, the entry queue is approximately 40
/// days and the exit queue is 0 days (with ~6 days of processing time).
///
/// In a non-optimal scenario for the protocol, a user could stake (for example) 32 ETH to receive mETH, wait
/// until a validator enters the queue, and then request to unstake to recover their 32 ETH. Now we have 32 ETH in
/// the system which affects the exchange rate, but is not earning rewards.
///
/// In this case, the 'fair' thing to do would be to make the user wait for the queue processing to finish before
/// returning their funds. Because the tokens are fungible however, we have no way of matching 'pending' stakes to a
/// particular user. This means that in order to fulfill unstake requests quickly, we must exit a different
/// validator to return the user's funds. If we exit a validator, we can return the funds after ~5 days, but the
/// original 32 ETH will not be earning for another 35 days, leading to a small but repeatable socialised loss of
/// efficiency for the protocol. As we can only exit validators in chunks of 32 ETH, this case is also exacerbated
/// by a user unstaking smaller amounts of ETH.
///
/// To compensate for the fact that these two queues differ in length, we apply an adjustment to the exchange rate
/// to reflect the difference and mitigate its effect on the protocol. This protects the protocol from the case
/// above, and also from griefing attacks following the same principle. Essentially, when you stake you are
/// receiving a value of mETH that discounts ~35 days worth of rewards in return for being able to access your
/// money without waiting the full 40 days when unstaking. As the adjustment is applied to the exchange rate, this
/// results in a small 'improvement' to the rate for all existing stakers (i.e. it is not a fee levied by the
/// protocol itself).
///
/// As the adjustment is applied to the exchange rate, the result is reflected in any user interface which shows the
/// amount of mETH received when staking, meaning there is no surprise for users when staking or unstaking.
/// @dev The value is in basis points (1/10000).
uint16 public exchangeAdjustmentRate;
/// @dev A basis point (often denoted as bp, 1bp = 0.01%) is a unit of measure used in finance to describe
/// the percentage change in a financial instrument. This is a constant value set as 10000 which represents
/// 100% in basis point terms.
uint16 internal constant _BASIS_POINTS_DENOMINATOR = 10_000;
/// @notice The maximum amount the exchange adjustment rate (10%) that can be set by the admin.
uint16 internal constant _MAX_EXCHANGE_ADJUSTMENT_RATE = _BASIS_POINTS_DENOMINATOR / 10; // 10%
/// @notice The minimum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending deposits that would result in non-activated
/// validators (since we don't do top-ups), that would need to be exited again to get the ETH back.
uint256 public minimumDepositAmount;
/// @notice The maximum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending too large deposits. While this is not a critical
/// issue as any surplus >32 ETH (at the time of writing) will automatically be withdrawn again at some point, it is
/// still undesireable as it locks up not-earning ETH for the duration of the round trip decreasing the efficiency
/// of the protocol.
uint256 public maximumDepositAmount;
/// @notice The beacon chain deposit contract.
/// @dev ETH will be sent there during validator initiation.
IDepositContract public depositContract;
/// @notice The mETH token contract.
/// @dev Tokens will be minted / burned during staking / unstaking.
IMETH public mETH;
/// @notice The oracle contract.
/// @dev Tracks ETH on the beacon chain and other accounting relevant quantities.
IOracleReadRecord public oracle;
/// @notice The pauser contract.
/// @dev Keeps the pause state across the protocol.
IPauserRead public pauser;
/// @notice The contract tracking unstake requests and related allocation and claim operations.
IUnstakeRequestsManager public unstakeRequestsManager;
/// @notice The address to receive beacon chain withdrawals (i.e. validator rewards and exits).
/// @dev Changing this variable will not have an immediate effect as all exisiting validators will still have the
/// original value set.
address public withdrawalWallet;
/// @notice The address for the returns aggregator contract to push funds.
/// @dev See also {receiveReturns}.
address public returnsAggregator;
/// @notice The staking allowlist flag which, when enabled, allows staking only for addresses in allowlist.
bool public isStakingAllowlist;
/// @inheritdoc IStakingInitiationRead
/// @dev This will be used to give off-chain services a sensible point in time to start their analysis from.
uint256 public initializationBlockNumber;
/// @notice The maximum amount of mETH that can be minted during the staking process.
/// @dev This is used as an additional safeguard to create a maximum stake amount in the protocol. As the protocol
/// scales up this value will be increased to allow for more staking.
uint256 public maximumMETHSupply;
/// @notice Configuration for contract initialization.
struct Init {
address admin;
address manager;
address allocatorService;
address initiatorService;
address returnsAggregator;
address withdrawalWallet;
IMETH mETH;
IDepositContract depositContract;
IOracleReadRecord oracle;
IPauserRead pauser;
IUnstakeRequestsManager unstakeRequestsManager;
}
constructor() {
_disableInitializers();
}
/// @notice Inititalizes the contract.
/// @dev MUST be called during the contract upgrade to set up the proxies state.
function initialize(Init memory init) external initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, init.admin);
_grantRole(STAKING_MANAGER_ROLE, init.manager);
_grantRole(ALLOCATOR_SERVICE_ROLE, init.allocatorService);
_grantRole(INITIATOR_SERVICE_ROLE, init.initiatorService);
// Intentionally does not set anyone as the TOP_UP_ROLE as it will only be granted
// in the off-chance that the top up functionality is required.
// Set up roles for the staking allowlist. Intentionally do not grant anyone the
// STAKING_ALLOWLIST_MANAGER_ROLE as it will only be granted later.
_setRoleAdmin(STAKING_ALLOWLIST_MANAGER_ROLE, STAKING_MANAGER_ROLE);
_setRoleAdmin(STAKING_ALLOWLIST_ROLE, STAKING_ALLOWLIST_MANAGER_ROLE);
mETH = init.mETH;
depositContract = init.depositContract;
oracle = init.oracle;
pauser = init.pauser;
returnsAggregator = init.returnsAggregator;
unstakeRequestsManager = init.unstakeRequestsManager;
withdrawalWallet = init.withdrawalWallet;
minimumStakeBound = 0.1 ether;
minimumUnstakeBound = 0.01 ether;
minimumDepositAmount = 32 ether;
maximumDepositAmount = 32 ether;
isStakingAllowlist = true;
initializationBlockNumber = block.number;
// Set the maximum mETH supply to some sensible amount which is expected to be changed as the
// protocol ramps up.
maximumMETHSupply = 1024 ether;
}
/// @notice Interface for users to stake their ETH with the protocol. Note: when allowlist is enabled, only users
/// with the allowlist can stake.
/// @dev Mints the corresponding amount of mETH (relative to the stake's share in the total ETH controlled by the
/// protocol) to the user.
/// @param minMETHAmount The minimum amount of mETH that the user expects to receive in return.
function stake(uint256 minMETHAmount) external payable {
if (pauser.isStakingPaused()) {
revert Paused();
}
if (isStakingAllowlist) {
_checkRole(STAKING_ALLOWLIST_ROLE);
}
if (msg.value < minimumStakeBound) {
revert MinimumStakeBoundNotSatisfied();
}
uint256 mETHMintAmount = ethToMETH(msg.value);
if (mETHMintAmount + mETH.totalSupply() > maximumMETHSupply) {
revert MaximumMETHSupplyExceeded();
}
if (mETHMintAmount < minMETHAmount) {
revert StakeBelowMinimumMETHAmount(mETHMintAmount, minMETHAmount);
}
// Increment unallocated ETH after calculating the exchange rate to ensure
// a consistent rate.
unallocatedETH += msg.value;
emit Staked(msg.sender, msg.value, mETHMintAmount);
mETH.mint(msg.sender, mETHMintAmount);
}
/// @notice Interface for users to submit a request to unstake.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The staking contract must therefore be approved to move the user's mETH on their behalf.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
/// @return The request ID.
function unstakeRequest(uint128 methAmount, uint128 minETHAmount) external returns (uint256) {
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Interface for users to submit a request to unstake with an ERC20 permit.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The permit must therefore allow the staking contract to move the user's mETH on their behalf.
/// @return The request ID.
function unstakeRequestWithPermit(
uint128 methAmount,
uint128 minETHAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
SafeERC20Upgradeable.safePermit(mETH, msg.sender, address(this), methAmount, deadline, v, r, s);
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Processes a user's request to unstake by transferring the corresponding mETH to the staking contract
/// and creating the request on the unstake requests manager.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
function _unstakeRequest(uint128 methAmount, uint128 minETHAmount) internal returns (uint256) {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
if (methAmount < minimumUnstakeBound) {
revert MinimumUnstakeBoundNotSatisfied();
}
uint128 ethAmount = uint128(mETHToETH(methAmount));
if (ethAmount < minETHAmount) {
revert UnstakeBelowMinimumETHAmount(ethAmount, minETHAmount);
}
uint256 requestID =
unstakeRequestsManager.create({requester: msg.sender, mETHLocked: methAmount, ethRequested: ethAmount});
emit UnstakeRequested({id: requestID, staker: msg.sender, ethAmount: ethAmount, mETHLocked: methAmount});
SafeERC20Upgradeable.safeTransferFrom(mETH, msg.sender, address(unstakeRequestsManager), methAmount);
return requestID;
}
/// @notice Interface for users to claim their finalized and filled unstaking requests.
/// @dev See also {UnstakeRequestsManager} for a more detailed explanation of finalization and request filling.
function claimUnstakeRequest(uint256 unstakeRequestID) external {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
emit UnstakeRequestClaimed(unstakeRequestID, msg.sender);
unstakeRequestsManager.claim(unstakeRequestID, msg.sender);
}
/// @notice Returns the status of the request whether it is finalized and how much ETH has been filled.
/// See also {UnstakeRequestsManager.requestInfo} for a more detailed explanation of finalization and request
/// filling.
/// @param unstakeRequestID The ID of the unstake request.
/// @return bool indicating if the unstake request is finalized, and the amount of ETH that has been filled.
function unstakeRequestInfo(uint256 unstakeRequestID) external view returns (bool, uint256) {
return unstakeRequestsManager.requestInfo(unstakeRequestID);
}
/// @notice Withdraws any surplus from the unstake requests manager.
/// @dev The request manager is expected to return the funds by pushing them using
/// {receiveFromUnstakeRequestsManager}.
function reclaimAllocatedETHSurplus() external onlyRole(STAKING_MANAGER_ROLE) {
// Calls the receiveFromUnstakeRequestsManager() where we perform
// the accounting.
unstakeRequestsManager.withdrawAllocatedETHSurplus();
}
/// @notice Allocates ETH from the unallocatedETH balance to the unstake requests manager to fill pending requests
/// and adds to the allocatedETHForDeposits balance that is used to initiate new validators.
function allocateETH(uint256 allocateToUnstakeRequestsManager, uint256 allocateToDeposits)
external
onlyRole(ALLOCATOR_SERVICE_ROLE)
{
if (pauser.isAllocateETHPaused()) {
revert Paused();
}
if (allocateToUnstakeRequestsManager + allocateToDeposits > unallocatedETH) {
revert NotEnoughUnallocatedETH();
}
unallocatedETH -= allocateToUnstakeRequestsManager + allocateToDeposits;
if (allocateToDeposits > 0) {
allocatedETHForDeposits += allocateToDeposits;
emit AllocatedETHToDeposits(allocateToDeposits);
}
if (allocateToUnstakeRequestsManager > 0) {
emit AllocatedETHToUnstakeRequestsManager(allocateToUnstakeRequestsManager);
unstakeRequestsManager.allocateETH{value: allocateToUnstakeRequestsManager}();
}
}
/// @notice Initiates new validators by sending ETH to the beacon chain deposit contract.
/// @dev Cannot initiate the same validator (public key) twice. Since BLS signatures cannot be feasibly verified on
/// the EVM, the caller must carefully make sure that the sent payloads (public keys + signatures) are correct,
/// otherwise the sent ETH will be lost.
function initiateValidatorsWithDeposits(ValidatorParams[] calldata validators, bytes32 expectedDepositRoot)
external
onlyRole(INITIATOR_SERVICE_ROLE)
{
if (pauser.isInitiateValidatorsPaused()) {
revert Paused();
}
if (validators.length == 0) {
return;
}
// Check that the deposit root matches the given value. This ensures that the deposit contract state
// has not changed since the transaction was submitted, which means that a rogue node operator cannot
// front-run deposit transactions.
bytes32 actualRoot = depositContract.get_deposit_root();
if (expectedDepositRoot != actualRoot) {
revert InvalidDepositRoot(actualRoot);
}
// First loop is to check that all validators are valid according to our constraints and we record the
// validators and how much we have deposited.
uint256 amountDeposited = 0;
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
if (usedValidators[validator.pubkey]) {
revert PreviouslyUsedValidator();
}
if (validator.depositAmount < minimumDepositAmount) {
revert MinimumValidatorDepositNotSatisfied();
}
if (validator.depositAmount > maximumDepositAmount) {
revert MaximumValidatorDepositExceeded();
}
_requireProtocolWithdrawalAccount(validator.withdrawalCredentials);
usedValidators[validator.pubkey] = true;
amountDeposited += validator.depositAmount;
emit ValidatorInitiated({
id: keccak256(validator.pubkey),
operatorID: validator.operatorID,
pubkey: validator.pubkey,
amountDeposited: validator.depositAmount
});
}
if (amountDeposited > allocatedETHForDeposits) {
revert NotEnoughDepositETH();
}
allocatedETHForDeposits -= amountDeposited;
totalDepositedInValidators += amountDeposited;
numInitiatedValidators += validators.length;
// Second loop is to send the deposits to the deposit contract. Keeps external calls to the deposit contract
// separate from state changes.
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
depositContract.deposit{value: validator.depositAmount}({
pubkey: validator.pubkey,
withdrawal_credentials: validator.withdrawalCredentials,
signature: validator.signature,
deposit_data_root: validator.depositDataRoot
});
}
}
/// @inheritdoc IStakingReturnsWrite
/// @dev Intended to be the called in the same transaction initiated by reclaimAllocatedETHSurplus().
/// This should only be called in emergency scenarios, e.g. if the unstake requests manager has cancelled
/// unfinalized requests and there is a surplus balance.
/// Adds the received funds to the unallocated balance.
function receiveFromUnstakeRequestsManager() external payable onlyUnstakeRequestsManager {
unallocatedETH += msg.value;
}
/// @notice Tops up the unallocated ETH balance to increase the amount of ETH in the protocol.
/// @dev Bypasses the returns aggregator fee collection to inject ETH directly into the protocol.
function topUp() external payable onlyRole(TOP_UP_ROLE) {
unallocatedETH += msg.value;
}
/// @notice Converts from mETH to ETH using the current exchange rate.
/// The exchange rate is given by the total supply of mETH and total ETH controlled by the protocol.
function ethToMETH(uint256 ethAmount) public view returns (uint256) {
// 1:1 exchange rate on the first stake.
// Using `METH.totalSupply` over `totalControlled` to check if the protocol is in its bootstrap phase since
// the latter can be manipulated, for example by transferring funds to the `ExecutionLayerReturnsReceiver`, and
// therefore be non-zero by the time the first stake is made
if (mETH.totalSupply() == 0) {
return ethAmount;
}
// deltaMETH = (1 - exchangeAdjustmentRate) * (mETHSupply / totalControlled) * ethAmount
// This rounds down to zero in the case of `(1 - exchangeAdjustmentRate) * ethAmount * mETHSupply <
// totalControlled`.
// While this scenario is theoretically possible, it can only be realised feasibly during the protocol's
// bootstrap phase and if `totalControlled` and `mETHSupply` can be changed independently of each other. Since
// the former is permissioned, and the latter is not permitted by the protocol, this cannot be exploited by an
// attacker.
return Math.mulDiv(
ethAmount,
mETH.totalSupply() * uint256(_BASIS_POINTS_DENOMINATOR - exchangeAdjustmentRate),
totalControlled() * uint256(_BASIS_POINTS_DENOMINATOR)
);
}
/// @notice Converts from ETH to mETH using the current exchange rate.
/// The exchange rate is given by the total supply of mETH and total ETH controlled by the protocol.
function mETHToETH(uint256 mETHAmount) public view returns (uint256) {
// 1:1 exchange rate on the first stake.
// Using `METH.totalSupply` over `totalControlled` to check if the protocol is in its bootstrap phase since
// the latter can be manipulated, for example by transferring funds to the `ExecutionLayerReturnsReceiver`, and
// therefore be non-zero by the time the first stake is made
if (mETH.totalSupply() == 0) {
return mETHAmount;
}
// deltaETH = (totalControlled / mETHSupply) * mETHAmount
// This rounds down to zero in the case of `mETHAmount * totalControlled < mETHSupply`.
// While this scenario is theoretically possible, it can only be realised feasibly during the protocol's
// bootstrap phase and if `totalControlled` and `mETHSupply` can be changed independently of each other. Since
// the former is permissioned, and the latter is not permitted by the protocol, this cannot be exploited by an
// attacker.
return Math.mulDiv(mETHAmount, totalControlled(), mETH.totalSupply());
}
/// @notice The total amount of ETH controlled by the protocol.
/// @dev Sums over the balances of various contracts and the beacon chain information from the oracle.
function totalControlled() public view returns (uint256) {
OracleRecord memory record = oracle.latestRecord();
uint256 total = 0;
total += unallocatedETH;
total += allocatedETHForDeposits;
/// The total ETH deposited to the beacon chain must be decreased by the deposits processed by the off-chain
/// oracle since it will be accounted for in the currentTotalValidatorBalance from that point onwards.
total += totalDepositedInValidators - record.cumulativeProcessedDepositAmount;
total += record.currentTotalValidatorBalance;
total += unstakeRequestsManager.balance();
return total;
}
/// @notice Checks if the given withdrawal credentials are a valid 0x01 prefixed withdrawal address.
/// @dev See also
/// https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/validator.md#eth1_address_withdrawal_prefix
function _requireProtocolWithdrawalAccount(bytes calldata withdrawalCredentials) internal view {
if (withdrawalCredentials.length != 32) {
revert InvalidWithdrawalCredentialsWrongLength(withdrawalCredentials.length);
}
// Check the ETH1_ADDRESS_WITHDRAWAL_PREFIX and that all other bytes are zero.
bytes12 prefixAndPadding = bytes12(withdrawalCredentials[:12]);
if (prefixAndPadding != 0x010000000000000000000000) {
revert InvalidWithdrawalCredentialsNotETH1(prefixAndPadding);
}
address addr = address(bytes20(withdrawalCredentials[12:32]));
if (addr != withdrawalWallet) {
revert InvalidWithdrawalCredentialsWrongAddress(addr);
}
}
/// @inheritdoc IStakingReturnsWrite
/// @dev Adds the received funds to the unallocated balance.
function receiveReturns() external payable onlyReturnsAggregator {
emit ReturnsReceived(msg.value);
unallocatedETH += msg.value;
}
/// @notice Ensures that the caller is the returns aggregator.
modifier onlyReturnsAggregator() {
if (msg.sender != returnsAggregator) {
revert NotReturnsAggregator();
}
_;
}
/// @notice Ensures that the caller is the unstake requests manager.
modifier onlyUnstakeRequestsManager() {
if (msg.sender != address(unstakeRequestsManager)) {
revert NotUnstakeRequestsManager();
}
_;
}
/// @notice Ensures that the given address is not the zero address.
modifier notZeroAddress(address addr) {
if (addr == address(0)) {
revert ZeroAddress();
}
_;
}
/// @notice Sets the minimum amount of ETH users can stake.
function setMinimumStakeBound(uint256 minimumStakeBound_) external onlyRole(STAKING_MANAGER_ROLE) {
minimumStakeBound = minimumStakeBound_;
emit ProtocolConfigChanged(
this.setMinimumStakeBound.selector, "setMinimumStakeBound(uint256)", abi.encode(minimumStakeBound_)
);
}
/// @notice Sets the minimum amount of mETH users can unstake.
function setMinimumUnstakeBound(uint256 minimumUnstakeBound_) external onlyRole(STAKING_MANAGER_ROLE) {
minimumUnstakeBound = minimumUnstakeBound_;
emit ProtocolConfigChanged(
this.setMinimumUnstakeBound.selector, "setMinimumUnstakeBound(uint256)", abi.encode(minimumUnstakeBound_)
);
}
/// @notice Sets the staking adjust rate.
function setExchangeAdjustmentRate(uint16 exchangeAdjustmentRate_) external onlyRole(STAKING_MANAGER_ROLE) {
if (exchangeAdjustmentRate_ > _MAX_EXCHANGE_ADJUSTMENT_RATE) {
revert InvalidConfiguration();
}
// even though this check is redundant with the one above, this function will be rarely used so we keep it as a
// reminder for future upgrades that this must never be violated.
assert(exchangeAdjustmentRate_ <= _BASIS_POINTS_DENOMINATOR);
exchangeAdjustmentRate = exchangeAdjustmentRate_;
emit ProtocolConfigChanged(
this.setExchangeAdjustmentRate.selector,
"setExchangeAdjustmentRate(uint16)",
abi.encode(exchangeAdjustmentRate_)
);
}
/// @notice Sets the minimum amount of ETH that the staking contract can send to the deposit contract to initiate
/// new validators.
function setMinimumDepositAmount(uint256 minimumDepositAmount_) external onlyRole(STAKING_MANAGER_ROLE) {
minimumDepositAmount = minimumDepositAmount_;
emit ProtocolConfigChanged(
this.setMinimumDepositAmount.selector, "setMinimumDepositAmount(uint256)", abi.encode(minimumDepositAmount_)
);
}
/// @notice Sets the maximum amount of ETH that the staking contract can send to the deposit contract to initiate
/// new validators.
function setMaximumDepositAmount(uint256 maximumDepositAmount_) external onlyRole(STAKING_MANAGER_ROLE) {
maximumDepositAmount = maximumDepositAmount_;
emit ProtocolConfigChanged(
this.setMaximumDepositAmount.selector, "setMaximumDepositAmount(uint256)", abi.encode(maximumDepositAmount_)
);
}
/// @notice Sets the maximumMETHSupply variable.
/// Note: We intentionally allow this to be set lower than the current totalSupply so that the amount can be
/// adjusted downwards by unstaking.
/// See also {maximumMETHSupply}.
function setMaximumMETHSupply(uint256 maximumMETHSupply_) external onlyRole(STAKING_MANAGER_ROLE) {
maximumMETHSupply = maximumMETHSupply_;
emit ProtocolConfigChanged(
this.setMaximumMETHSupply.selector, "setMaximumMETHSupply(uint256)", abi.encode(maximumMETHSupply_)
);
}
/// @notice Sets the address to receive beacon chain withdrawals (i.e. validator rewards and exits).
/// @dev Changing this variable will not have an immediate effect as all exisiting validators will still have the
/// original value set.
function setWithdrawalWallet(address withdrawalWallet_)
external
onlyRole(STAKING_MANAGER_ROLE)
notZeroAddress(withdrawalWallet_)
{
withdrawalWallet = withdrawalWallet_;
emit ProtocolConfigChanged(
this.setWithdrawalWallet.selector, "setWithdrawalWallet(address)", abi.encode(withdrawalWallet_)
);
}
/// @notice Sets the staking allowlist flag.
function setStakingAllowlist(bool isStakingAllowlist_) external onlyRole(STAKING_MANAGER_ROLE) {
isStakingAllowlist = isStakingAllowlist_;
emit ProtocolConfigChanged(
this.setStakingAllowlist.selector, "setStakingAllowlist(bool)", abi.encode(isStakingAllowlist_)
);
}
receive() external payable {
revert DoesNotReceiveETH();
}
fallback() external payable {
revert DoesNotReceiveETH();
}
}
IMETH.sol 16 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IERC20Upgradeable} from "openzeppelin-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20PermitUpgradeable} from "openzeppelin-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol";
interface IMETH is IERC20Upgradeable, IERC20PermitUpgradeable {
/// @notice Mint mETH to the staker.
/// @param staker The address of the staker.
/// @param amount The amount of tokens to mint.
function mint(address staker, uint256 amount) external;
/// @notice Burn mETH from the msg.sender.
/// @param amount The amount of tokens to burn.
function burn(uint256 amount) external;
}
IOracle.sol 72 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice The records stored by the oracle contract informing the protocol about consensus layer activity. It is
/// computed and reported by off-chain oracle services.
/// @dev "current" quantities refer to the state at the `updateEndBlock` block number.
/// @dev "cumulative" quantities refer to sums up to the `updateEndBlock` block number.
/// @dev "window" quantities refer to sums over the block window between the `updateStartBlock` and `updateEndBlock`.
/// @param updateStartBlock The start of the oracle record block window. This should be 1 higher than the
/// updateEndBlock of the previous oracle record.
/// @param updateEndBlock The block number up to which this oracle record was computed (inclusive).
/// @param currentNumValidatorsNotWithdrawable The number of our validators that do not have the withdrawable status.
/// @param cumulativeNumValidatorsWithdrawable The total number of our validators that have the withdrawable status.
/// These validators have either the status `withdrawal_possible` or `withdrawal_done`. Note: validators can
/// fluctuate between the two statuses due to top ups.
/// @param windowWithdrawnPrincipalAmount The amount of principal that has been withdrawn from the consensus layer in
/// the analyzed block window.
/// @param windowWithdrawnRewardAmount The amount of rewards that has been withdrawn from the consensus layer in the
/// analysed block window.
/// @param currentTotalValidatorBalance The total amount of ETH in the consensus layer (i.e. the sum of all validator
/// balances). This is one of the major quantities to compute the total value controlled by the protocol.
/// @param cumulativeProcessedDepositAmount The total amount of ETH that has been deposited into and processed by the
/// consensus layer. This is used to prevent double counting of the ETH deposited to the consensus layer.
struct OracleRecord {
uint64 updateStartBlock;
uint64 updateEndBlock;
uint64 currentNumValidatorsNotWithdrawable;
uint64 cumulativeNumValidatorsWithdrawable;
uint128 windowWithdrawnPrincipalAmount;
uint128 windowWithdrawnRewardAmount;
uint128 currentTotalValidatorBalance;
uint128 cumulativeProcessedDepositAmount;
}
interface IOracleWrite {
/// @notice Pushes a new record to the oracle.
function receiveRecord(OracleRecord calldata record) external;
}
interface IOracleReadRecord {
/// @notice Returns the latest validated record.
/// @return `OracleRecord` The latest validated record.
function latestRecord() external view returns (OracleRecord calldata);
/// @notice Returns the record at the given index.
/// @param idx The index of the record to retrieve.
/// @return `OracleRecord` The record at the given index.
function recordAt(uint256 idx) external view returns (OracleRecord calldata);
/// @notice Returns the number of records in the oracle.
/// @return `uint256` The number of records in the oracle.
function numRecords() external view returns (uint256);
}
interface IOracleReadPending {
/// @notice Returns the pending update.
/// @return `OracleRecord` The pending update.
function pendingUpdate() external view returns (OracleRecord calldata);
/// @notice Indicates whether an oracle update is pending, i.e. if it was rejected by `_sanityCheckUpdate`.
function hasPendingUpdate() external view returns (bool);
}
interface IOracleRead is IOracleReadRecord, IOracleReadPending {}
interface IOracleManager {
/// @notice Sets the new oracle updater for the contract.
/// @param newUpdater The new oracle updater.
function setOracleUpdater(address newUpdater) external;
}
interface IOracle is IOracleWrite, IOracleRead, IOracleManager {}
IPauser.sol 26 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IPauserRead {
/// @notice Flag indicating if staking is paused.
function isStakingPaused() external view returns (bool);
/// @notice Flag indicating if unstake requests are paused.
function isUnstakeRequestsAndClaimsPaused() external view returns (bool);
/// @notice Flag indicating if initiate validators is paused
function isInitiateValidatorsPaused() external view returns (bool);
/// @notice Flag indicating if submit oracle records is paused.
function isSubmitOracleRecordsPaused() external view returns (bool);
/// @notice Flag indicating if allocate ETH is paused.
function isAllocateETHPaused() external view returns (bool);
}
interface IPauserWrite {
/// @notice Pauses all actions.
function pauseAll() external;
}
interface IPauser is IPauserRead, IPauserWrite {}
IStaking.sol 23 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IStakingInitiationRead {
/// @notice The total amount of ETH sent to the beacon chain deposit contract.
function totalDepositedInValidators() external view returns (uint256);
/// @notice The number of validators initiated by the staking contract.
function numInitiatedValidators() external view returns (uint256);
/// @notice The block number at which the staking contract has been initialised.
function initializationBlockNumber() external view returns (uint256);
}
interface IStakingReturnsWrite {
/// @notice Accepts funds sent by the returns aggregator.
function receiveReturns() external payable;
/// @notice Accepts funds sent by the unstake requests manager.
function receiveFromUnstakeRequestsManager() external payable;
}
interface IStaking is IStakingInitiationRead, IStakingReturnsWrite {}
UnstakeRequestsManager.sol 403 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Initializable} from "openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlEnumerableUpgradeable} from
"openzeppelin-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import {Address} from "openzeppelin/utils/Address.sol";
import {Math} from "openzeppelin/utils/math/Math.sol";
import {SafeERC20Upgradeable} from "openzeppelin-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {ProtocolEvents} from "./interfaces/ProtocolEvents.sol";
import {IMETH} from "./interfaces/IMETH.sol";
import {IOracleReadRecord} from "./interfaces/IOracle.sol";
import {
IUnstakeRequestsManager,
IUnstakeRequestsManagerWrite,
IUnstakeRequestsManagerRead,
UnstakeRequest
} from "./interfaces/IUnstakeRequestsManager.sol";
import {IStakingReturnsWrite} from "./interfaces/IStaking.sol";
/// @notice Events emitted by the unstake requests manager.
interface UnstakeRequestsManagerEvents {
/// @notice Created emitted when an unstake request has been created.
/// @param id The id of the unstake request.
/// @param requester The address of the user who requested to unstake.
/// @param mETHLocked The amount of mETH that will be burned when the request is claimed.
/// @param ethRequested The amount of ETH that will be returned to the requester.
/// @param cumulativeETHRequested The cumulative amount of ETH requested at the time of the unstake request.
/// @param blockNumber The block number at the point at which the request was created.
event UnstakeRequestCreated(
uint256 indexed id,
address indexed requester,
uint256 mETHLocked,
uint256 ethRequested,
uint256 cumulativeETHRequested,
uint256 blockNumber
);
/// @notice Claimed emitted when an unstake request has been claimed.
/// @param id The id of the unstake request.
/// @param requester The address of the user who requested to unstake.
/// @param mETHLocked The amount of mETH that will be burned when the request is claimed.
/// @param ethRequested The amount of ETH that will be returned to the requester.
/// @param cumulativeETHRequested The cumulative amount of ETH requested at the time of the unstake request.
/// @param blockNumber The block number at the point at which the request was created.
event UnstakeRequestClaimed(
uint256 indexed id,
address indexed requester,
uint256 mETHLocked,
uint256 ethRequested,
uint256 cumulativeETHRequested,
uint256 blockNumber
);
/// @notice Cancelled emitted when an unstake request has been cancelled by an admin.
/// @param id The id of the unstake request.
/// @param requester The address of the user who requested to unstake.
/// @param mETHLocked The amount of mETH that will be burned when the request is claimed.
/// @param ethRequested The amount of ETH that will be returned to the requester.
/// @param cumulativeETHRequested The cumulative amount of ETH requested at the time of the unstake request.
/// @param blockNumber The block number at the point at which the request was created.
event UnstakeRequestCancelled(
uint256 indexed id,
address indexed requester,
uint256 mETHLocked,
uint256 ethRequested,
uint256 cumulativeETHRequested,
uint256 blockNumber
);
}
/// @title UnstakeRequestsManager
/// @notice Manages unstake requests from the staking contract.
contract UnstakeRequestsManager is
Initializable,
AccessControlEnumerableUpgradeable,
IUnstakeRequestsManager,
UnstakeRequestsManagerEvents,
ProtocolEvents
{
// Errors.
error AlreadyClaimed();
error DoesNotReceiveETH();
error NotEnoughFunds(uint256 cumulativeETHOnRequest, uint256 allocatedETHForClaims);
error NotFinalized();
error NotRequester();
error NotStakingContract();
/// @notice Role allowed to set properties of the contract.
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
/// @notice Role that is allowed to cancel unfinalized requests if the protocol is in emergency state.
bytes32 public constant REQUEST_CANCELLER_ROLE = keccak256("REQUEST_CANCELLER_ROLE");
/// @notice The staking contract to which the unstake requests manager accepts claims and new unstake requests from.
IStakingReturnsWrite public stakingContract;
/// @notice The oracle contract that the finalization criteria relies on.
IOracleReadRecord public oracle;
/// @notice The total amount of ether sent by the staking contract.
/// @dev This value can be decreased when reclaiming surplus allocatedETHs.
uint256 public allocatedETHForClaims;
/// @notice The total amount of ether claimed by requesters.
uint256 public totalClaimed;
/// @notice A request's block number on creation plus numberOfBlocksToFinalize determines
/// if the request is finalized.
uint256 public numberOfBlocksToFinalize;
/// @notice The mETH token contract.
/// @dev Tokens will be minted / burned during staking / unstaking.
IMETH public mETH;
/// @dev Cache the latest cumulative ETH requested value instead of checking latest element in the array.
/// This prevents encountering an invalid value if someone claims the request which resets it.
uint128 public latestCumulativeETHRequested;
/// @dev The internal queue of unstake requests.
UnstakeRequest[] internal _unstakeRequests;
/// @notice Configuration for contract initialization.
struct Init {
address admin;
address manager;
address requestCanceller;
IMETH mETH;
IStakingReturnsWrite stakingContract;
IOracleReadRecord oracle;
uint256 numberOfBlocksToFinalize;
}
constructor() {
_disableInitializers();
}
/// @notice Inititalizes the contract.
/// @dev MUST be called during the contract upgrade to set up the proxies state.
function initialize(Init memory init) external initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, init.admin);
numberOfBlocksToFinalize = init.numberOfBlocksToFinalize;
stakingContract = init.stakingContract;
oracle = init.oracle;
mETH = init.mETH;
_grantRole(MANAGER_ROLE, init.manager);
_grantRole(REQUEST_CANCELLER_ROLE, init.requestCanceller);
}
/// @inheritdoc IUnstakeRequestsManagerWrite
/// @dev Increases the cumulative ETH requested counter and pushes a new unstake request to the array. This function
/// can only be called by the staking contract.
function create(address requester, uint128 mETHLocked, uint128 ethRequested)
external
onlyStakingContract
returns (uint256)
{
uint128 currentCumulativeETHRequested = latestCumulativeETHRequested + ethRequested;
uint256 requestID = _unstakeRequests.length;
UnstakeRequest memory unstakeRequest = UnstakeRequest({
id: uint128(requestID),
requester: requester,
mETHLocked: mETHLocked,
ethRequested: ethRequested,
cumulativeETHRequested: currentCumulativeETHRequested,
blockNumber: uint64(block.number)
});
_unstakeRequests.push(unstakeRequest);
latestCumulativeETHRequested = currentCumulativeETHRequested;
emit UnstakeRequestCreated(
requestID, requester, mETHLocked, ethRequested, currentCumulativeETHRequested, block.number
);
return requestID;
}
/// @inheritdoc IUnstakeRequestsManagerWrite
/// @dev Verifies the requester's identity, finality of the request, and availability of funds before transferring
/// the requested ETH. The unstake request is then removed from the array.
function claim(uint256 requestID, address requester) external onlyStakingContract {
UnstakeRequest memory request = _unstakeRequests[requestID];
if (request.requester == address(0)) {
revert AlreadyClaimed();
}
if (requester != request.requester) {
revert NotRequester();
}
if (!_isFinalized(request)) {
revert NotFinalized();
}
if (request.cumulativeETHRequested > allocatedETHForClaims) {
revert NotEnoughFunds(request.cumulativeETHRequested, allocatedETHForClaims);
}
delete _unstakeRequests[requestID];
totalClaimed += request.ethRequested;
emit UnstakeRequestClaimed({
id: requestID,
requester: requester,
mETHLocked: request.mETHLocked,
ethRequested: request.ethRequested,
cumulativeETHRequested: request.cumulativeETHRequested,
blockNumber: request.blockNumber
});
// Claiming the request burns the locked mETH tokens from this contract.
// Note that it is intentional that burning happens here rather than at unstake time.
// Please see the docs folder for more information.
mETH.burn(request.mETHLocked);
Address.sendValue(payable(requester), request.ethRequested);
}
/// @inheritdoc IUnstakeRequestsManagerWrite
/// @dev Iteratively checks the finality of the latest requests and cancels the unfinalized ones until reaching a
/// finalized request or the max loop bound. Adjusts the state of the latest cumulative ETH accordingly.
function cancelUnfinalizedRequests(uint256 maxCancel) external onlyRole(REQUEST_CANCELLER_ROLE) returns (bool) {
uint256 length = _unstakeRequests.length;
if (length == 0) {
return false;
}
if (length < maxCancel) {
maxCancel = length;
}
// Cache all cancelled requests to perform the refunds after processing all local effects to strictly follow the
// checks-effects-interaction pattern.
UnstakeRequest[] memory requests = new UnstakeRequest[](maxCancel);
// Find the number of requests that have not been finalized.
uint256 numCancelled = 0;
uint128 amountETHCancelled = 0;
while (numCancelled < maxCancel) {
UnstakeRequest memory request = _unstakeRequests[_unstakeRequests.length - 1];
if (_isFinalized(request)) {
break;
}
_unstakeRequests.pop();
requests[numCancelled] = request;
++numCancelled;
amountETHCancelled += request.ethRequested;
emit UnstakeRequestCancelled(
request.id,
request.requester,
request.mETHLocked,
request.ethRequested,
request.cumulativeETHRequested,
request.blockNumber
);
}
// Reset the latest cumulative ETH state
if (amountETHCancelled > 0) {
latestCumulativeETHRequested -= amountETHCancelled;
}
// check whether there are more unfinalized requests to cancel.
bool hasMore;
uint256 remainingRequestsLength = _unstakeRequests.length;
if (remainingRequestsLength == 0) {
hasMore = false;
} else {
UnstakeRequest memory latestRemainingRequest = _unstakeRequests[remainingRequestsLength - 1];
hasMore = !_isFinalized(latestRemainingRequest);
}
// Return the locked mETH of all cancelled requests.
for (uint256 i = 0; i < numCancelled; i++) {
SafeERC20Upgradeable.safeTransfer(mETH, requests[i].requester, requests[i].mETHLocked);
}
return hasMore;
}
/// @inheritdoc IUnstakeRequestsManagerWrite
/// @dev Handles incoming ether from the staking contract, increasing the allocatedETHForClaims counter by the value
/// of the incoming allocatedETH.
function allocateETH() external payable onlyStakingContract {
allocatedETHForClaims += msg.value;
}
/// @inheritdoc IUnstakeRequestsManagerWrite
/// @dev Helps during the emergency scenario where we cancel unstake requests and we want to move ether back into
/// the staking contract.
function withdrawAllocatedETHSurplus() external onlyStakingContract {
uint256 toSend = allocatedETHSurplus();
if (toSend == 0) {
return;
}
allocatedETHForClaims -= toSend;
stakingContract.receiveFromUnstakeRequestsManager{value: toSend}();
}
/// @notice Returns the ID of the next unstake requests to be created.
function nextRequestId() external view returns (uint256) {
return _unstakeRequests.length;
}
/// @inheritdoc IUnstakeRequestsManagerRead
function requestByID(uint256 requestID) external view returns (UnstakeRequest memory) {
return _unstakeRequests[requestID];
}
/// @inheritdoc IUnstakeRequestsManagerRead
function requestInfo(uint256 requestID) external view returns (bool, uint256) {
UnstakeRequest memory request = _unstakeRequests[requestID];
bool isFinalized = _isFinalized(request);
uint256 claimableAmount = 0;
// The cumulative ETH requested also includes the ETH requested and must be subtracted from the cumulative total
// to find partially filled amounts.
uint256 allocatedEthRequired = request.cumulativeETHRequested - request.ethRequested;
if (allocatedEthRequired < allocatedETHForClaims) {
// The allocatedETHForClaims increases over time whereas the request's cumulative ETH requested stays the
// same. This means the difference between the two will also increase over time. Given we only want to
// return the partially filled amount up to the full ETH requested, we take the minimum of the two.
claimableAmount = Math.min(allocatedETHForClaims - allocatedEthRequired, request.ethRequested);
}
return (isFinalized, claimableAmount);
}
/// @inheritdoc IUnstakeRequestsManagerRead
/// @dev Compares the latest the allocatedETHForClaims value and the cumulative ETH requested value to determine if
/// there's a surplus.
function allocatedETHSurplus() public view returns (uint256) {
if (allocatedETHForClaims > latestCumulativeETHRequested) {
return allocatedETHForClaims - latestCumulativeETHRequested;
}
return 0;
}
/// @inheritdoc IUnstakeRequestsManagerRead
/// @dev Compares the latest cumulative ETH requested value and the allocatedETHForClaims value to determine if
/// there's a deficit.
function allocatedETHDeficit() external view returns (uint256) {
if (latestCumulativeETHRequested > allocatedETHForClaims) {
return latestCumulativeETHRequested - allocatedETHForClaims;
}
return 0;
}
/// @inheritdoc IUnstakeRequestsManagerRead
/// @dev The difference between allocatedETHForClaims and totalClaimed represents the amount of ether waiting to be
/// claimed.
function balance() external view returns (uint256) {
if (allocatedETHForClaims > totalClaimed) {
return allocatedETHForClaims - totalClaimed;
}
return 0;
}
/// @notice Updates the number of blocks required to finalize requests.
/// @param numberOfBlocksToFinalize_ The number of blocks required to finalize requests.
function setNumberOfBlocksToFinalize(uint256 numberOfBlocksToFinalize_) external onlyRole(MANAGER_ROLE) {
numberOfBlocksToFinalize = numberOfBlocksToFinalize_;
emit ProtocolConfigChanged(
this.setNumberOfBlocksToFinalize.selector,
"setNumberOfBlocksToFinalize(uint256)",
abi.encode(numberOfBlocksToFinalize_)
);
}
/// @notice Used by the claim function to check whether the request can be claimed (i.e. is finalized).
/// @dev Finalization relies on the latest record of the oracle. This way, users can only claim their unstake
/// requests in a period where the protocol has a valid record. We also use numberOfBlocksToFinalize as another
/// safety buffer that can be set depending on the needs of the protocol.
/// See also {claim}
/// @return A boolean indicating whether the unstake request is finalized or not.
function _isFinalized(UnstakeRequest memory request) internal view returns (bool) {
return (request.blockNumber + numberOfBlocksToFinalize) <= oracle.latestRecord().updateEndBlock;
}
/// @dev Validates that the caller is the staking contract.
modifier onlyStakingContract() {
if (msg.sender != address(stakingContract)) {
revert NotStakingContract();
}
_;
}
// Fallbacks.
receive() external payable {
revert DoesNotReceiveETH();
}
fallback() external payable {
revert DoesNotReceiveETH();
}
}
ProtocolEvents.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ProtocolEvents {
/// @notice Emitted when a protocol configuration has been updated.
/// @param setterSelector The selector of the function that updated the configuration.
/// @param setterSignature The signature of the function that updated the configuration.
/// @param value The abi-encoded data passed to the function that updated the configuration. Since this event will
/// only be emitted by setters, this data corresponds to the updated values in the protocol configuration.
event ProtocolConfigChanged(bytes4 indexed setterSelector, string setterSignature, bytes value);
}
IDepositContract.sol 53 lines
// ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━
// ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓
// ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛
// ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃��━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━
// ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓
// ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//
// From: https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.20;
// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index);
/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);
/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}
// Based on official specification in https://eips.ethereum.org/EIPS/eip-165
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceId` and
/// `interfaceId` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
IUnstakeRequestsManager.sol 74 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Staking} from "../Staking.sol";
/// @notice An unstake request is stored in the UnstakeRequestsManager and records the information required to
/// fulfill an unstake request claim.
/// @param id The unique ID of the unstake request.
/// @param requester The address of the user that requested the unstake.
/// @param mETHLocked The amount of mETH that was locked when the unstake request was created. The amount of mETH
/// will be burned once the request has been claimed.
/// @param ethRequested The amount of ETH that was requested when the unstake request was created.
/// @param cumulativeETHRequested The cumulative amount of ETH that had been requested in this request and all unstake
/// requests before this one.
/// @param blockNumber The block number at which the unstake request was created.
struct UnstakeRequest {
uint64 blockNumber;
address requester;
uint128 id;
uint128 mETHLocked;
uint128 ethRequested;
uint128 cumulativeETHRequested;
}
interface IUnstakeRequestsManagerWrite {
/// @notice Creates a new unstake request and adds it to the unstake requests array.
/// @param requester The address of the entity making the unstake request.
/// @param mETHLocked The amount of mETH tokens currently locked in the contract.
/// @param ethRequested The amount of ETH being requested for unstake.
/// @return The ID of the new unstake request.
function create(address requester, uint128 mETHLocked, uint128 ethRequested) external returns (uint256);
/// @notice Allows the requester to claim their unstake request after it has been finalized.
/// @param requestID The ID of the unstake request to claim.
/// @param requester The address of the entity claiming the unstake request.
function claim(uint256 requestID, address requester) external;
/// @notice Cancels a batch of the latest unfinalized unstake requests.
/// @param maxCancel The maximum number of requests to cancel.
/// @return A boolean indicating if there are more unstake requests to cancel.
function cancelUnfinalizedRequests(uint256 maxCancel) external returns (bool);
/// @notice Allocate ether into the contract.
function allocateETH() external payable;
/// @notice Withdraws surplus ETH from the allocatedETHForClaims.
function withdrawAllocatedETHSurplus() external;
}
interface IUnstakeRequestsManagerRead {
/// @notice Retrieves a specific unstake request based on its ID.
/// @param requestID The ID of the unstake request to fetch.
/// @return The UnstakeRequest struct corresponding to the given ID.
function requestByID(uint256 requestID) external view returns (UnstakeRequest memory);
/// @notice Returns the status of the request whether it is finalized and how much ETH that has been filled.
/// @param requestID The ID of the unstake request.
/// @return bool indicating if the request is finalized, and the amount of ETH that has been filled.
function requestInfo(uint256 requestID) external view returns (bool, uint256);
/// @notice Calculates the amount of ether allocated in the contract exceeding the total required to pay unclaimed.
/// @return The amount of surplus allocatedETH.
function allocatedETHSurplus() external view returns (uint256);
/// @notice Calculates the amount of ether that is needed to fulfill the unstake requests.
/// @return The amount of allocatedETH deficit.
function allocatedETHDeficit() external view returns (uint256);
/// @notice Calculates the amount of ether that has been allocated but not yet claimed.
/// @return The total amount of ether that is waiting to be claimed.
function balance() external view returns (uint256);
}
interface IUnstakeRequestsManager is IUnstakeRequestsManagerRead, IUnstakeRequestsManagerWrite {}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
ContextUpgradeable.sol 37 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
StringsUpgradeable.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
MathUpgradeable.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
ERC20Upgradeable.sol 377 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
IERC20Upgradeable.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
AccessControlUpgradeable.sol 261 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
IAccessControlUpgradeable.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
SignedMathUpgradeable.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
ERC165Upgradeable.sol 42 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
SafeERC20Upgradeable.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
* 0 before setting it to a non-zero value.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
IERC165Upgradeable.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
EnumerableSetUpgradeable.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
AccessControlEnumerableUpgradeable.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
IAccessControlEnumerableUpgradeable.sol 31 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
IERC20PermitUpgradeable.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
IERC20MetadataUpgradeable.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
Read Contract
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
MANAGER_ROLE 0xec87621c → bytes32
REQUEST_CANCELLER_ROLE 0xfe3af1c1 → bytes32
allocatedETHDeficit 0x106b263c → uint256
allocatedETHForClaims 0x1453444d → uint256
allocatedETHSurplus 0xc02d4c8e → uint256
balance 0xb69ef8a8 → uint256
getRoleAdmin 0x248a9ca3 → bytes32
getRoleMember 0x9010d07c → address
getRoleMemberCount 0xca15c873 → uint256
hasRole 0x91d14854 → bool
latestCumulativeETHRequested 0x278c5acd → uint128
mETH 0x29e84867 → address
nextRequestId 0x6a84a985 → uint256
numberOfBlocksToFinalize 0xae5cf272 → uint256
oracle 0x7dc0d1d0 → address
requestByID 0x9a6e6ed1 → tuple
requestInfo 0x4f588bf1 → bool, uint256
stakingContract 0xee99205c → address
supportsInterface 0x01ffc9a7 → bool
totalClaimed 0xd54ad2a1 → uint256
Write Contract 10 functions
These functions modify contract state and require a wallet transaction to execute.
allocateETH 0x4d13bfa6
No parameters
cancelUnfinalizedRequests 0x1e846464
uint256 maxCancel
returns: bool
claim 0xddd5e1b2
uint256 requestID
address requester
create 0xb5475cf6
address requester
uint128 mETHLocked
uint128 ethRequested
returns: uint256
grantRole 0x2f2ff15d
bytes32 role
address account
initialize 0x588570a5
tuple init
renounceRole 0x36568abe
bytes32 role
address account
revokeRole 0xd547741f
bytes32 role
address account
setNumberOfBlocksToFinalize 0x28ad3aac
uint256 numberOfBlocksToFinalize_
withdrawAllocatedETHSurplus 0xb2d42b46
No parameters
Recent Transactions
No transactions found for this address