Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0x5D2eA33449A60a70E8FCdc5251FDd86a030fAD91
Balance 0 ETH
Nonce 1
Code Size 10532 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

10532 bytes
0x608060405234801561000f575f80fd5b5060043610610213575f3560e01c806370a082311161011f578063a4733df9116100a9578063deb906e711610079578063deb906e7146105d7578063e30c39781461065a578063e399f29f1461066d578063eecbc2ae146106a0578063f2fde38b146106da575f80fd5b8063a4733df914610582578063a694fc3a14610595578063b48e9519146105a8578063ddaa26ad146105b0575f80fd5b8063874d6d81116100ef578063874d6d81146104cb57806388ba63ba146104d35780638da5cb5b1461053157806395255285146105445780639e94080e1461056f575f80fd5b806370a082311461049557806379ba5097146104a8578063802c4a0f146104b05780638381e182146104b8575f80fd5b80632ee40908116101a057806349d1818d1161017057806349d1818d146103df5780634b3b140a146103f2578063510e995d1461040557806351ed6a301461042f5780636f68fa1e1461046e575f80fd5b80632ee40908146103615780633011ef5714610374578063313ce567146103935780633ea01b34146103cc575f80fd5b8063143d7084116101e6578063143d7084146102c457806318160ddd146102f6578063231aed7c146102ff57806328f1ae5114610312578063293405011461033a575f80fd5b806301681a6214610217578063026800d01461022c57806307f93a381461025257806312cf9dad14610265575b5f80fd5b61022a61022536600461256f565b6106ed565b005b61023f61023a366004612588565b6107f7565b6040519081526020015b60405180910390f35b61023f6102603660046125c1565b6108ae565b6102786102733660046125c1565b610a7c565b6040805183516001600160701b039081168252602080860151909116908201528382015161ffff169181019190915260609283015160ff1692810192909252608082015260a001610249565b6102e66102d236600461256f565b600c6020525f908152604090205460ff1681565b6040519015158152602001610249565b61023f60085481565b61022a61030d3660046125f9565b610b4a565b60045461032790600160701b900461ffff1681565b60405161ffff9091168152602001610249565b61023f7f000000000000000000000000000000000000000000000000000000000000000481565b61023f61036f3660046125c1565b610bd2565b61023f61038236600461262e565b60076020525f908152604090205481565b6103ba7f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff9091168152602001610249565b61023f6103da36600461256f565b610c87565b61022a6103ed366004612645565b610c94565b61023f61040036600461262e565b610d27565b61023f6104133660046125c1565b600360209081525f928352604080842090915290825290205481565b6104567f00000000000000000000000022222222aea0076fca927a3f44dc0b4fdf9479d681565b6040516001600160a01b039091168152602001610249565b6103ba7f000000000000000000000000000000000000000000000000000000000000001081565b61023f6104a336600461256f565b610df7565b61022a610e7e565b61023f610ef1565b61023f6104c6366004612672565b610f02565b61023f610f0e565b6105116104e13660046125c1565b600260209081525f92835260408084209091529082529020546001600160801b0380821691600160801b90041682565b604080516001600160801b03938416815292909116602083015201610249565b600954610456906001600160a01b031681565b600454610557906001600160701b031681565b6040516001600160701b039091168152602001610249565b61027861057d36600461256f565b610f39565b61023f6105903660046125c1565b610ff6565b61023f6105a336600461262e565b6112dd565b61023f6112e8565b61023f7f0000000000000000000000000000000000000000000000000000000069441b2781565b6106236105e536600461256f565b5f602081905290815260409020546001600160701b0380821691600160701b810490911690600160e01b810461ffff1690600160f01b900460ff1684565b604080516001600160701b03958616815294909316602085015261ffff9091169183019190915260ff166060820152608001610249565b600a54610456906001600160a01b031681565b61051161067b36600461262e565b60066020525f90815260409020546001600160801b0380821691600160801b90041682565b6106cd6106ae36600461269c565b600b60209081525f928352604080842090915290825290205460ff1681565b60405161024991906126d8565b61022a6106e836600461256f565b611303565b6009546001600160a01b031633146107205760405162461bcd60e51b8152600401610717906126fe565b60405180910390fd5b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa158015610764573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107889190612723565b90507f00000000000000000000000022222222aea0076fca927a3f44dc0b4fdf9479d66001600160a01b0316826001600160a01b0316036107d3576008546107d0908261274e565b90505b80156107f3576009546107f3906001600160a01b0384811691168361134f565b5050565b5f336001600160a01b0385161461089b576001600160a01b0384165f908152600b6020908152604080832033845290915290205460ff166003816003811115610842576108426126c4565b148061085f5750600281600381111561085d5761085d6126c4565b145b6108995760405162461bcd60e51b815260206004820152600b60248201526a10a832b936b4b9b9b4b7b760a91b6044820152606401610717565b505b6108a68484846113b7565b949350505050565b5f6108b7610f0e565b8211156108c557505f610a76565b6001600160a01b0383165f9081526020818152604091829020825160808101845290546001600160701b038082168352600160701b82041692820192909252600160e01b820461ffff16928101839052600160f01b90910460ff16606082015290838110610958575050506001600160a01b0382165f908152600160209081526040808320848452909152902054610a76565b6001600160a01b0385165f90815260016020908152604080832061ffff8516845282528220549084015190916001600160701b03909116908190036109a257509250610a76915050565b60608401515b868461ffff161015610a6e576001909301926109c48284612761565b925060018160ff16901b90507f000000000000000000000000000000000000000000000000000000000000001060ff167f0000000000000000000000000000000000000000000000000000000000000010821660ff1603610a69576001600160a01b0388165f90815260026020908152604080832061ffff88168452909152902054610a6090600160801b90046001600160801b03168361274e565b91508115610a6e575b6109a8565b509093505050505b92915050565b604080516080810182525f80825260208201819052918101829052606081018290529080610aa8610f0e565b9050808410610ab5578093505b610abf8585611abc565b6001600160a01b039096165f9081526020818152604091829020835181549285015193850151606086015160ff16600160f01b0260ff60f01b1961ffff909216600160e01b029190911662ffffff60e01b196001600160701b03968716600160701b026001600160e01b03199096169690931695909517939093171692909217179055959350505050565b6009546001600160a01b03163314610b745760405162461bcd60e51b8152600401610717906126fe565b6001600160a01b0382165f818152600c6020908152604091829020805460ff191685151590811790915591519182527f386b58ddc1936aa97344d1a8d49c247eec866f85d00106bd7d0b516079819c9f910160405180910390a25050565b5f336001600160a01b03841614610c76576001600160a01b0383165f908152600b6020908152604080832033845290915290205460ff166003816003811115610c1d57610c1d6126c4565b1480610c3a57506001816003811115610c3857610c386126c4565b145b610c745760405162461bcd60e51b815260206004820152600b60248201526a10a832b936b4b9b9b4b7b760a91b6044820152606401610717565b505b610c808383611e49565b9392505050565b5f610a7682610260610f0e565b335f908152600b602090815260408083206001600160a01b03861684529091529020805482919060ff19166001836003811115610cd357610cd36126c4565b0217905550816001600160a01b0316336001600160a01b03167fcdadcd1f1a942380f3ff00a651eee9878ae0c68bc11b4abb3b2c96d82477161883604051610d1b91906126d8565b60405180910390a35050565b5f80610d31610f0e565b905080831115610d4357505f92915050565b60045461ffff600160701b820416906001600160701b0316818511610d77575050505f918252506005602052604090205490565b61ffff82165f9081526005602052604081205490829003610d9b5795945050505050565b858361ffff161015610dee57600190920191610db78282612761565b61ffff84165f90815260066020526040902054909150610de790600160801b90046001600160801b03168361274e565b9150610d9b565b95945050505050565b6001600160a01b0381165f90815260208181526040808320815160808101835290546001600160701b03808216808452600160701b8304909116948301859052600160e01b820461ffff1693830193909352600160f01b900460ff16606082015291610e639190612774565b610e6e90600261279b565b6001600160701b03169392505050565b600a546001600160a01b03163314610ea85760405162461bcd60e51b8152600401610717906126fe565b60098054336001600160a01b03199182168117909255600a805490911690556040517f04dba622d284ed0014ee4b9a6a68386be1a4c08a4913ae272de89199cc686163905f90a2565b5f610efd610400610f0e565b905090565b5f610c803384846113b7565b62093a807f0000000000000000000000000000000000000000000000000000000069441b2742030490565b604080516080810182525f808252602082018190529181018290526060810182905290610f6d83610f68610f0e565b611abc565b6001600160a01b039094165f9081526020818152604091829020835181549285015193850151606086015160ff16600160f01b0260ff60f01b1961ffff909216600160e01b029190911662ffffff60e01b196001600160701b03968716600160701b026001600160e01b0319909616969093169590951793909317169290921717905593915050565b335f908152600c602052604081205460ff166110465760405162461bcd60e51b815260206004820152600f60248201526e10b0b8383937bb32b229ba30b5b2b960891b6044820152606401610717565b60018211801561105c57506001600160701b0382105b6110785760405162461bcd60e51b8152600401610717906127c6565b5f611081610f0e565b90505f8061108f8684611abc565b915091505f61109d8461220d565b835160011988169791925060019190911c90819085906110be908390612774565b6001600160701b03169052506110f57f00000000000000000000000000000000000000000000000000000000000000046001612761565b6110ff90826127ee565b6001600160a01b0389165f908152600360209081526040808320898452909152812080549293508992909190611136908490612761565b90915550505f8581526007602052604081208054899290611158908490612761565b9091555061116890508184612761565b6001600160a01b0389165f90815260016020908152604080832089845290915290205561119e816001600160701b038416612761565b5f868152600560209081526040808320939093556001600160a01b038b16825281815282822087518154928901519489015160608a015160ff16600160f01b0260ff60f01b1961ffff909216600160e01b029190911662ffffff60e01b196001600160701b03978816600160701b026001600160e01b031990961697909316969096179390931716939093171790915560088054899290611240908490612761565b9091555061127b90506001600160a01b037f00000000000000000000000022222222aea0076fca927a3f44dc0b4fdf9479d61633308a612311565b846001600160a01b0389167f9cfd25589d1eb8ad71e342a86a8524e83522e3936c0803048c08f6d9ad974f40896112b28588612761565b604080519283526020830191909152810185905260600160405180910390a350949695505050505050565b5f610a763383611e49565b5f806112f2610f0e565b90506112fd8161220d565b91505090565b6009546001600160a01b0316331461132d5760405162461bcd60e51b8152600401610717906126fe565b600a80546001600160a01b0319166001600160a01b0392909216919091179055565b6040516001600160a01b0383166024820152604481018290526113b290849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261234f565b505050565b5f6001831180156113ce57506001600160701b0383105b6113ea5760405162461bcd60e51b8152600401610717906127c6565b5f6113f3610f0e565b90505f6114008683611abc565b50905061140c8261220d565b5060608101516ffffffffffffffffffffffffffffffffe8616955f9060011c60ff83161561180e575f5b7f0000000000000000000000000000000000000000000000000000000000000004816001600160801b031610156118035760016001600160801b0382161b60ff808216868316909116036117fa575f6001600160801b0383166114b97f00000000000000000000000000000000000000000000000000000000000000048a612761565b6114c3919061274e565b6001600160a01b038d165f9081526002602090815260408083208484529091529020549091506001600160801b03600160801b909104811690851681101561163b57611510846001612805565b61151a9082612825565b6115249087612805565b6001600160a01b038e165f908152600260209081526040808320868452825280832080546001600160801b03908116909155600690925290912080549298508392909160109161157d918591600160801b900416612848565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550836001600160801b03165f03611626576001600160a01b038d165f908152600260209081526040808320858452825280832080546001600160801b03191690556006909152812080548392906116019084906001600160801b0316612848565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b958218956116348186612848565b94506117f7565b611646846001612805565b6116509086612825565b61165a9087612805565b6001600160a01b038e165f9081526002602090815260408083208684529091529020805491975086916010906116a1908490600160801b90046001600160801b0316612848565b92506101000a8154816001600160801b0302191690836001600160801b031602179055508460065f8481526020019081526020015f205f0160108282829054906101000a90046001600160801b03166116fa9190612848565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550836001600160801b03165f036117ce576001600160a01b038d165f908152600260209081526040808320858452909152812080548792906117699084906001600160801b0316612848565b82546101009290920a6001600160801b038181021990931691831602179091555f848152600660205260408120805489945090926117a991859116612848565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b806001600160801b0316856001600160801b0316036117ec57958218955b5f9450505050611803565b50505b50600101611436565b5060ff831660608501525b5f6118266001600160801b03831660018b901c61274e565b90506001600160801b038216156118a0576118627f00000000000000000000000000000000000000000000000000000000000000046001612761565b61186c9083612825565b6118769084612805565b925081855f018181516118899190612868565b6001600160701b03169052505f60208601526118bf565b80856020018181516118b29190612868565b6001600160701b03169052505b6001600160a01b038a165f9081526020818152604080832088518154938a0151928a015160608b015160ff16600160f01b0260ff60f01b1961ffff909216600160e01b029190911662ffffff60e01b196001600160701b03958616600160701b026001600160e01b03199097169386169390931795909517919091169390931792909217909155600480548493919261195a91859116612868565b92506101000a8154816001600160701b0302191690836001600160701b03160217905550826001600160801b031660055f8881526020019081526020015f205f8282546119a7919061274e565b90915550506001600160a01b038a165f9081526001602090815260408083208984529091528120546119e3906001600160801b0386169061274e565b6001600160a01b038c165f9081526001602090815260408083208b84529091528120829055600880549293508c92909190611a1f90849061274e565b9091555050604080518b8152602081018390526001600160801b03861681830152905188916001600160a01b038e16917fdcfd2b4017d03f7e541021db793b2f9b31e4acdee005f789e52853c390e3e9629181900360600190a3611aad6001600160a01b037f00000000000000000000000022222222aea0076fca927a3f44dc0b4fdf9479d6168a8c61134f565b50979998505050505050505050565b60408051608080820183525f808352602080840182905283850182905260609384018290526001600160a01b038716825281815284822085519384018652546001600160701b038082168552600160701b82041691840191909152600160e01b810461ffff16948301859052600160f01b900460ff169282019290925291808403611b6a576001600160a01b0385165f90815260016020908152604080832093835292905220549050611e42565b808411611bcb5760405162461bcd60e51b815260206004820152602960248201527f737065636966696564207765656b206973206f6c646572207468616e206c61736044820152683a103ab83230ba329760b91b6064820152608401610717565b602083015183516001600160701b0391821691165f829003611c8c578015611c49576001600160a01b0387165f90815260016020908152604080832086845290915290205493505b85831015611c49576001600160a01b0387165f908152600160208181526040808420969092018084529590529020849055611c13565b5050506001600160a01b0384165f9081526020819052604090819020805461ffff60e01b1916600160e01b61ffff87169081029190911790915590830152611e42565b6001600160a01b0387165f908152600160209081526040808320868452909152812054606087015190955090611ceb88611ce67f000000000000000000000000000000000000000000000000000000000000000488612761565b612422565b90505b80851015611dc957600190940193611d068487612761565b6001600160a01b038a165f9081526001602081815260408084208a85529091529091208290559096506101fe92901b918216917f000000000000000000000000000000000000000000000000000000000000001060ff811660fe919092161603611dc4576001600160a01b0389165f908152600260209081526040808320888452909152902054600160801b90046001600160801b0316611da7818661274e565b9450611db38185612761565b9350845f03611dc25750611dc9565b505b611cee565b5b87851015611e00576001600160a01b0389165f908152600160208181526040808420989092018084529790529020869055611dca565b6040518060800160405280846001600160701b03168152602001856001600160701b031681526020018961ffff1681526020018360ff16815250965050505050505b9250929050565b5f600182118015611e6057506001600160701b0382105b611e7c5760405162461bcd60e51b8152600401610717906127c6565b5f611e85610f0e565b90505f80611e938684611abc565b915091505f611ea18461220d565b90505f600187901c9050600181901b96508084602001818151611ec49190612774565b6001600160701b039081169091526004805484935090915f91611ee991859116612774565b92506101000a8154816001600160701b0302191690836001600160701b031602179055505f7f000000000000000000000000000000000000000000000000000000000000000486611f3a9190612761565b6001600160a01b038a165f9081526002602090815260408083208484528252918290208251808401909352546001600160801b038082168452600160801b9091041690820181815292935090918491611f94908390612805565b6001600160801b0316905250805183908290611fb1908390612805565b6001600160801b039081169091526001600160a01b038c165f9081526002602090815260408083208784528252808320865196830151968516600160801b97861688021790556006825291829020825180840190935254808416835294909404909116928101838152909285925061202a908390612805565b6001600160801b0316905250805183908290612047908390612805565b6001600160801b039081169091525f8481526006602090815260409091208451918501518316600160801b0291909216179055506120858386612761565b6001600160a01b038b165f9081526001602090815260408083208b84529091529020556120bb836001600160701b038616612761565b5f8881526005602090815260408083209390935560608901805160011760ff90811682526001600160a01b038f1684528383528484208b518154948d0151968d015193516001600160701b039182166001600160e01b031990961695909517600160701b91909716029590951762ffffff60e01b1916600160e01b61ffff9093169290920260ff60f01b191691909117600160f01b929091169190910217909155600880548b929061216e908490612761565b909155506121a990506001600160a01b037f00000000000000000000000022222222aea0076fca927a3f44dc0b4fdf9479d61633308c612311565b866001600160a01b038b167f9cfd25589d1eb8ad71e342a86a8524e83522e3936c0803048c08f6d9ad974f408b6121e0878a612761565b604080519283526020830191909152810187905260600160405180910390a3509698975050505050505050565b60045461ffff600160701b8204165f8181526005602052604081205490926001600160701b0316908084036122665750506004805461ffff909416600160701b0261ffff60701b1990941693909317909255505f919050565b848361ffff160361227957949350505050565b848361ffff1610156122d9576001909201916122958282612761565b61ffff84165f90815260056020908152604080832084905560069091529020549091506122d290600160801b90046001600160801b03168361274e565b9150612279565b6004805461ffff909616600160701b026001600160801b03199096166001600160701b03909316929092179490941790555090919050565b6040516001600160a01b03808516602483015283166044820152606481018290526123499085906323b872dd60e01b9060840161137b565b50505050565b5f6123a3826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166124379092919063ffffffff16565b905080515f14806123c35750808060200190518101906123c39190612888565b6113b25760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610717565b5f8183106124305781610c80565b5090919050565b60606108a684845f85855f80866001600160a01b0316858760405161245c91906128a3565b5f6040518083038185875af1925050503d805f8114612496576040519150601f19603f3d011682016040523d82523d5f602084013e61249b565b606091505b50915091506124ac878383876124b7565b979650505050505050565b606083156125255782515f0361251e576001600160a01b0385163b61251e5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610717565b50816108a6565b6108a6838381511561253a5781518083602001fd5b8060405162461bcd60e51b815260040161071791906128b9565b80356001600160a01b038116811461256a575f80fd5b919050565b5f6020828403121561257f575f80fd5b610c8082612554565b5f805f6060848603121561259a575f80fd5b6125a384612554565b9250602084013591506125b860408501612554565b90509250925092565b5f80604083850312156125d2575f80fd5b6125db83612554565b946020939093013593505050565b80151581146125f6575f80fd5b50565b5f806040838503121561260a575f80fd5b61261383612554565b91506020830135612623816125e9565b809150509250929050565b5f6020828403121561263e575f80fd5b5035919050565b5f8060408385031215612656575f80fd5b61265f83612554565b9150602083013560048110612623575f80fd5b5f8060408385031215612683575f80fd5b8235915061269360208401612554565b90509250929050565b5f80604083850312156126ad575f80fd5b6126b683612554565b915061269360208401612554565b634e487b7160e01b5f52602160045260245ffd5b60208101600483106126f857634e487b7160e01b5f52602160045260245ffd5b91905290565b6020808252600b908201526a08585d5d1a1bdc9a5e995960aa1b604082015260600190565b5f60208284031215612733575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610a7657610a7661273a565b80820180821115610a7657610a7661273a565b6001600160701b038181168382160190808211156127945761279461273a565b5092915050565b6001600160701b038181168382160280821691908281146127be576127be61273a565b505092915050565b6020808252600e908201526d1a5b9d985b1a5908185b5bdd5b9d60921b604082015260600190565b8082028115828204841417610a7657610a7661273a565b6001600160801b038181168382160190808211156127945761279461273a565b6001600160801b038181168382160280821691908281146127be576127be61273a565b6001600160801b038281168282160390808211156127945761279461273a565b6001600160701b038281168282160390808211156127945761279461273a565b5f60208284031215612898575f80fd5b8151610c80816125e9565b5f82518060208501845e5f920191825250919050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f8301168401019150509291505056fea2646970667358221220180194f9f524c1d6029655d5882e89835eaed26badc389608a2d0be58cb0f1cb64736f6c63430008190033

Verified Source Code Partial Match

Compiler: v0.8.25+commit.b61c2a91 EVM: cancun Optimization: Yes (200 runs)
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
     * ====
     *
     * [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://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

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

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return 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);
        }
    }
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Permit.sol";
import "./Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}
IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @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);
}
YearnBoostedStaker.sol 590 lines
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.22;

import {IERC20, SafeERC20} from "./SafeERC20.sol";
import {IERC20Metadata} from "./IERC20Metadata.sol";

contract YearnBoostedStaker {
    using SafeERC20 for IERC20;

    uint public immutable MAX_STAKE_GROWTH_WEEKS;
    uint8 public immutable MAX_WEEK_BIT;
    uint public immutable START_TIME;
    IERC20 public immutable stakeToken;

    // Account weight tracking state vars.
    mapping(address account => AccountData data) public accountData;
    mapping(address account => mapping(uint week => uint weight)) private accountWeeklyWeights;
    mapping(address account => mapping(uint week => ToRealize weight)) public accountWeeklyToRealize;
    mapping(address account => mapping(uint week => uint amount)) public accountWeeklyMaxStake;

    // Global weight tracking stats vars.
    uint112 public globalGrowthRate;
    uint16 public globalLastUpdateWeek;
    mapping(uint week => uint weight) private globalWeeklyWeights;
    mapping(uint week => ToRealize weight) public globalWeeklyToRealize;
    mapping(uint week => uint amount) public globalWeeklyMaxStake;

    // Generic token interface.
    uint public totalSupply;
    uint8 public immutable decimals;

    // Permissioned roles
    address public owner;
    address public pendingOwner;
    mapping(address account => mapping(address caller => ApprovalStatus approvalStatus)) public approvedCaller;
    mapping(address staker => bool approved) public approvedWeightedStaker;

    struct ToRealize {
        uint128 weightPersistent;
        uint128 weight;
    }

    struct AccountData {
        uint112 realizedStake;  // Amount of stake that has fully realized weight.
        uint112 pendingStake;   // Amount of stake that has not yet fully realized weight.
        uint16 lastUpdateWeek;  // Week of last sync.

        // One byte member to represent weeks in which an account has pending weight changes.
        // A bit is set to true when the account has a non-zero token balance to be realized in
        // the corresponding week. We use this as a "map", allowing us to reduce gas consumption
        // by avoiding unnecessary lookups on weeks which an account has zero pending stake.
        //
        // Example: 01000001
        // The left-most bit represents the final week of pendingStake.
        // Therefore, we can see that account has stake updates to process only in weeks 7 and 1.
        uint8 updateWeeksBitmap;
    }

    enum ApprovalStatus {
        None,               // 0. Default value, indicating no approval
        StakeOnly,          // 1. Approved for stake only
        UnstakeOnly,        // 2. Approved for unstake only
        StakeAndUnstake     // 3. Approved for both stake and unstake
    }

    event Staked(address indexed account, uint indexed week, uint amount, uint newUserWeight, uint weightAdded);
    event Unstaked(address indexed account, uint indexed week, uint amount, uint newUserWeight, uint weightRemoved);
    event ApprovedCallerSet(address indexed account, address indexed caller, ApprovalStatus status);
    event OwnershipTransferred(address indexed newOwner);
    event WeightedStakerSet(address indexed staker, bool approved);

    /**
        @param _token The token to be staked.
        @param _max_stake_growth_weeks The number of weeks a stake will grow for.
                            Not including desposit week.
        @param _start_time  allows deployer to optionally set a custom start time.
                            useful if needed to line up with week count in another system.
                            Passing a value of 0 will start at block.timestamp.
        @param _owner       Owner is able to grant access to stake with max boost.
    */
    constructor(address _token, uint _max_stake_growth_weeks, uint _start_time, address _owner) {
        owner = _owner;
        emit OwnershipTransferred(_owner);
        stakeToken = IERC20(_token);
        decimals = IERC20Metadata(_token).decimals();
        require(
            _max_stake_growth_weeks > 0 &&
            _max_stake_growth_weeks <= 7,
            "Invalid weeks"
        );
        MAX_STAKE_GROWTH_WEEKS = _max_stake_growth_weeks;
        MAX_WEEK_BIT = uint8(1 << MAX_STAKE_GROWTH_WEEKS);
        if (_start_time == 0){
            START_TIME = block.timestamp;
        }
        else {
            require(_start_time <= block.timestamp, "!Past");
            START_TIME = _start_time;
        }
    }

    /**
        @notice Stake tokens into the staking contract.
        @param _amount Amount of tokens to stake.
    */
    function stake(uint _amount) external returns (uint) {
        return _stake(msg.sender, _amount);
    }

    function stakeFor(address _account, uint _amount) external returns (uint) {
        if (msg.sender != _account) {
            ApprovalStatus status = approvedCaller[_account][msg.sender];
            require(
                status == ApprovalStatus.StakeAndUnstake ||
                status == ApprovalStatus.StakeOnly,
                "!Permission"
            );
        }
        
        return _stake(_account, _amount);
    }

    function _stake(address _account, uint _amount) internal returns (uint) {
        require(_amount > 1 && _amount < type(uint112).max, "invalid amount");

        // Before going further, let's sync our account and global weights
        uint systemWeek = getWeek();
        (AccountData memory acctData, uint accountWeight) = _checkpointAccount(_account, systemWeek);
        uint112 globalWeight = uint112(_checkpointGlobal(systemWeek));

        uint weight = _amount >> 1;
        _amount = weight << 1; // This helps prevent balance/weight discrepencies.
        
        acctData.pendingStake += uint112(weight);
        globalGrowthRate += uint112(weight);

        uint realizeWeek = systemWeek + MAX_STAKE_GROWTH_WEEKS;
        ToRealize memory toRealize = accountWeeklyToRealize[_account][realizeWeek];
        toRealize.weight += uint128(weight);
        toRealize.weightPersistent += uint128(weight);
        accountWeeklyToRealize[_account][realizeWeek] = toRealize;

        toRealize = globalWeeklyToRealize[realizeWeek];
        toRealize.weight += uint128(weight);
        toRealize.weightPersistent += uint128(weight);
        globalWeeklyToRealize[realizeWeek] = toRealize;
        
        accountWeeklyWeights[_account][systemWeek] = accountWeight + weight;
        globalWeeklyWeights[systemWeek] = globalWeight + weight;

        acctData.updateWeeksBitmap |= 1; // Use bitwise or to ensure bit is flipped at least weighted position.
        accountData[_account] = acctData;
        totalSupply += _amount;
        
        stakeToken.safeTransferFrom(msg.sender, address(this), uint(_amount));
        emit Staked(_account, systemWeek, _amount, accountWeight + weight, weight);
        
        return _amount;
    }

    /**
        @notice Allows an option for an approved helper to stake to any account at any weight week.
        @dev A stake using this method only effects weight in current and future weeks. It does not backfill prior weeks.
        @param _amount Amount to stake
        @return amount of tokens staked
    */
    function stakeAsMaxWeighted(address _account, uint _amount) external returns (uint) {
        require(
            approvedWeightedStaker[msg.sender],
            "!approvedStaker"
        );
        require(_amount > 1 && _amount < type(uint112).max, "invalid amount");

        // Before going further, let's sync our account and global weights
        uint systemWeek = getWeek();
        (AccountData memory acctData, uint accountWeight) = _checkpointAccount(_account, systemWeek);
        uint112 globalWeight = uint112(_checkpointGlobal(systemWeek));

        uint weight = _amount >> 1;
        _amount = weight << 1;
        acctData.realizedStake += uint112(weight);
        weight = weight * (MAX_STAKE_GROWTH_WEEKS + 1);

        // Note: The usage of `stakeAsMaxWeighted` breaks an ability to reliably derive account + global
        // amount deposited at any week using `weeklyToRealize` variables.
        // To make up for this, we introduce the following two variables that are meant to recover that same
        // ability for any on-chain integrators. They may combine this new data with `weeklyToRealize`.
        accountWeeklyMaxStake[_account][systemWeek] += _amount;
        globalWeeklyMaxStake[systemWeek] += _amount;

        accountWeeklyWeights[_account][systemWeek] = accountWeight + weight;
        globalWeeklyWeights[systemWeek] = globalWeight + weight;

        

        accountData[_account] = acctData;
        totalSupply += _amount;

        stakeToken.safeTransferFrom(msg.sender, address(this), uint(_amount));
        emit Staked(_account, systemWeek, _amount, accountWeight + weight, weight);

        return _amount;
    }

    /**
        @notice Unstake tokens from the contract.
        @dev During partial unstake, this will always remove from the least-weighted first.
    */
    function unstake(uint _amount, address _receiver) external returns (uint) {
        return _unstake(msg.sender, _amount, _receiver);
    }

    /**
        @notice Unstake tokens from the contract on behalf of another user.
        @dev During partial unstake, this will always remove from the least-weighted first.
    */
    function unstakeFor(address _account, uint _amount, address _receiver) external returns (uint) {
        if (msg.sender != _account) {
            ApprovalStatus status = approvedCaller[_account][msg.sender];
            require(
                status == ApprovalStatus.StakeAndUnstake ||
                status == ApprovalStatus.UnstakeOnly,
                "!Permission"
            );
        }
        return _unstake(_account, _amount, _receiver);
    }

    function _unstake(address _account, uint _amount, address _receiver) internal returns (uint) {
        require(_amount > 1 && _amount < type(uint112).max, "invalid amount");
        uint systemWeek = getWeek();

        // Before going further, let's sync our account and global weights
        (AccountData memory acctData, ) = _checkpointAccount(_account, systemWeek);
        _checkpointGlobal(systemWeek);

        // Here we do work to pull from most recent (least weighted) stake first
        uint8 bitmap = acctData.updateWeeksBitmap;
        uint128 weightToRemove;

        uint128 amountNeeded = uint128(_amount >> 1);
        _amount = amountNeeded << 1; // This helps prevent balance/weight discrepencies.

        if (bitmap > 0) {
            for (uint128 weekIndex; weekIndex < MAX_STAKE_GROWTH_WEEKS;) {
                // Move right to left, checking each bit if there's an update for corresponding week.
                uint8 mask = uint8(1 << weekIndex);
                if (bitmap & mask == mask) {
                    uint weekToCheck = systemWeek + MAX_STAKE_GROWTH_WEEKS - weekIndex;
                    uint128 pending = accountWeeklyToRealize[_account][weekToCheck].weight;
                    if (amountNeeded > pending){
                        weightToRemove += pending * (weekIndex + 1);
                        accountWeeklyToRealize[_account][weekToCheck].weight = 0;
                        globalWeeklyToRealize[weekToCheck].weight -= pending;
                        if (weekIndex == 0) { // Current system week
                            accountWeeklyToRealize[_account][weekToCheck].weightPersistent = 0;
                            globalWeeklyToRealize[weekToCheck].weightPersistent -= pending;
                        }
                        bitmap = bitmap ^ mask;
                        amountNeeded -= pending;
                    }
                    else { 
                        // handle the case where we have more pending than needed
                        weightToRemove += amountNeeded * (weekIndex + 1);
                        accountWeeklyToRealize[_account][weekToCheck].weight -= amountNeeded;
                        globalWeeklyToRealize[weekToCheck].weight -= amountNeeded;
                        if (weekIndex == 0) { // Current system week
                            accountWeeklyToRealize[_account][weekToCheck].weightPersistent -= amountNeeded;
                            globalWeeklyToRealize[weekToCheck].weightPersistent -= amountNeeded;
                        }
                        if (amountNeeded == pending) bitmap = bitmap ^ mask;
                        amountNeeded = 0;
                        break;
                    }
                }
                unchecked{weekIndex++;}
            }
            acctData.updateWeeksBitmap = bitmap;
        }
        
        uint pendingRemoved = (_amount >> 1) - amountNeeded;
        if (amountNeeded > 0) {
            weightToRemove += amountNeeded * uint128(1 + MAX_STAKE_GROWTH_WEEKS);
            acctData.realizedStake -= uint112(amountNeeded);
            acctData.pendingStake = 0;
        }
        else{
            acctData.pendingStake -= uint112(pendingRemoved);
        }
        
        accountData[_account] = acctData;

        globalGrowthRate -= uint112(pendingRemoved);
        globalWeeklyWeights[systemWeek] -= weightToRemove;
        uint newAccountWeight = accountWeeklyWeights[_account][systemWeek] - weightToRemove;
        accountWeeklyWeights[_account][systemWeek] = newAccountWeight;
        
        totalSupply -= _amount;

        emit Unstaked(_account, systemWeek, _amount, newAccountWeight, weightToRemove);
        
        stakeToken.safeTransfer(_receiver, _amount);
        
        return _amount;
    }
    
    /**
        @notice Get the current realized weight for an account
        @param _account Account to checkpoint.
        @return acctData Most recent account data written to storage.
        @return weight Most current account weight.
        @dev Prefer to use this function over it's view counterpart for
             contract -> contract interactions.
    */
    function checkpointAccount(address _account) external returns (AccountData memory acctData, uint weight) {
        (acctData, weight) = _checkpointAccount(_account, getWeek());
        accountData[_account] = acctData;
    }

    /**
        @notice Checkpoint an account using a specified week limit.
        @dev    To use in the event that significant number of weeks have passed since last 
                heckpoint and single call becomes too expensive.
        @param _account Account to checkpoint.
        @param _week Week which we want to checkpoint to.
        @return acctData Most recent account data written to storage.
        @return weight Account weight for provided week.
    */
    function checkpointAccountWithLimit(address _account, uint _week) external returns (AccountData memory acctData, uint weight) {
        uint systemWeek = getWeek();
        if (_week >= systemWeek) _week = systemWeek;
        (acctData, weight) = _checkpointAccount(_account, _week);
        accountData[_account] = acctData;
    }

    function _checkpointAccount(address _account, uint _systemWeek) internal returns (AccountData memory acctData, uint weight){
        acctData = accountData[_account];
        uint lastUpdateWeek = acctData.lastUpdateWeek;

        if (_systemWeek == lastUpdateWeek) {
            return (acctData, accountWeeklyWeights[_account][lastUpdateWeek]);
        }

        require(_systemWeek > lastUpdateWeek, "specified week is older than last update.");

        uint pending = uint(acctData.pendingStake);
        uint realized = acctData.realizedStake;

        if (pending == 0) {
            if (realized != 0) {
                weight = accountWeeklyWeights[_account][lastUpdateWeek];
                while (lastUpdateWeek < _systemWeek) {
                    unchecked{lastUpdateWeek++;}
                    // Fill in any missing weeks
                    accountWeeklyWeights[_account][lastUpdateWeek] = weight;
                }
            }
            accountData[_account].lastUpdateWeek = uint16(_systemWeek);
            acctData.lastUpdateWeek = uint16(_systemWeek);
            return (acctData, weight);
        }

        weight = accountWeeklyWeights[_account][lastUpdateWeek];
        uint8 bitmap = acctData.updateWeeksBitmap;
        uint targetSyncWeek = min(_systemWeek, lastUpdateWeek + MAX_STAKE_GROWTH_WEEKS);

        // Populate data for missed weeks
        while (lastUpdateWeek < targetSyncWeek) {
            unchecked{ lastUpdateWeek++; }
            weight += pending; // Increment weights by weekly growth factor.
            accountWeeklyWeights[_account][lastUpdateWeek] = weight;

            // Shift left on bitmap as we pass over each week.
            bitmap = bitmap << 1;
            if (bitmap & MAX_WEEK_BIT == MAX_WEEK_BIT){ // If left-most bit is true, we have something to realize; push pending to realized.
                // Do any updates needed to realize an amount for an account.
                uint toRealize = accountWeeklyToRealize[_account][lastUpdateWeek].weight;
                pending -= toRealize;
                realized += toRealize;
                if (pending == 0) break; // All pending has been realized. No need to continue.
            }
        }

        // Fill in any missed weeks.
        while (lastUpdateWeek < _systemWeek){
            unchecked{lastUpdateWeek++;}
            accountWeeklyWeights[_account][lastUpdateWeek] = weight;
        }   

        // Write new account data to storage.
        acctData = AccountData({
            updateWeeksBitmap: bitmap,
            pendingStake: uint112(pending),
            realizedStake: uint112(realized),
            lastUpdateWeek: uint16(_systemWeek)
        });
    }

    /**
        @notice View function to get the current weight for an account
    */
    function getAccountWeight(address account) external view returns (uint) {
        return getAccountWeightAt(account, getWeek());
    }

    /**
        @notice Get the weight for an account in a given week
    */
    function getAccountWeightAt(address _account, uint _week) public view returns (uint) {
        if (_week > getWeek()) return 0;
        
        AccountData memory acctData = accountData[_account];
        
        uint16 lastUpdateWeek = acctData.lastUpdateWeek;

        if (lastUpdateWeek >= _week) return accountWeeklyWeights[_account][_week]; 

        uint weight = accountWeeklyWeights[_account][lastUpdateWeek];

        uint pending = uint(acctData.pendingStake);
        if (pending == 0) return weight;

        uint8 bitmap = acctData.updateWeeksBitmap;

        while (lastUpdateWeek < _week) { // Populate data for missed weeks
            unchecked{lastUpdateWeek++;}
            weight += pending; // Increment weight by 1 week

            // Our bitmap is used to determine if week has any amount to realize.
            bitmap = bitmap << 1;
            if (bitmap & MAX_WEEK_BIT == MAX_WEEK_BIT){ // If left-most bit is true, we have something to realize; push pending to realized.
                pending -= accountWeeklyToRealize[_account][lastUpdateWeek].weight;
                if (pending == 0) break; // All pending has now been realized, let's exit.
            }            
        }
        
        return weight;
    }

    /**
        @notice Get the current total system weight
        @dev Also updates local storage values for total weights. Using
             this function over it's `view` counterpart is preferred for
             contract -> contract interactions.
    */
    function checkpointGlobal() external returns (uint) {
        uint systemWeek = getWeek();
        return _checkpointGlobal(systemWeek);
    }

    /**
        @notice Get the current total system weight
        @dev Also updates local storage values for total weights. Using
             this function over it's `view` counterpart is preferred for
             contract -> contract interactions.
    */
    function _checkpointGlobal(uint systemWeek) internal returns (uint) {
        // These two share a storage slot.
        uint16 lastUpdateWeek = globalLastUpdateWeek;
        uint rate = globalGrowthRate;

        uint weight = globalWeeklyWeights[lastUpdateWeek];

        if (weight == 0) {
            globalLastUpdateWeek = uint16(systemWeek);
            return 0;
        }

        if (lastUpdateWeek == systemWeek){
            return weight;
        }

        while (lastUpdateWeek < systemWeek) {
            unchecked{lastUpdateWeek++;}
            weight += rate;
            globalWeeklyWeights[lastUpdateWeek] = weight;
            rate -= globalWeeklyToRealize[lastUpdateWeek].weight;
        }

        globalGrowthRate = uint112(rate);
        globalLastUpdateWeek = uint16(systemWeek);

        return weight;
    }

    /**
        @notice Get the system weight for current week.
    */
    function getGlobalWeight() external view returns (uint) {
        return getGlobalWeightAt(getWeek());
    }

    /**
        @notice Get the system weight for a specified week in the past.
        @dev querying a week in the future will always return 0.
        @param week the week number to query global weight for.
    */
    function getGlobalWeightAt(uint week) public view returns (uint) {
        uint systemWeek = getWeek();
        if (week > systemWeek) return 0;

        // Read these together since they are packed in the same slot.
        uint16 lastUpdateWeek = globalLastUpdateWeek;
        uint rate = globalGrowthRate;

        if (week <= lastUpdateWeek) return globalWeeklyWeights[week];

        uint weight = globalWeeklyWeights[lastUpdateWeek];
        if (rate == 0) {
            return weight;
        }

        while (lastUpdateWeek < week) {
            unchecked {lastUpdateWeek++;}
            weight += rate;
            rate -= globalWeeklyToRealize[lastUpdateWeek].weight;
        }

        return weight;
    }

    /**
        @notice Returns the balance of underlying staked tokens for an account
        @param _account Account to query balance.
        @return balance of account.
    */
    function balanceOf(address _account) external view returns (uint) {
        AccountData memory acctData = accountData[_account];
        return 2 * (acctData.pendingStake + acctData.realizedStake);
    }

    /**
        @notice Allow another address to stake or unstake on behalf of. Useful for zaps and other functionality.
        @param _caller Address of the caller to approve or unapprove.
        @param _status Enum representing various approval status states.
    */
    function setApprovedCaller(address _caller, ApprovalStatus _status) external {
        approvedCaller[msg.sender][_caller] = _status;
        emit ApprovedCallerSet(msg.sender, _caller, _status);
    }

    /**
        @notice Allow owner to specify an account which has ability to stakeAsWeighted.
        @param _staker Address of account with staker permissions.
        @param _approved Approve or unapprove the staker.
    */
    function setWeightedStaker(address _staker, bool _approved) external {
        require(msg.sender == owner, "!authorized");
        approvedWeightedStaker[_staker] = _approved;
        emit WeightedStakerSet(_staker, _approved);
    }

    /**
        @notice Set a pending owner which can later be accepted.
        @param _pendingOwner Address of the new owner.
    */
    function transferOwnership(address _pendingOwner) external {
        require(msg.sender == owner, "!authorized");
        pendingOwner = _pendingOwner;
    }

    /**
        @notice Allow pending owner to accept ownership
    */
    function acceptOwnership() external {
        require(msg.sender == pendingOwner, "!authorized");
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipTransferred(msg.sender);
    }

    function sweep(address _token) external {
        require(msg.sender == owner, "!authorized");
        uint amount = IERC20(_token).balanceOf(address(this));
        if (_token == address(stakeToken)) {
            amount = amount - totalSupply;
        }
        if (amount > 0) IERC20(_token).safeTransfer(owner, amount);
    }

    function getWeek() public view returns (uint week) {
        unchecked{
            return (block.timestamp - START_TIME) / 1 weeks;
        }
    }

    function min(uint a, uint b) internal pure returns (uint) {
        return a < b ? a : b;
    }
}

Read Contract

MAX_STAKE_GROWTH_WEEKS 0x29340501 → uint256
MAX_WEEK_BIT 0x6f68fa1e → uint8
START_TIME 0xddaa26ad → uint256
accountData 0xdeb906e7 → uint112, uint112, uint16, uint8
accountWeeklyMaxStake 0x510e995d → uint256
accountWeeklyToRealize 0x88ba63ba → uint128, uint128
approvedCaller 0xeecbc2ae → uint8
approvedWeightedStaker 0x143d7084 → bool
balanceOf 0x70a08231 → uint256
decimals 0x313ce567 → uint8
getAccountWeight 0x3ea01b34 → uint256
getAccountWeightAt 0x07f93a38 → uint256
getGlobalWeight 0x802c4a0f → uint256
getGlobalWeightAt 0x4b3b140a → uint256
getWeek 0x874d6d81 → uint256
globalGrowthRate 0x95255285 → uint112
globalLastUpdateWeek 0x28f1ae51 → uint16
globalWeeklyMaxStake 0x3011ef57 → uint256
globalWeeklyToRealize 0xe399f29f → uint128, uint128
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
stakeToken 0x51ed6a30 → address
totalSupply 0x18160ddd → uint256

Write Contract 13 functions

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

acceptOwnership 0x79ba5097
No parameters
checkpointAccount 0x9e94080e
address _account
returns: tuple, uint256
checkpointAccountWithLimit 0x12cf9dad
address _account
uint256 _week
returns: tuple, uint256
checkpointGlobal 0xb48e9519
No parameters
returns: uint256
setApprovedCaller 0x49d1818d
address _caller
uint8 _status
setWeightedStaker 0x231aed7c
address _staker
bool _approved
stake 0xa694fc3a
uint256 _amount
returns: uint256
stakeAsMaxWeighted 0xa4733df9
address _account
uint256 _amount
returns: uint256
stakeFor 0x2ee40908
address _account
uint256 _amount
returns: uint256
sweep 0x01681a62
address _token
transferOwnership 0xf2fde38b
address _pendingOwner
unstake 0x8381e182
uint256 _amount
address _receiver
returns: uint256
unstakeFor 0x026800d0
address _account
uint256 _amount
address _receiver
returns: uint256

Recent Transactions

No transactions found for this address