Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x4bAF99F33c0414aAE06543Ab6Fc4a9ae405Ee2f7
Balance 0 ETH
Nonce 1
Code Size 18640 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

18640 bytes
0x6080604052600436101561001257600080fd5b60003560e01c80630717404f146103235780630951984d1461031e578063101527a51461031957806310f835111461031457806314ce783d1461030f578063172e78521461030a578063203b79b61461030557806320c32bfe146103005780632c17bbcc146102fb5780632cbdfac9146102f65780632f380b35146102f157806334308561146102ec578063441a3e70146102e75780634b5170031461027e578063527cb1d7146102475780635b35f9c9146102e25780635ca73f2b146102dd57806372f702f3146102d857806377ff1111146102d35780637a01e2bd146102565780637b0472f0146102ce5780637fbf3853146102c957806385d0b699146102c457806385dc0aaf146102bf5780638b4db06b146102ba5780638b752677146102795780638eec5d70146102b557806393dfad23146102b057806397c51bc1146102ab5780639d59c134146102a6578063a1980430146102a1578063a19e26831461029c578063a5bedf1314610297578063a7eb4f1714610292578063a8c478ba1461028d578063ac4afa3814610288578063b1427ac114610283578063b4b114ed1461027e578063be40e7a914610279578063c0f013db14610274578063c2d0a6f11461026f578063c34902631461026a578063c60b337f14610265578063c706b31614610260578063d9d2c3321461025b578063dc690ab314610256578063deb6020314610251578063eb4af0451461024c578063f1887684146102475763f4af0bd01461024257600080fd5b612629565b6110f1565b6125a5565b6124fe565b611232565b612478565b6123e7565b612378565b61215b565b61203a565b611f52565b611754565b6110b7565b611ed0565b611e20565b611b22565b611a6e565b6119ae565b611983565b6118f9565b61186f565b6117e2565b61179b565b61177d565b61172b565b611626565b6114e1565b6114ab565b611255565b611204565b6111bf565b611138565b61110f565b610dc4565b610cc1565b610c26565b610aba565b610a38565b61097a565b6108dc565b6107a4565b610667565b610590565b61050b565b61040c565b346103db5760403660031901126103db57600054610351906001600160a01b03165b6001600160a01b031690565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d6576000916103a8575b501561039657610394602435600435612a03565b005b60405163036c8cf960e11b8152600490fd5b6103c9915060203d81116103cf575b6103c18183611ceb565b8101906127fb565b38610380565b503d6103b7565b612810565b600080fd5b600435906001600160a01b03821682036103db57565b602435906001600160a01b03821682036103db57565b346103db576020806003193601126103db576104266103e0565b60065460009182915b80831061044557604051848152602090f35b0390f35b60008381526007865260408082206001600160a01b0385168352602052908190209394909390929080549061048561047c83613be1565b96519687611ceb565b818652600090815287812090888088015b8483106104ec5750505050506000925b84518410156104d4576104c86104ce916104c08688613c5b565b51519061368f565b93613261565b926104a6565b9592509250926104e390613261565b9190939261042f565b6001916005916104fb8661369c565b8152019301910190918990610496565b346103db5760203660031901126103db57610524613bbe565b60ff60055416156105405761053a600435613756565b60018055005b6040516395aad27b60e01b8152600490fd5b6024359061ffff821682036103db57565b9181601f840112156103db578235916001600160401b0383116103db57602083818601950101116103db57565b346103db5760e03660031901126103db576001600160401b0360043581811681036103db5760443561ffff811681036103db576064359283116103db576105de610394933690600401610563565b60c4359360a43593608435939160243590612d7e565b60208082019080835283518092528060408094019401926000905b83821061061e57505050505090565b84518051875280840151878501528082015187830152606080820151908801526080808201519088015260a0908101519087015260c0909501949382019360019091019061060f565b346103db576040806003193601126103db57600435906106856103f6565b600654831015610762576106c16106c6916106aa856000526007602052604060002090565b9060018060a01b0316600052602052604060002090565b613bf8565b9081516106d28161475a565b9260005b8281106106ea5783518061044187826105f4565b806106f760019284613c5b565b5161070281896142c2565b90805191602091828101518982015160609081840151926107288660808097015161368f565b96610731612f42565b9889528801528b87015285015283015260a08201526107508288613c5b565b5261075b8187613c5b565b50016106d6565b815163d531737d60e01b815260048101849052602490fd5b60609060031901126103db57600435906024356001600160a01b03811681036103db579060443590565b346103db576107b23661077a565b906006548310156108645760008381526007602090815260408083206001600160a01b038516845290915290205482101561084b5761082761082160809361081c61082e9487600052600760205260406000209060018060a01b0316600052602052604060002090565b611eb4565b5061369c565b80936142c2565b91015190810180911161084657604051908152602090f35b6131d6565b6040516358371f2b60e11b815260048101839052602490fd5b60405163d531737d60e01b815260048101849052602490fd5b60208082019080835283518092528060408094019401926000905b8382106108a757505050505090565b845180518752808401518785015280820151878301526060908101519087015260809095019493820193600190910190610898565b346103db576020806003193601126103db5760048035600654811015610963576000526008825260406000209081549161091583613be1565b936109236040519586611ceb565b83855260009182528082208186015b8584106109475760405180610441898261087d565b848360019261095585614189565b815201920193019290610932565b60405163d531737d60e01b81529182015260249150fd5b346103db5760403660031901126103db576024356001600160401b0381116103db576109aa903690600401610563565b6000546109bf906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d657600091610a00575b50156103965761039491600435612a88565b610a18915060203d81116103cf576103c18183611ceb565b386109ee565b60609060031901126103db57600435906024359060443590565b346103db57610a4636610a1e565b600054909190610a5e906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d657600091610a9c575b50156103965761039492612927565b610ab4915060203d81116103cf576103c18183611ceb565b38610a8d565b346103db5760403660031901126103db57600435610ad66103f6565b90600654811015610b0e5760009081526007602090815260408083206001600160a01b03909416835292815291902054604051908152f35b6024906040519063d531737d60e01b82526004820152fd5b919082519283825260005b848110610b52575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201610b31565b6101c0610c23926020835280516020840152602081015160408401526040810151606084015260608101516080840152608081015160a084015260a081015160c084015260c081015160e084015260e081015161010090818501528101516101209081850152810151610be761014091828601906001600160401b03169052565b810151610bfd610160918286019061ffff169052565b81015190610c12610180928386019015159052565b0151916101a0808201520190610b26565b90565b346103db5760203660031901126103db576004356060610180604051610c4b81611caf565b600080825280602083015280604083015280848301528060808301528060a08301528060c08301528060e08301528061010083015280610120830152806101408301526101608201520152600654811015610b0e57610cb5610caf61044192611c1f565b50613fab565b60405191829182610b66565b346103db576020806003193601126103db57610cdb6103e0565b60008091829060065494845b868110610d125750505061044190604051938493846040919493926060820195825260208201520152565b60008181526007835260408082206001600160a01b03861683526020529020610d3a90613bf8565b938451908115610db85781610d4e9161368f565b9460005b828110610d6a57505050610d6590613261565b610ce7565b610d748183613c5b565b51805180610d8d575b5050610d8890613261565b610d52565b99610daa610da3610d88949c610db0949c61368f565b9a876142c2565b9061368f565b989038610d7d565b945050610d6590613261565b346103db576040806003193601126103db57602435600435610de4613bbe565b6006548110156110a0576000818152600760209081528482203383529052604090205482101561108957610e2a8261081c336106aa856000526007602052604060002090565b5080548015611071578293946006610e627fea0c0780680fae66f1e26fd6c4020591e8552b124d5d7e5b74f2810b0577aa9395611c1f565b50015415158061105a575b611043575b610e84610e7e8461369c565b866142c2565b80610fa4575b5060009260018101544210610f75575b50610efa906001610eaa87611c1f565b5001838154039055610ebb86613d73565b610ec486614064565b610ecf8733886145fc565b838303610f43575b83610f06575b519283923397846040919493926060820195825260208201520152565b0390a361039460018055565b600354610f3e9085906001600160a01b03167f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e613a80565b610edd565b610f70848403337f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e613a80565b610ed7565b610f8b919350610f85839161369c565b866144f4565b91818311610f9a575b38610e9a565b9091508190610f94565b426002850155600484018181540190556008610fbf87611c1f565b5001818154019055610fd181336146aa565b1561100257815187815260208101919091523390869060008051602061487b83398151915290604090a35b38610e8a565b336000908152600c6020526040902061101c82825461368f565b905560008051602061485b83398151915282518061103b339482613d05565b0390a2610ffc565b61104c85613d73565b61105585614064565b610e72565b50600661106686611c1f565b500154421015610e6d565b8451633728b83d60e01b815260006004820152602490fd5b5060249151906358371f2b60e11b82526004820152fd5b60249083519063d531737d60e01b82526004820152fd5b346103db5760203660031901126103db576001600160a01b036110d86103e0565b16600052600c6020526020604060002054604051908152f35b346103db5760003660031901126103db576020600454604051908152f35b346103db5760003660031901126103db576002546040516001600160a01b039091168152602090f35b346103db5760403660031901126103db5760005461115e906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d6576000916111a1575b5015610396576103946024356004356129bc565b6111b9915060203d81116103cf576103c18183611ceb565b3861118d565b346103db5760003660031901126103db576040517f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e6001600160a01b03168152602090f35b346103db5761121236610a1e565b90600654831015610864579061122a91602093614817565b604051908152f35b346103db5760003660031901126103db57602060ff600554166040519015158152f35b346103db576040806003193601126103db57600480359160243591611278613bbe565b6006548410156114965760ff600554166114885760ff600961129986611c1f565b50015460501c166114735760066112af85611c1f565b50015415158061145c575b61144757821561142b5780548084106114075750508261135d61130b6113056112f960096112ea6113fe99611c1f565b5001546001600160401b031690565b6001600160401b031690565b4261368f565b611335611322846000526007602052604060002090565b3360009081526020919091526040902090565b61133d612f61565b918683526020830152428583015242606083015260006080830152613c6f565b600161136882611c1f565b500183815401905561137981613d73565b61138281614064565b7f17700ceb1658b18206f427c1578048e87504106b14ec69e9b4586d9a95174a326113c46113be336106aa856000526007602052604060002090565b546131ec565b9251928352602083018490523392604090a330337f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e613cc1565b61039460018055565b9151634df4ec0560e11b815290810192835260208301919091529081906040010390fd5b9051633728b83d60e01b81529081019182529081906020010390fd5b836024925191631fb0515960e21b8352820152fd5b50600661146885611c1f565b5001544210156112ba565b83602492519163375e1d4760e01b8352820152fd5b905163168ea94560e21b8152fd5b83602492519163d531737d60e01b8352820152fd5b346103db5760203660031901126103db57600435600654811015610b0e5760076114d6602092611c1f565b500154604051908152f35b346103db576020806003193601126103db576114fb6103e0565b6000906006549282935b80851061151757604051848152602090f35b60008581526007835260408082206001600160a01b038616835260205290819020909492939080549061155561154c83613be1565b97519788611ceb565b818752600090815285812090868089015b8483106115cc5750505050506000925b85518410156115b7576104c86115b191610daa61159d611596888b613c5b565b518b6142c2565b60806115a9898c613c5b565b51015161368f565b92611576565b9450929150936115c690613261565b93611505565b6001916005916115db8661369c565b8152019301910190918790611566565b6020908160408183019282815285518094520193019160005b828110611612575050505090565b835185529381019392810192600101611604565b346103db5760403660031901126103db576004356116426103f6565b6006548210156117125760009180835261167760209260078452604085209060018060a01b0316600052602052604060002090565b80549061168382613be1565b936116916040519586611ceb565b82855280850191865280862086925b8484106116f5578787878151916116b6836147e5565b935b8381106116cd576040518061044187826115eb565b806116e46116dd60019385613c5b565b51856142c2565b6116ee8288613c5b565b52016116b8565b6005836001926117048561369c565b8152019201930192906116a0565b60405163d531737d60e01b815260048101839052602490fd5b346103db5760003660031901126103db576000546040516001600160a01b039091168152602090f35b346103db5760003660031901126103db576003546040516001600160a01b039091168152602090f35b346103db5760003660031901126103db576020600654604051908152f35b346103db5760203660031901126103db57600435600654811015610b0e57610caf6117c591611c1f565b608081015160a09091015160408051928352602083019190915290f35b346103db5760403660031901126103db576117fb610552565b600054611810906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d657600091611851575b50156103965761039490600435612c85565b611869915060203d81116103cf576103c18183611ceb565b3861183f565b346103db5760203660031901126103db576118886103e0565b60005461189d906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d6576000916118db575b50156103965761039490612884565b6118f3915060203d81116103cf576103c18183611ceb565b386118cc565b346103db5760203660031901126103db576119126103e0565b600054611927906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d657600091611965575b50156103965761039490612d2a565b61197d915060203d81116103cf576103c18183611ceb565b38611956565b346103db5760203660031901126103db57600435600654811015610b0e5760066114d6602092611c1f565b346103db576119bc3661077a565b91600654811015610b0e5760008181526007602090815260408083206001600160a01b0386168452909152812090929054841015611a55576108216104419461081c611a25938587526007602052604087209060018060a01b0316600052602052604060002090565b60208101514210611a435750505b6040519081529081906020820190565b611a5092508051916144f4565b611a33565b6040516358371f2b60e11b815260048101859052602490fd5b346103db5760203660031901126103db576004356001600160401b038082116103db57366023830112156103db5781600401359081116103db5736602460608302840101116103db57600054604051630935e01b60e21b815233600482015290602090829060249082906001600160a01b03165afa9081156103d657600091611b04575b501561039657602461039492016134a6565b611b1c915060203d81116103cf576103c18183611ceb565b38611af2565b346103db576020806003193601126103db57611b3c6103e0565b9060009160065491835b838110611b5857604051858152602090f35b60008181526007835260408082206001600160a01b038616835260205290819020805490611b91611b8883613be1565b93519384611ceb565b818352600090815284812090858085015b848310611bea57505050505080516000915b818310611bc657505050600101611b46565b909196600190611be0611bd98a85613c5b565b51866142c2565b0197019190611bb4565b600191600591611bf98661369c565b8152019301910190918690611ba2565b634e487b7160e01b600052603260045260246000fd5b600654811015611c5a57600b906006600052027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0190600090565b611c09565b90600182811c92168015611c8f575b6020831014611c7957565b634e487b7160e01b600052602260045260246000fd5b91607f1691611c6e565b634e487b7160e01b600052604160045260246000fd5b6101a081019081106001600160401b03821117611ccb57604052565b611c99565b608081019081106001600160401b03821117611ccb57604052565b90601f801991011681019081106001600160401b03821117611ccb57604052565b9060405191826000825492611d2084611c5f565b908184526001948581169081600014611d8f5750600114611d4c575b5050611d4a92500383611ceb565b565b9093915060005260209081600020936000915b818310611d77575050611d4a93508201013880611d3c565b85548884018501529485019487945091830191611d5f565b915050611d4a94506020925060ff191682840152151560051b8201013880611d3c565b9a97936001600160401b039793610c239e9d9b979360208e61ffff9d99958152015260408d015260608c015260808b015260a08a015260c089015260e0880152610100870152166101208501521661014083015215156101608201526101a090816101808201520190610b26565b346103db5760203660031901126103db576004356006548110156103db57611e4790611c1f565b508054610441600183015460028401549260038501549460048101549260058201546006830154600784015490600885015492611e8b600a60098801549701611d0c565b976040519b8c9b8c9760ff8a60501c169a6001600160401b0361ffff8c60401c169b1699611db2565b8054821015611c5a576000526005602060002091020190600090565b346103db57611f07611ee13661077a565b9291600052600760205260406000209060018060a01b0316600052602052604060002090565b80548210156103db5760a091611f1c91611eb4565b50805490600181015490600281015460046003830154920154926040519485526020850152604084015260608301526080820152f35b346103db5760403660031901126103db57600435611f6e6103f6565b90600654811015610b0e57600091818352611fa460209160078352604085209060018060a01b0316600052602052604060002090565b805490611fb082613be1565b92611fbe6040519485611ceb565b82845280840191865280862086925b84841061201d57878787825b8151841015612012576104c861200c91610daa612000611ff98887613c5b565b51876142c2565b60806115a98988613c5b565b92611fd9565b604051908152602090f35b60058360019261202c8561369c565b815201920193019290611fcd565b346103db5760203660031901126103db57600435612056613bbe565b336000908152600c6020526040902054908115612142578061213c5750805b81116121225761208581336146aa565b156120dd57336000908152600c602052604090206120a48282546131fb565b905560405190815233907f593e1f56f7ca51a2318e287690f06c9f6930ad80990fa2e99b3bd61fb71b84ba90602090a261039460018055565b60405162461bcd60e51b815260206004820152601d60248201527f5265776172647357616c6c6574207472616e73666572206661696c65640000006044820152606490fd5b604051633728b83d60e01b81526004810191909152602490fd5b90612075565b604051633728b83d60e01b815260006004820152602490fd5b346103db576040806003193601126103db576004356024359161217c613bbe565b600654821015612345576000828152600760209081528282203383529052604090205483101561232e576121c28361081c336106aa866000526007602052604060002090565b509060066121cf84611c1f565b500154151580612317575b612300575b6121f16121eb8361369c565b846142c2565b91826122005761039460018055565b6004904260028201550161221583825461368f565b9055600861222284611c1f565b500161222f83825461368f565b905561223a83611c1f565b50541515806122df575b6122c8575b61225382336146aa565b1561228257519283526020830152339160008051602061487b83398151915290604090a35b38808080806113fe565b336000908152600c6020526040902091935060008051602061485b8339815191529250906122b184825461368f565b905551806122c0339482613d05565b0390a2612278565b6122d183613d73565b6122da83614064565b612249565b5060086122eb84611c1f565b5001546122f784611c1f565b50541115612244565b61230983613d73565b61231283614064565b6121df565b50600661232384611c1f565b5001544210156121da565b516358371f2b60e11b815260048101839052602490fd5b60249250519063d531737d60e01b82526004820152fd5b8054821015611c5a5760005260206000209060021b0190600090565b346103db5760403660031901126103db576024356004356000526008602052604060002080548210156103db576080916123b19161235c565b508054906001810154906003600282015491015491604051938452602084015260408301526060820152f35b801515036103db57565b346103db5760403660031901126103db57602435612404816123dd565b600054612419906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d65760009161245a575b5015610396576103949060043561281c565b612472915060203d81116103cf576103c18183611ceb565b38612448565b346103db576000806003193601126124fb57805461249e906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d65782916124dd575b5015610396576124da613270565b80f35b6124f5915060203d81116103cf576103c18183611ceb565b386124cc565b80fd5b346103db5761250c3661077a565b91600654811015610b0e5760008181526007602090815260408083206001600160a01b038616845290915290205483101561258c576108216104419361081c602094612575946000526007865260406000209060018060a01b0316600052602052604060002090565b015160405142919091101581529081906020820190565b6040516358371f2b60e11b815260048101849052602490fd5b346103db5760203660031901126103db576000546125cb906001600160a01b0316610345565b604051630935e01b60e21b815233600482015290602090829060249082905afa9081156103d65760009161260b575b5015610396576103946004356128ea565b612623915060203d81116103cf576103c18183611ceb565b386125fa565b346103db576000806003193601126124fb57612643613bbe565b6006908154815b81811061265b57826124da60018055565b8361266582611c1f565b5001541515806127e5575b6127ce575b61268d336106aa836000526007602052604060002090565b805490845b8281106126a45750505060010161264a565b806126b160019284611eb4565b506126c46126be8261369c565b876142c2565b90816126d3575b505001612692565b4260028201556004018054820190556126eb86611c1f565b50600880910182815401905561270087611c1f565b50015461270c87611c1f565b50541115806127bb575b6127a4575b61272581336146aa565b15612762578560008051602061487b833981519152604051806127573395878360209093929193604081019481520152565b0390a35b38806126cb565b336000908152600c6020526040902061277c82825461368f565b905560008051602061485b8339815191526040518061279c339482613d05565b0390a261275b565b6127ad86613d73565b6127b686614064565b61271b565b506127c586611c1f565b50541515612716565b6127d781613d73565b6127e081614064565b612675565b50836127f082611c1f565b500154421015612670565b908160209103126103db5751610c23816123dd565b6040513d6000823e3d90fd5b90600654821015611712576020816128797f69d3787effb5480079bbae856a98c2cd600fb5353bbbee41fc17697b3954d72493600961285a87611c1f565b5001805460ff60501b191691151560501b60ff60501b16919091179055565b6040519015158152a2565b6001600160a01b039081169081156128d857600354826bffffffffffffffffffffffff60a01b821617600355167f52164aa782bea075ec17649c0b557515997f7cb8f9e872c55f96008ce22a3a33600080a3565b60405163e6c4247b60e01b8152600490fd5b60048054908290556040805191825260208201929092527f171aabb8815c02fd00303450a77058600e3661eb75ce2e77972c0f080bc7099d9190a1565b919060065483101561086457811515806129b3575b61299b5790817fb70e98e7951565fc8ac98d8ba009c0aa78fb4590a8e5aabde9892aae690cc32992600461296f86611c1f565b50015581600561297e86611c1f565b50015560408051918252602082019290925290819081015b0390a2565b60249060405190633728b83d60e01b82526004820152fd5b5081811161293c565b90600654821015611712576020817f1a2481bdd09a5b342ca8ddd176a364b46d678feb5bb2dff76497e0d86062987c9260066129f786611c1f565b500155604051908152a2565b90600654821015611712576ec097ce7bc90715b34b9f1000000000811161299b577f7429ea012ceb4586c833fdcc60d315aa3151c246e24bf79059c9aa8053ccacb190612a4f83611c1f565b505481612a5b85611c1f565b5055612a6684613d73565b612a6f84614064565b6040805191825260208201929092529081908101612996565b9160065483101561086457612aa8600a612aa185611c1f565b5001611d0c565b90600a612ab485611c1f565b50016001600160401b038211611ccb57612ad882612ad28354611c5f565b83612beb565b6000601f8311600114612b42579161299691817f6894c91c11f97120f9ef9b8ccffa18042ecaa0e8c97f6e8f5717eada49cf07e3969594600091612b37575b508260011b906000198460031b1c19161790555b60405193849384612c60565b905085013538612b17565b601f19831690612b5783600052602060002090565b91815b818110612bbd5750916129969391857f6894c91c11f97120f9ef9b8ccffa18042ecaa0e8c97f6e8f5717eada49cf07e39897969410612ba3575b5050600182811b019055612b2b565b860135600019600385901b60f8161c191690553880612b94565b9192602060018192868b013581550194019201612b5a565b634e487b7160e01b600052600060045260246000fd5b90601f8111612bf957505050565b600091825260208220906020601f850160051c83019410612c35575b601f0160051c01915b828110612c2a57505050565b818155600101612c1e565b9092508290612c15565b908060209392818452848401376000828201840152601f01601f1916010190565b91612c77610c239492604085526040850190610b26565b926020818503910152612c3f565b906006548210156117125761ffff80821690610fa08211612d1157916040917f3aeae2cd3c279a024cac8bf01cf1c099f7574b49ce77bab9729dbc3251df869b93612d016009612cd488611c1f565b500154936009612ce389611c1f565b50019061ffff60401b82549160401b169061ffff60401b1916179055565b835192841c1682526020820152a2565b604051633728b83d60e01b815260048101839052602490fd5b6001600160a01b039081169081156128d857600254826bffffffffffffffffffffffff60a01b821617600255167f85710b1053f40e0d492d81001a623cd191d251fed32881e7bb80fc1b66a6e463600080a3565b90929394979660009660018060a01b03885416996024602060409c8d5192838092630935e01b60e21b82523360048301525afa9081156103d6578a91612f24575b5015612f13576ec097ce7bc90715b34b9f10000000008611612efb57610fa061ffff861611612ee05793612e69612e92946129969794612e75948c9d9e987f150cb369f834b70a4f343956659b1f84cd37d44352b9a76ff77ac59552ef4aa09d612e27612f80565b9889528060208a01528a890152426060890152608088015260a087015260c08601528b60e08601528b6101008601526101208501906001600160401b03169052565b61ffff16610140830152565b87610160820152612e87368787612fb5565b6101808201526130ba565b612ed6612ea06006546131ec565b96612eb5886000526008602052604060002090565b612ebd612f8d565b9142835280602084015280858401526060830152613208565b5192839283613250565b8a51633728b83d60e01b815261ffff86166004820152602490fd5b8a51633728b83d60e01b815260048101879052602490fd5b8a5163036c8cf960e11b8152600490fd5b612f3c915060203d81116103cf576103c18183611ceb565b38612dbf565b6040519060c082018281106001600160401b03821117611ccb57604052565b6040519060a082018281106001600160401b03821117611ccb57604052565b60405190611d4a82611caf565b60405190611d4a82611cd0565b6001600160401b038111611ccb57601f01601f191660200190565b929192612fc182612f9a565b91612fcf6040519384611ceb565b8294818452818301116103db578281602093846000960137010152565b91909182516001600160401b038111611ccb576130138161300d8454611c5f565b84612beb565b602080601f831160011461304f575081929394600092613044575b50508160011b916000199060031b1c1916179055565b01519050388061302e565b90601f1983169561306585600052602060002090565b926000905b8882106130a257505083600195969710613089575b505050811b019055565b015160001960f88460031b161c1916905538808061307f565b8060018596829496860151815501950193019061306a565b600654600160401b811015611ccb578060016130d99201600655611c1f565b6131d157600a61018083611d4a945184556020810151600185015560408101516002850155606081015160038501556080810151600485015560a0810151600585015560c0810151600685015560e0810151600785015561010081015160088501556131c86009850161317761315a6101208501516001600160401b031690565b825467ffffffffffffffff19166001600160401b03909116178255565b6131a661318a61014085015161ffff1690565b825461ffff60401b191660409190911b61ffff60401b16178255565b6101608301511515815460ff60501b191690151560501b60ff60501b16179055565b01519101612fec565b612bd5565b634e487b7160e01b600052601160045260246000fd5b60001981019190821161084657565b9190820391821161084657565b8054600160401b811015611ccb576132259160018201815561235c565b9190916131d15760608160039251845560208101516001850155604081015160028501550151910155565b916020610c23938181520191612c3f565b60001981146108465760010190565b60005b60065481101561333f57806132bd61328d61333a93611c1f565b506009908101805460ff60501b1916600160501b1790556132ad83611c1f565b5001805461ffff60401b19169055565b600060026132ca83611c1f565b500155600060076132da83611c1f565b500155600060046132ea83611c1f565b500155600060056132fa83611c1f565b500155807f69d3787effb5480079bbae856a98c2cd600fb5353bbbee41fc17697b3954d7246040518061333281906001602083019252565b0390a2613261565b613273565b5061335461334f60095460010190565b600955565b613366600160ff196005541617600555565b60005b6006548110156134215780807f459d2119d31d9e9f8ca61faa4372cb89990dc849eb039d39e2f85b41166baf3e6133326133b061341c956000526008602052604060002090565b6133b984611c1f565b506133f26001809201546133cd84886141cb565b936133d6612f8d565b9142835260208301526040946000868401526060830152613208565b6133fb85611c1f565b50015490514281526020810191909152600060408201529081906060820190565b613369565b507f0a3194d54d030766a03a57c8da69922243cd9f90aedddbf954a834e7d6a70cbb600080a1565b9190811015611c5a576060020190565b6060813603126103db576040519060608201908282106001600160401b03831117611ccb5760409182528035835260208101356020840152013561ffff811681036103db57604082015290565b6006928354830361366f576134c060ff1960055416600555565b60005b8454811015613643576134df6134da828686613449565b613459565b604090818101906134f2825161ffff1690565b610fa061ffff821611613626575061333284936136068594857fb70e98e7951565fc8ac98d8ba009c0aa78fb4590a8e5aabde9892aae690cc3297f3aeae2cd3c279a024cac8bf01cf1c099f7574b49ce77bab9729dbc3251df869b9661355a6136219b611c1f565b506009908101805460ff60501b19169055908051600461357986611c1f565b5001556135a460208201928351600561359188611c1f565b500155865161ffff1690612ce387611c1f565b6135ad84613d73565b6135b684614064565b837f69d3787effb5480079bbae856a98c2cd600fb5353bbbee41fc17697b3954d7248851806135ea81906000602083019252565b0390a251905186519182526020820152604090a25161ffff1690565b90516000815261ffff90911660208201529081906040820190565b6134c3565b8351633728b83d60e01b815261ffff919091166004820152602490fd5b50925050507f696f10054d6c1ede8f1a191c155c7e36b572da39bbd1faba110b029df808b1b7600080a1565b60405163512509d360e11b8152600490fd5b906001820180921161084657565b9190820180921161084657565b9060405160a081018181106001600160401b03821117611ccb57604052608060048294805484526001810154602085015260028101546040850152600381015460608501520154910152565b8181029291811591840414171561084657565b805460008083558161370c57505050565b600592828402928484040361084657815260208120918201915b8281106137335750505050565b808285925582600182015582600282015582600382015582600482015501613726565b801561212257600654336000908152600b6020526040812090928392915460095403613a5a575b336000908152600a60205260409020549180831015613a5357816137a5846137b494936131fb565b809111613a4b575b508261368f565b905b8181106138e95750336000908152600a60205260409020557fd9996fcfa05f18222e3e811aa63cfec080281e53cc6c41b8836f9ee58dd9ba6e9061299690836138b9575b80613819575b6040805194855260208501919091523393918291820190565b61382381336146aa565b61380057336000908152600c6020526040902061384182825461368f565b905560405160008051602061485b8339815191523391806138b1858260a091815260406020820152602e60408201527f5265776172647357616c6c6574207472616e73666572206661696c656420647560608201526d3934b7339036b4b3b930ba34b7b760911b60808201520190565b0390a2613800565b6138e484337f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e613a80565b6137fa565b613901336106aa836000526007602052604060002090565b80549081613914575b50506001016137b6565b600091805b61395c575050906001918261392d83611c1f565b5001908154039055613955613950336106aa846000526007602052604060002090565b6136fb565b903861390a565b6000190161396a8183611eb4565b508054908161397c575b505080613919565b81839295989961399461398e8461369c565b896142c2565b9601998601980194806139f2575b5054857fea0c0780680fae66f1e26fd6c4020591e8552b124d5d7e5b74f2810b0577aa93604051806139e93395878360409060009294936060820195825260208201520152565b0390a338613974565b600482018181540190554260028301556008613a0d88611c1f565b50018181540190558660008051602061487b83398151915260405180613a423395888360209093929193604081019481520152565b0390a3386139a2565b9050386137ad565b5050505050565b336000908152600a60209081526040808320879055600954600b9092529091205561377d565b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152611d4a91613ab982611cd0565b600080613ae29260018060a01b03169360208151910182865af1613adb613b2b565b9083613b5b565b8051908115159182613b10575b5050613af85750565b60249060405190635274afe760e01b82526004820152fd5b613b2392506020809183010191016127fb565b153880613aef565b3d15613b56573d90613b3c82612f9a565b91613b4a6040519384611ceb565b82523d6000602084013e565b606090565b90613b825750805115613b7057805190602001fd5b604051630a12f52160e11b8152600490fd5b81511580613bb5575b613b93575090565b604051639996b31560e01b81526001600160a01b039091166004820152602490fd5b50803b15613b8b565b600260015414613bcf576002600155565b604051633ee5aeb560e01b8152600490fd5b6001600160401b038111611ccb5760051b60200190565b908154613c0481613be1565b92613c126040519485611ceb565b818452600090815260208082208186015b848410613c31575050505050565b600583600192613c408561369c565b815201920193019290613c23565b805115611c5a5760200190565b8051821015611c5a5760209160051b010190565b8054600160401b811015611ccb57613c8c91600182018155611eb4565b9190916131d1576080816004925184556020810151600185015560408101516002850155606081015160038501550151910155565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152611d4a91613ab9608483611ceb565b908152604060208201819052601d908201527f5265776172647357616c6c6574207472616e73666572206661696c6564000000606082015260800190565b8015613d535764496cebb8000490565b634e487b7160e01b600052601260045260246000fd5b8115613d53570490565b613d7c90611c1f565b5060055460ff16613e7e5760068101548015159081613e94575b50613e7e5760018101548154600883015460048401549180600586015492101580613e75575b15613de1575050613dd491505b806007840155613e9f565b6002820155600342910155565b83613df45750505050613dd46000613dc9565b613dd4938115613e6d57613e2791613e21613e1c6112f960098a01546001600160401b031690565b613d43565b90613f28565b9180151580613e64575b613e5c575b5080151580613e53575b613e4b575b50613dc9565b905038613e45565b50808211613e40565b915038613e36565b50808310613e31565b505050613dc9565b50801515613dbc565b6000600282015560006007820155600342910155565b905042101538613d96565b670de0b6b3a76400008181029060001981840990828083109203918083039214613f1a5764496cebb8009082821115613f08577fd18ce2d033892ab6710afe1da5f26d00b43f019695d75c72580c14ab81b64c47940990828211900360f51b9103600b1c170290565b60405163227bc15360e01b8152600490fd5b505064496cebb80091500490565b90918282029160001984820993838086109503948086039514613f9e5784831115613f085782910981600003821680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b505090610c239250613d69565b9061405c600a613fb9612f80565b938054855260018101546020860152600281015460408601526003810154606086015260048101546080860152600581015460a0860152600681015460c0860152600781015460e0860152600881015461010086015261405660ff60098301546140396001600160401b0382166101208a01906001600160401b03169052565b604081901c61ffff1661014089015260501c161515610160870152565b01611d0c565b610180830152565b614070610caf82611c1f565b614084826000526008602052604060002090565b60055460ff168061417f575b61417a5780548015908115614154575b811561412e575b506140b157505050565b8161410f60207f459d2119d31d9e9f8ca61faa4372cb89990dc849eb039d39e2f85b41166baf3e9401916040835191019384516140ee82896141cb565b906140f7612f8d565b93428552602085015260408401526060830152613208565b5190516040805142815260208101939093528201528060608101612996565b6001915061413e614144916131ec565b8361235c565b50015460208301511415386140a7565b9050600261416a614164836131ec565b8461235c565b50015460408401511415906140a0565b505050565b5080541515614090565b90604051608081018181106001600160401b03821117611ccb576040526060600382948054845260018101546020850152600281015460408501520154910152565b9080548015614264576141f0916141e46141ea926131ec565b9061235c565b50614189565b9060066141fd4292611c1f565b5001548015158061425b575b614253575b508151908181111561424a5790614224916131fb565b90811561424157610daa610c2392604060608401519301516136e8565b60609150015190565b50506060015190565b90503861420e565b50808211614209565b505050600090565b90815461427881613be1565b926142866040519485611ceb565b818452600090815260208082208186015b8484106142a5575050505050565b6004836001926142b485614189565b815201920193019290614297565b9190916000926142e46142df836000526008602052604060002090565b61426c565b9081511561444b5760066142fc604083015194611c1f565b50015491429280151580614442575b61443a575b50828411614430576143228482614454565b606061432e8284613c5b565b5101519361433c8184614454565b906143478285613c5b565b515181111561441a5790610daa61436d614390936143658488613c5b565b5151906131fb565b6040614388606061437e868a613c5b565b5101519488613c5b565b5101516136e8565b945b61439c8284613c5b565b515181116143de575b5050508183116143b457505050565b610c239394506143d092916143ca9151926131fb565b906136e8565b670de0b6b3a7640000900490565b6144119394509060406143886143fb610daa946143658588613c5b565b9260606144088288613c5b565b51015195613c5b565b903880806143a5565b5061442760609184613c5b565b51015194614392565b5060009450505050565b925038614310565b5080841161430b565b50600093505050565b8051918215614264576144686000936131ec565b61447183613c4e565b515182106144ee576144838184613c5b565b51518210156144e75791905b82841061449c5750505090565b9091926144ba6144b46144af868461368f565b613681565b60011c90565b90826144c68386613c5b565b5151116144d75750925b919061448f565b93506144e2906131ec565b6144d0565b9250505090565b50505090565b610caf61450391949394611c1f565b6101208101916001600160401b038351161561444b576060015142034281116108465761453a6112f984516001600160401b031690565b918282101561443057926145896112f961457b6145959561ffff61457461458f9761456e61014061459d9c015161ffff1690565b936131fb565b91166136e8565b92516001600160401b031690565b90613d69565b846136e8565b612710900490565b918083116145a85750565b9150565b805480156145e65760001901906145c38282611eb4565b6131d1576004816000809355826001820155826002820155826003820155015555565b634e487b7160e01b600052603160045260246000fd5b60009081526007602090815260408083206001600160a01b039094168352929052208054801561417a578083101561417a5760001981019081116108465780830361464d575b50611d4a91506145ac565b61465a6146629183611eb4565b509282611eb4565b6131d15782611d4a938203614678575b50614642565b600481819254845560018101546001850155600281015460028501556003810154600385015501549101553880614672565b6002546040516323b872dd60e01b602082019081526001600160a01b03928316602483015291909216604483015260648083019390935291815260009182916146f4608482611ceb565b5190827f0000000000000000000000009ff58067bd8d239000010c154c6983a325df138e6001600160a01b03165af161472b613b2b565b90156147545780518061473f575050600190565b6020111561474d5750600190565b6020015190565b50600090565b9061476482613be1565b604061477281519283611ceb565b8382528193614783601f1991613be1565b019060005b8281106147955750505050565b81519060c08201918083106001600160401b03841117611ccb57602092845260008152826000818301526000858301526000606083015260006080830152600060a0830152828701015201614788565b906147ef82613be1565b6147fc6040519182611ceb565b828152809261480d601f1991613be1565b0190602036910137565b4283111561426457610caf61482b91611c1f565b9142810390811161084657614851614856926040670de0b6b3a7640000950151906136e8565b6136e8565b049056feaa211e74adce5c21e4e0fc664561d516fa03c91b42283f5da9740ebb0f0e6901fc6ecd966b430510beae9124efe7dd517ed5286d7ed0ae258f8556c7a9765a44a2646970667358221220b119eca2bfbd9ccd76953d635b00a7010182e5ee6ba0446732bd827d5e1e809064736f6c63430008140033

Verified Source Code Full Match

Compiler: v0.8.20+commit.a1b79de6 EVM: paris Optimization: Yes (200 runs)
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @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.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
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].
     *
     * CAUTION: See Security Considerations above.
     */
    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);
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

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

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @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.encodeCall(token.approve, (spender, value));

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

    /**
     * @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);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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(token).code.length > 0;
    }
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) 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 FailedInnerCall();
        }
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Math.sol 415 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

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

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

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

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

    /**
     * @dev Returns the 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 towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (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 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                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.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 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.

            uint256 twos = denominator & (0 - denominator);
            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 (unsignedRoundsUp(rounding) && 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
     * towards zero.
     *
     * 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
ReentrancyGuard.sol 84 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

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

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
PlatformAccessController.sol 41 lines
// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

import "../admin-panel/PlatformAdminPanel.sol";

/**
 * @title Abstract contract from which platform contracts with admin function are inherited
 * @dev Contains the platform admin panel
 * Contains modifier that checks whether sender is platform admin, use platform admin panel
 */
abstract contract PlatformAccessController {
    address public _panel;

    error CallerNotAdmin();
    error AlreadyInitialized();

    function _initiatePlatformAccessController(address adminPanel) internal {
        if(address(_panel) != address(0))
            revert AlreadyInitialized();

        _panel = adminPanel;
    }

    /**
     * @dev Modifier that makes function available for platform admins only
     */
    modifier onlyPlatformAdmin() {
        if(!PlatformAdminPanel(_panel).isAdmin(msgSender()))
            revert CallerNotAdmin();
        _;
    }

    function _isAdmin() internal view returns (bool) {
        return PlatformAdminPanel(_panel).isAdmin(msgSender());
    }

    function msgSender() internal view virtual returns (address) {
        return msg.sender;
    }
}
PlatformAdminPanel.sol 106 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "../interfaces/IPlatformAdminPanel.sol";

/**
 * @title Platform admins holder contract
 * @notice Used to check accessibility of senders to admin functions in platform contracts
 */
contract PlatformAdminPanel is IPlatformAdminPanel {
    /**
     * @notice Emit during root admin set and reset
     */
    event SetRootAdmin(address indexed wallet);

    event InsertAdminList(address[] adminList);

    event RemoveAdminList(address[] adminList);

    mapping(address => bool) private _adminMap;
    address private _rootAdmin;

    modifier onlyRootAdmin() {
        require(_rootAdmin == msg.sender, "sender is not root admin");
        _;
    }

    /**
     * @notice Specify the root admin, only he has the rights to add and remove admins
     */
    constructor(address rootAdminWallet) {
        _setRootAdmin(rootAdminWallet);
    }

    /**
     * @notice Needed to determine if the user has admin rights for platform contracts
     */
    function isAdmin(address wallet)
        external
        view
        virtual
        override
        returns (bool)
    {
        return wallet == _rootAdmin || _adminMap[wallet];
    }

    function rootAdmin() external view returns (address) {
        return _rootAdmin;
    }

    /**
     * @notice Only root admin can call
     */
    function insertAdminList(address[] calldata adminList)
        external
        onlyRootAdmin
    {
        require(0 < adminList.length, "empty admin list");
        require(20 >= adminList.length, "list too large");

        uint256 index = adminList.length;
        while (0 < index) {
            --index;

            _adminMap[adminList[index]] = true;
        }

        emit InsertAdminList(adminList);
    }

    /**
     * @notice Only root admin can call
     */
    function removeAdminList(address[] calldata adminList)
        external
        onlyRootAdmin
    {
        require(0 < adminList.length, "empty admin list");
        require(20 >= adminList.length, "list too large");

        uint256 index = adminList.length;
        while (0 < index) {
            --index;

            _adminMap[adminList[index]] = false;
        }

        emit RemoveAdminList(adminList);
    }

    /**
     * @notice Only root admin can call
     */
    function setRootAdmin(address rootAdminWallet) external onlyRootAdmin {
        _setRootAdmin(rootAdminWallet);
    }

    function _setRootAdmin(address wallet) private {
        require(wallet != address(0), "wallet is zero address");

        _rootAdmin = wallet;

        emit SetRootAdmin(wallet);
    }
}
IPlatformAdminPanel.sol 7 lines
// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

interface IPlatformAdminPanel {
    function isAdmin(address wallet) external view returns (bool);
}
PropchainStakingV3.sol 1315 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

/**
 * @author Yash Gupta (Propchain) (GitHub: @theyashgupta)
 */

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import '@openzeppelin/contracts/utils/math/Math.sol';
import '../access-controller/PlatformAccessController.sol';

/**
 * @title PropchainStakingV3
 * @dev Staking contract with dynamic APYs, reward caps, checkpoints, and migration support
 */
contract PropchainStakingV3 is PlatformAccessController, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /// @dev Constants for precision and calculations
    uint256 private constant PRECISION = 1e18;
    uint256 private constant BASIS_POINTS = 10000;
    uint256 private constant SECONDS_PER_MONTH = 30 days;
    uint256 private constant MAX_REWARD_CAP = 1e36; // Maximum safe reward cap to prevent overflow
    uint16 private constant MAX_PENALTY_BPS = 4000; // Maximum penalty in basis points (40%)

    /// @notice Checkpoint for tracking reward rate changes over time
    struct Checkpoint {
        uint256 timestamp;
        uint256 totalStaked;
        uint256 rewardRatePerSec;
        uint256 cumulativeRewardPerToken;
    }

    /// @notice Pool configuration and state (optimized for storage packing)
    struct PoolInfo {
        uint256 rewardCap;           // total reward tokens allocated
        uint256 totalStaked;         // current TVL
        uint256 rewardRatePerSec;    // computed per-second rate
        uint256 lastCheckpoint;      // last APY update timestamp
        uint256 minAPY;              // minimum APY in basis points
        uint256 maxAPY;              // maximum APY in basis points
        uint256 endTime;             // pool end time (0 = infinite)
        uint256 currentAPY;          // current effective APY in basis points
        uint256 totalRewardsPaid;    // total rewards paid out from this pool
        uint64 lockupSeconds;        // lockup duration (packed slot)
        uint16 initialPenaltyBps;    // early withdrawal penalty bps (packed slot)
        bool isPaused;               // pool pause state (packed slot)
        string name;                 // pool name
    }

    /// @notice Individual stake information
    struct StakeInfo {
        uint256 amount;
        uint256 unlockTimestamp;
        uint256 lastClaimTimestamp;
        uint256 stakeTimestamp;
        uint256 totalClaimedRewards;
    }

    /// @notice Stake information with pending rewards (for view functions)
    struct StakeInfoWithRewards {
        uint256 amount;
        uint256 unlockTimestamp;
        uint256 lastClaimTimestamp;
        uint256 stakeTimestamp;
        uint256 pendingRewards;
        uint256 totalClaimedRewardsWithPendingRewards;
    }

    /// @notice Pool configuration for migration mode restoration
    struct PoolConfig {
        uint256 minAPY;              // minimum APY in basis points
        uint256 maxAPY;              // maximum APY in basis points
        uint16 initialPenaltyBps;    // early withdrawal penalty bps (max 4000 = 40%)
    }

    /// @dev Core contract state
    IERC20 public immutable stakingToken;
    address public rewardsWallet;
    address public penaltyWallet;
    uint256 public minStakeAmount = 1 ether;
    bool public migrationMode;

    /// @dev Pool and stake data
    PoolInfo[] public pools;
    mapping(uint256 => mapping(address => StakeInfo[])) public stakes;
    mapping(uint256 => Checkpoint[]) public poolCheckpoints;
    
    /// @dev Migration epoch counter - incremented each time migration mode is enabled
    uint256 private migrationEpoch;
    
    /// @dev Tracks per-user progress during migration to allow chunked processing
    mapping(address => uint256) private userMigrationCursor;
    
    /// @dev Tracks which migration epoch each user's cursor belongs to
    mapping(address => uint256) private userMigrationEpoch;
    
    /// @dev Tracks owed rewards when rewardsWallet transfer fails
    mapping(address => uint256) public owedRewards;

    /// @dev User action events
    event Staked(uint256 indexed poolId, address indexed user, uint256 stakeIndex, uint256 amount);
    event RewardClaimed(uint256 indexed poolId, address indexed user, uint256 stakeIndex, uint256 amount);
    event Withdrawn(uint256 indexed poolId, address indexed user, uint256 stakeIndex, uint256 amount, uint256 penalty);
    event UserMigrated(address indexed user, uint256 totalStaked, uint256 totalRewards);
    event RewardsOwed(address indexed user, uint256 amount, string reason);
    event OwedRewardsClaimed(address indexed user, uint256 amount);

    /// @dev Pool management events
    event PoolAdded(uint256 indexed poolId, string name);
    event PoolPaused(uint256 indexed poolId, bool isPaused);
    event CheckpointCreated(uint256 indexed poolId, uint256 timestamp, uint256 totalStaked, uint256 rewardRatePerSec);
    event CheckpointsCleanedUp(uint256 indexed poolId, uint256 oldCount, uint256 newCount);

    /// @dev Configuration events
    event PenaltyWalletUpdated(address indexed oldWallet, address indexed newWallet);
    event RewardsWalletUpdated(address indexed oldWallet, address indexed newWallet);
    event MinStakeUpdated(uint256 oldAmount, uint256 newAmount);
    event APYLimitsUpdated(uint256 indexed poolId, uint256 minAPY, uint256 maxAPY);
    event PoolEndTimeUpdated(uint256 indexed poolId, uint256 endTime);
    event PoolRewardCapSet(uint256 indexed poolId, uint256 oldCap, uint256 newCap);
    event PoolNameUpdated(uint256 indexed poolId, string oldName, string newName);
    event PoolPenaltyUpdated(uint256 indexed poolId, uint16 oldPenalty, uint16 newPenalty);
    event MigrationModeEnabled();
    event MigrationModeDisabled();

    /// @dev Custom errors
    error InvalidPoolId(uint256 poolId);
    error InvalidStakeIndex(uint256 stakeIndex);
    error InvalidAmount(uint256 amount);
    error InsufficientStake(uint256 requested, uint256 available);
    error InvalidAddress();
    error ArrayLengthMismatch();
    error PoolIsPaused(uint256 poolId);
    error BelowMinStake(uint256 amount, uint256 minStake);
    error PoolEnded(uint256 poolId);
    error MigrationModeActive();
    error MigrationModeNotActive();

    /// @dev Validation modifiers
    modifier validPool(uint256 poolId) {
        if (poolId >= pools.length) revert InvalidPoolId(poolId);
        _;
    }

    modifier validStake(uint256 poolId, address user, uint256 stakeIndex) {
        if (stakeIndex >= stakes[poolId][user].length) revert InvalidStakeIndex(stakeIndex);
        _;
    }

    modifier poolNotPaused(uint256 poolId) {
        if (pools[poolId].isPaused) revert PoolIsPaused(poolId);
        _;
    }

    modifier poolNotEnded(uint256 poolId) {
        if (pools[poolId].endTime > 0 && block.timestamp >= pools[poolId].endTime) {
            revert PoolEnded(poolId);
        }
        _;
    }

    modifier onlyInMigrationMode() {
        if (!migrationMode) revert MigrationModeNotActive();
        _;
    }

    modifier onlyNotInMigrationMode() {
        if (migrationMode) revert MigrationModeActive();
        _;
    }

    /// @notice Initialize the staking contract
    constructor(IERC20 _stakingToken, address _rewardsWallet, address _penaltyWallet, address adminPanel) {
        if (
            address(_stakingToken) == address(0) ||
            _rewardsWallet == address(0) ||
            _penaltyWallet == address(0) ||
            adminPanel == address(0)
        ) revert InvalidAddress();

        stakingToken = _stakingToken;
        rewardsWallet = _rewardsWallet;
        penaltyWallet = _penaltyWallet;
        _initiatePlatformAccessController(adminPanel);
    }

    // ========================================================
    //                    Admin Functions
    // ========================================================

    /**
     * @notice Pause or unpause a pool
     * @param poolId Pool identifier
     * @param isPaused True to pause, false to unpause
     */
    function setPoolPause(uint256 poolId, bool isPaused) external onlyPlatformAdmin validPool(poolId) {
        pools[poolId].isPaused = isPaused;
        emit PoolPaused(poolId, isPaused);
    }

    /**
     * @notice Update penalty wallet address
     * @param newPenaltyWallet New penalty wallet address
     */
    function setPenaltyWallet(address newPenaltyWallet) external onlyPlatformAdmin {
        if (newPenaltyWallet == address(0)) revert InvalidAddress();
        address oldWallet = penaltyWallet;
        penaltyWallet = newPenaltyWallet;
        emit PenaltyWalletUpdated(oldWallet, newPenaltyWallet);
    }

    /**
     * @notice Update minimum stake amount
     * @param newMinStake New minimum stake amount
     */
    function setMinStakeAmount(uint256 newMinStake) external onlyPlatformAdmin {
        uint256 oldAmount = minStakeAmount;
        minStakeAmount = newMinStake;
        emit MinStakeUpdated(oldAmount, newMinStake);
    }

    /**
     * @notice Update APY limits for a pool
     * @param poolId Pool identifier
     * @param minAPY Minimum APY in basis points
     * @param maxAPY Maximum APY in basis points
     */
    function setAPYLimits(uint256 poolId, uint256 minAPY, uint256 maxAPY) external onlyPlatformAdmin validPool(poolId) {
        if (maxAPY > 0 && minAPY > maxAPY) revert InvalidAmount(minAPY);

        pools[poolId].minAPY = minAPY;
        pools[poolId].maxAPY = maxAPY;

        emit APYLimitsUpdated(poolId, minAPY, maxAPY);
    }

    /**
     * @notice Set pool end time
     * @param poolId Pool identifier
     * @param endTime End time (0 = infinite)
     */
    function setPoolEndTime(uint256 poolId, uint256 endTime) external onlyPlatformAdmin validPool(poolId) {
        pools[poolId].endTime = endTime;
        emit PoolEndTimeUpdated(poolId, endTime);
    }

    /**
     * @notice Set reward cap for a pool
     * @param poolId Pool identifier
     * @param newCap New reward cap
     */
    function setRewardCap(uint256 poolId, uint256 newCap) external onlyPlatformAdmin validPool(poolId) {
        if (newCap > MAX_REWARD_CAP) revert InvalidAmount(newCap);
        uint256 oldCap = pools[poolId].rewardCap;
        pools[poolId].rewardCap = newCap;
        _updatePool(poolId);
        _createCheckpoint(poolId);
        emit PoolRewardCapSet(poolId, oldCap, newCap);
    }

    /**
     * @notice Set pool name
     * @param poolId Pool identifier
     * @param newName New pool name
     */
    function setPoolName(uint256 poolId, string calldata newName) external onlyPlatformAdmin validPool(poolId) {
        string memory oldName = pools[poolId].name;
        pools[poolId].name = newName;
        emit PoolNameUpdated(poolId, oldName, newName);
    }

    /**
     * @notice Set initial penalty BPS for a pool
     * @param poolId Pool identifier
     * @param newPenaltyBps New penalty BPS (max 4000 = 40%)
     */
    function setInitialPenaltyBps(uint256 poolId, uint16 newPenaltyBps) external onlyPlatformAdmin validPool(poolId) {
        if (newPenaltyBps > MAX_PENALTY_BPS) revert InvalidAmount(newPenaltyBps);
        
        uint16 oldPenalty = pools[poolId].initialPenaltyBps;
        pools[poolId].initialPenaltyBps = newPenaltyBps;
        emit PoolPenaltyUpdated(poolId, oldPenalty, newPenaltyBps);
    }

    /**
     * @notice Set rewards wallet address
     * @param newRewardsWallet New rewards wallet address
     */
    function setRewardsWallet(address newRewardsWallet) external onlyPlatformAdmin {
        if (newRewardsWallet == address(0)) revert InvalidAddress();
        address oldWallet = rewardsWallet;
        rewardsWallet = newRewardsWallet;
        emit RewardsWalletUpdated(oldWallet, newRewardsWallet);
    }

    /**
     * @notice Add a new staking pool
     * @param lockupSeconds Duration tokens must be locked up for
     * @param rewardCap Total reward tokens allocated to this pool
     * @param initialPenaltyBps Early withdrawal penalty in basis points (max 4000 = 40%)
     * @param name Name identifier for the pool
     * @param minAPY Minimum APY in basis points
     * @param maxAPY Maximum APY in basis points
     * @param endTime When the pool ends (0 = no end)
     */
    function addPool(
        uint64 lockupSeconds,
        uint256 rewardCap,
        uint16 initialPenaltyBps,
        string calldata name,
        uint256 minAPY,
        uint256 maxAPY,
        uint256 endTime
    ) external onlyPlatformAdmin {
        if (rewardCap > MAX_REWARD_CAP) revert InvalidAmount(rewardCap);
        if (initialPenaltyBps > MAX_PENALTY_BPS) revert InvalidAmount(initialPenaltyBps);
        
        pools.push(
            PoolInfo({
                rewardCap: rewardCap,
                totalStaked: 0,
                rewardRatePerSec: 0,
                lastCheckpoint: block.timestamp,
                minAPY: minAPY,
                maxAPY: maxAPY,
                endTime: endTime,
                currentAPY: 0,
                totalRewardsPaid: 0,
                lockupSeconds: lockupSeconds,
                initialPenaltyBps: initialPenaltyBps,
                isPaused: false,
                name: name
            })
        );
        uint256 poolId = pools.length - 1;
        poolCheckpoints[poolId].push(
            Checkpoint({ timestamp: block.timestamp, totalStaked: 0, rewardRatePerSec: 0, cumulativeRewardPerToken: 0 })
        );
        emit PoolAdded(poolId, name);
    }

    

    // ========================================================
    //                   Migration Functions
    // ========================================================

    /**
     * @notice Enable migration mode - pauses all pools, zeros penalties and locks APY at zero
     */
    function enableMigrationMode() external onlyPlatformAdmin {
        // Pause all pools and lock rewards at zero BEFORE setting migration mode
        for (uint256 poolId = 0; poolId < pools.length; poolId++) {
            pools[poolId].isPaused = true;
            pools[poolId].initialPenaltyBps = 0; // No withdrawal penalties

            // LOCK APY at zero - these won't change during migration
            pools[poolId].rewardRatePerSec = 0;
            pools[poolId].currentAPY = 0;
            pools[poolId].minAPY = 0;
            pools[poolId].maxAPY = 0;

            emit PoolPaused(poolId, true);
        }

        unchecked { ++migrationEpoch; }

        // Set migration mode AFTER updating pools
        migrationMode = true;

        // Create final checkpoints with zero rewards
        for (uint256 poolId = 0; poolId < pools.length; poolId++) {
            // Force create checkpoint with current zero values
            Checkpoint[] storage checkpoints = poolCheckpoints[poolId];
            checkpoints.push(
                Checkpoint({
                    timestamp: block.timestamp,
                    totalStaked: pools[poolId].totalStaked,
                    rewardRatePerSec: 0, // Explicitly zero
                    cumulativeRewardPerToken: _calculateNewCumulativeReward(poolId, checkpoints)
                })
            );
            emit CheckpointCreated(poolId, block.timestamp, pools[poolId].totalStaked, 0);
        }

        emit MigrationModeEnabled();
    }

    /**
     * @notice Disable migration mode and restore pool configurations
     * @param poolConfigs Array of pool configurations to restore after migration
     */
    function disableMigrationMode(
        PoolConfig[] calldata poolConfigs
    ) external onlyPlatformAdmin {
        if (poolConfigs.length != pools.length) revert ArrayLengthMismatch();
        
        migrationMode = false;

        for (uint256 poolId = 0; poolId < pools.length; poolId++) {
            PoolConfig memory config = poolConfigs[poolId];
            
            if (config.initialPenaltyBps > MAX_PENALTY_BPS) revert InvalidAmount(config.initialPenaltyBps);
            
            pools[poolId].isPaused = false;
            pools[poolId].minAPY = config.minAPY;
            pools[poolId].maxAPY = config.maxAPY;
            pools[poolId].initialPenaltyBps = config.initialPenaltyBps;
            
            _updatePool(poolId);
            _createCheckpoint(poolId);
            
            emit PoolPaused(poolId, false);
            emit APYLimitsUpdated(poolId, config.minAPY, config.maxAPY);
            emit PoolPenaltyUpdated(poolId, 0, config.initialPenaltyBps);
        }

        emit MigrationModeDisabled();
    }

    /**
     * @notice Batch withdraw all stakes for migration (only in migration mode)
     */
    function migrateWithdrawAll(uint256 maxPools) external nonReentrant onlyInMigrationMode {
        if (maxPools == 0) revert InvalidAmount(maxPools);
        uint256 poolCount = pools.length;
        uint256 totalWithdrawn;
        uint256 totalRewards;

        if (userMigrationEpoch[msg.sender] != migrationEpoch) {
            userMigrationCursor[msg.sender] = 0;
            userMigrationEpoch[msg.sender] = migrationEpoch;
        }

        uint256 startPoolId = userMigrationCursor[msg.sender];
        if (startPoolId >= poolCount) {
            return;
        }

        uint256 poolsToProcess = maxPools;
        uint256 remaining = poolCount - startPoolId;
        if (poolsToProcess > remaining) poolsToProcess = remaining;

        uint256 endPoolExclusive = startPoolId + poolsToProcess;

        for (uint256 poolId = startPoolId; poolId < endPoolExclusive;) {
            StakeInfo[] storage userStakes = stakes[poolId][msg.sender];
            uint256 stakeCount = userStakes.length;

            if (stakeCount > 0) {
                uint256 poolStakeAmount;

                for (uint256 i = stakeCount; i > 0;) {
                    unchecked { --i; }
                    StakeInfo storage userStake = userStakes[i];

                    if (userStake.amount > 0) {
                        uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStake);

                        unchecked {
                            totalWithdrawn += userStake.amount;
                            totalRewards += pending;
                            poolStakeAmount += userStake.amount;
                        }

                        if (pending > 0) {
                            unchecked { userStake.totalClaimedRewards += pending; }
                            userStake.lastClaimTimestamp = block.timestamp;

                            unchecked { pools[poolId].totalRewardsPaid += pending; }
                            emit RewardClaimed(poolId, msg.sender, i, pending);
                        }
                        emit Withdrawn(poolId, msg.sender, i, userStake.amount, 0);
                    }
                }

                unchecked { pools[poolId].totalStaked -= poolStakeAmount; }
                delete stakes[poolId][msg.sender];
            }

            unchecked { ++poolId; }
        }

        userMigrationCursor[msg.sender] = endPoolExclusive;

        if (totalWithdrawn > 0) stakingToken.safeTransfer(msg.sender, totalWithdrawn);
        if (totalRewards > 0) {
            if (_tryTransferRewards(msg.sender, totalRewards)) {
            } else {
                owedRewards[msg.sender] += totalRewards;
                emit RewardsOwed(msg.sender, totalRewards, "RewardsWallet transfer failed during migration");
            }
        }

        emit UserMigrated(msg.sender, totalWithdrawn, totalRewards);
    }

    /**
     * @notice Get user's total migration data
     * @param user User address
     * @return totalStaked Total staked amount across all pools
     * @return totalPendingRewards Total pending rewards across all pools
     * @return totalStakes Total number of stakes
     */
    function getUserMigrationSummary(address user) external view returns (
        uint256 totalStaked,
        uint256 totalPendingRewards,
        uint256 totalStakes
    ) {
        uint256 poolCount = pools.length;

        for (uint256 poolId = 0; poolId < poolCount; poolId++) {
            StakeInfo[] memory userStakes = stakes[poolId][user];
            uint256 stakeCount = userStakes.length;

            if (stakeCount == 0) continue; // Skip empty pools

            totalStakes += stakeCount;

            for (uint256 i = 0; i < stakeCount; i++) {
                StakeInfo memory stakeInfo = userStakes[i];
                if (stakeInfo.amount > 0) { // Only process non-zero stakes
                    totalStaked += stakeInfo.amount;
                    totalPendingRewards += _calculatePendingRewardsWithCheckpoints(poolId, stakeInfo);
                }
            }
        }
    }

    /**
     * @notice Check if migration mode is active
     * @return True if migration mode is active
     */
    function isMigrationMode() external view returns (bool) {
        return migrationMode;
    }

    // ========================================================
    //                   Staking Functions
    // ========================================================

    /// @notice Stake tokens in a specific pool
    function stake(uint256 poolId, uint256 amount) 
        external 
        nonReentrant 
        validPool(poolId) 
        onlyNotInMigrationMode 
        poolNotPaused(poolId) 
        poolNotEnded(poolId) 
    {
        if (amount == 0) revert InvalidAmount(amount);
        if (amount < minStakeAmount) revert BelowMinStake(amount, minStakeAmount);

        // Cache timestamp and calculate unlock time
        uint256 currentTime = block.timestamp;
        uint256 unlockTime = currentTime + pools[poolId].lockupSeconds;

        // Create stake
        stakes[poolId][msg.sender].push(
            StakeInfo({
                amount: amount,
                unlockTimestamp: unlockTime,
                lastClaimTimestamp: currentTime,
                stakeTimestamp: currentTime,
                totalClaimedRewards: 0
            })
        );

        // Update pool state
        unchecked { pools[poolId].totalStaked += amount; }
        _updatePool(poolId);
        _createCheckpoint(poolId);

        uint256 stakeIndex = stakes[poolId][msg.sender].length - 1;
        emit Staked(poolId, msg.sender, stakeIndex, amount);

        stakingToken.safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice Claim rewards from a specific stake
     * @param poolId Pool identifier
     * @param stakeIndex Index of the stake
     */
    function claim(
        uint256 poolId,
        uint256 stakeIndex
    ) external nonReentrant validPool(poolId) validStake(poolId, msg.sender, stakeIndex) {
        StakeInfo storage userStake = stakes[poolId][msg.sender][stakeIndex];

        // If pool has ended, ensure pool state is updated and checkpointed
        if (pools[poolId].endTime > 0 && block.timestamp >= pools[poolId].endTime) {
            _updatePool(poolId);
            _createCheckpoint(poolId);
        }
        
        uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStake);

        if (pending > 0) {
            userStake.lastClaimTimestamp = block.timestamp;
            userStake.totalClaimedRewards += pending;

            // Track total rewards paid for cap enforcement
            pools[poolId].totalRewardsPaid += pending;

            // Check if reward cap exceeded and update pool if needed
            if (pools[poolId].rewardCap > 0 && pools[poolId].totalRewardsPaid >= pools[poolId].rewardCap) {
                _updatePool(poolId);
                _createCheckpoint(poolId);
            }

            if (_tryTransferRewards(msg.sender, pending)) {
                emit RewardClaimed(poolId, msg.sender, stakeIndex, pending);
            } else {
                owedRewards[msg.sender] += pending;
                emit RewardsOwed(msg.sender, pending, "RewardsWallet transfer failed");
            }
        }
    }

    /// @notice Batch claim rewards for all stakes in all pools for the caller
    function batchClaim() external nonReentrant {
        uint256 poolCount = pools.length;
        uint256 currentTime = block.timestamp;

        for (uint256 poolId; poolId < poolCount;) {
            if (pools[poolId].endTime > 0 && block.timestamp >= pools[poolId].endTime) {
                _updatePool(poolId);
                _createCheckpoint(poolId);
            }
            StakeInfo[] storage userStakes = stakes[poolId][msg.sender];
            uint256 stakeCount = userStakes.length;

            for (uint256 stakeIndex; stakeIndex < stakeCount;) {
                StakeInfo storage userStake = userStakes[stakeIndex];
                uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStake);

                if (pending > 0) {
                    userStake.lastClaimTimestamp = currentTime;
                    unchecked { userStake.totalClaimedRewards += pending; }
                    unchecked { pools[poolId].totalRewardsPaid += pending; }

                    // Check if reward cap exceeded and update pool if needed
                    if (pools[poolId].totalRewardsPaid >= pools[poolId].rewardCap && pools[poolId].rewardCap > 0) {
                        _updatePool(poolId);
                        _createCheckpoint(poolId);
                    }

                    if (_tryTransferRewards(msg.sender, pending)) {
                        emit RewardClaimed(poolId, msg.sender, stakeIndex, pending);
                    } else {
                        owedRewards[msg.sender] += pending;
                        emit RewardsOwed(msg.sender, pending, "RewardsWallet transfer failed");
                    }
                }

                unchecked { ++stakeIndex; }
            }

            unchecked { ++poolId; }
        }
    }

    /// @notice Withdraw entire stake (with penalty if before unlock)
    function withdraw(uint256 poolId, uint256 stakeIndex) 
        external 
        nonReentrant 
        validPool(poolId) 
        validStake(poolId, msg.sender, stakeIndex) 
    {
        StakeInfo storage userStake = stakes[poolId][msg.sender][stakeIndex];
        uint256 stakeAmount = userStake.amount;
        if (stakeAmount == 0) revert InvalidAmount(0);

        uint256 currentTime = block.timestamp;

        // If pool has ended, ensure pool state is updated and checkpointed
        if (pools[poolId].endTime > 0 && currentTime >= pools[poolId].endTime) {
            _updatePool(poolId);
            _createCheckpoint(poolId);
        }

        // Calculate and claim pending rewards
        uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStake);
        if (pending > 0) {
            userStake.lastClaimTimestamp = currentTime;
            unchecked { userStake.totalClaimedRewards += pending; }
            unchecked { pools[poolId].totalRewardsPaid += pending; }

            if (_tryTransferRewards(msg.sender, pending)) {
                emit RewardClaimed(poolId, msg.sender, stakeIndex, pending);
            } else {
                owedRewards[msg.sender] += pending;
                emit RewardsOwed(msg.sender, pending, "RewardsWallet transfer failed");
            }
        }

        // Calculate early withdrawal penalty
        uint256 penalty;
        if (currentTime < userStake.unlockTimestamp) {
            penalty = _calculatePenalty(poolId, userStake, stakeAmount);
            if (penalty > stakeAmount) penalty = stakeAmount;
        }

        // Update pool state and remove stake
        unchecked { pools[poolId].totalStaked -= stakeAmount; }
        _updatePool(poolId);
        _createCheckpoint(poolId);
        _removeStake(poolId, msg.sender, stakeIndex);

        // Transfer tokens
        unchecked {
            uint256 withdrawAmount = stakeAmount - penalty;
            if (withdrawAmount > 0) stakingToken.safeTransfer(msg.sender, withdrawAmount);
            if (penalty > 0) stakingToken.safeTransfer(penaltyWallet, penalty);
        }

        emit Withdrawn(poolId, msg.sender, stakeIndex, stakeAmount, penalty);
    }

    /// @notice Claim owed rewards that failed to transfer during withdrawal
    function claimOwedRewards(uint256 amount) external nonReentrant {
        uint256 userOwedRewards = owedRewards[msg.sender];
        if (userOwedRewards == 0) revert InvalidAmount(0);

        uint256 claimAmount = amount == 0 ? userOwedRewards : amount;
        if (claimAmount > userOwedRewards) revert InvalidAmount(claimAmount);

        if (_tryTransferRewards(msg.sender, claimAmount)) {
            owedRewards[msg.sender] -= claimAmount;
            emit OwedRewardsClaimed(msg.sender, claimAmount);
        } else {
            revert("RewardsWallet transfer failed");
        }
    }

    // ========================================================
    //                  Internal Functions
    // ========================================================

    /// @notice Update pool reward rate based on current state
    function _updatePool(uint256 poolId) internal {
        PoolInfo storage pool = pools[poolId];

        // Early returns for special states
        if (migrationMode) {
            pool.rewardRatePerSec = 0;
            pool.currentAPY = 0;
            pool.lastCheckpoint = block.timestamp;
            return;
        }

        if (pool.endTime > 0 && block.timestamp >= pool.endTime) {
            pool.rewardRatePerSec = 0;
            pool.currentAPY = 0;
            pool.lastCheckpoint = block.timestamp;
            return;
        }

        // Cache pool values to reduce storage reads
        uint256 totalStaked = pool.totalStaked;
        uint256 rewardCap = pool.rewardCap;
        uint256 totalRewardsPaid = pool.totalRewardsPaid;
        uint256 minAPY = pool.minAPY;
        uint256 maxAPY = pool.maxAPY;

        uint256 newAPY;

        // Calculate APY based on current state
        if (totalRewardsPaid >= rewardCap && rewardCap > 0) {
            newAPY = minAPY; // Cap exceeded
        } else if (totalStaked == 0) {
            newAPY = 0; // No stakes, freeze rewards
        } else if (rewardCap > 0) {
            // Calculate theoretical APY from original reward cap (fixed allocation)
            uint256 annualFactor = (365 days * BASIS_POINTS) / pool.lockupSeconds;
            uint256 theoreticalAPY = Math.mulDiv(rewardCap, annualFactor, totalStaked);

            // Apply limits
            newAPY = theoreticalAPY;
            if (minAPY > 0 && newAPY < minAPY) newAPY = minAPY;
            if (maxAPY > 0 && newAPY > maxAPY) newAPY = maxAPY;
        } else {
            // No cap, use min APY but check for zero stakes first
            if (totalStaked == 0) {
                newAPY = 0; // No stakes, freeze rewards
            } else {
                newAPY = minAPY; // No cap, use min APY
            }
        }

        // Update pool state
        pool.currentAPY = newAPY;
        pool.rewardRatePerSec = Math.mulDiv(newAPY, PRECISION, 365 days * BASIS_POINTS);
        pool.lastCheckpoint = block.timestamp;
    }

    /**
     * @notice Create a new checkpoint for APY tracking
     * @param poolId Pool identifier
     */
    function _createCheckpoint(uint256 poolId) internal {
        PoolInfo memory pool = pools[poolId];
        Checkpoint[] storage checkpoints = poolCheckpoints[poolId];

        // CRITICAL: Don't create new checkpoints during migration mode
        // The final checkpoint was created when migration mode was enabled
        if (migrationMode && checkpoints.length > 0) {
            return; // Skip checkpoint creation entirely
        }

        // Only create checkpoint if rate or stake amount changed
        if (
            checkpoints.length == 0 ||
            checkpoints[checkpoints.length - 1].rewardRatePerSec != pool.rewardRatePerSec ||
            checkpoints[checkpoints.length - 1].totalStaked != pool.totalStaked
        ) {
            checkpoints.push(
                Checkpoint({
                    timestamp: block.timestamp,
                    totalStaked: pool.totalStaked,
                    rewardRatePerSec: pool.rewardRatePerSec,
                    cumulativeRewardPerToken: _calculateNewCumulativeReward(poolId, checkpoints)
                })
            );

            emit CheckpointCreated(poolId, block.timestamp, pool.totalStaked, pool.rewardRatePerSec);
        }
    }

    /// @notice Calculate new cumulative reward per token for a checkpoint
    function _calculateNewCumulativeReward(
        uint256 poolId,
        Checkpoint[] storage checkpoints
    ) internal view returns (uint256) {
        if (checkpoints.length == 0) {
            return 0;
        }

        Checkpoint memory lastCheckpoint = checkpoints[checkpoints.length - 1];
        // Cap accrual at pool end time if set
        uint256 effectiveNow = block.timestamp;
        uint256 poolEnd = pools[poolId].endTime;
        if (poolEnd > 0 && effectiveNow > poolEnd) {
            effectiveNow = poolEnd;
        }
        if (effectiveNow <= lastCheckpoint.timestamp) {
            return lastCheckpoint.cumulativeRewardPerToken;
        }
        uint256 timeDelta = effectiveNow - lastCheckpoint.timestamp;

        if (timeDelta == 0) {
            return lastCheckpoint.cumulativeRewardPerToken;
        }

        return lastCheckpoint.cumulativeRewardPerToken + lastCheckpoint.rewardRatePerSec * timeDelta;
    }

    /**
     * @notice Calculate pending rewards using optimized prefix sum approach
     * @param poolId Pool identifier
     * @param userStake Stake information
     * @return pending Pending reward amount
     */
    function _calculatePendingRewardsWithCheckpoints(
        uint256 poolId,
        StakeInfo memory userStake
    ) internal view returns (uint256 pending) {
        Checkpoint[] memory checkpoints = poolCheckpoints[poolId];
        if (checkpoints.length == 0) return 0;

        uint256 lastClaimTime = userStake.lastClaimTimestamp;
        uint256 currentTime = block.timestamp;

        // Cap calculation window at pool end time if set
        uint256 poolEnd = pools[poolId].endTime;
        uint256 effectiveNow = currentTime;
        if (poolEnd > 0 && effectiveNow > poolEnd) {
            effectiveNow = poolEnd;
        }
        if (lastClaimTime > effectiveNow) {
            // Nothing to accrue after end time
            return 0;
        }

        // Find checkpoint at last claim time using binary search
        uint256 startIdx = _findCheckpointAtTimestamp(checkpoints, lastClaimTime);

        // Get cumulative reward per token at last claim time
        uint256 startCumulative = checkpoints[startIdx].cumulativeRewardPerToken;

        // Create a fresh checkpoint to get accurate current cumulative reward
        // This eliminates precision issues with manual partial calculations
        uint256 endCumulative;
        uint256 endIdx = _findCheckpointAtTimestamp(checkpoints, effectiveNow);
        
        if (effectiveNow > checkpoints[endIdx].timestamp) {
            // Calculate end cumulative with current timestamp
            uint256 timeDelta = effectiveNow - checkpoints[endIdx].timestamp;
            endCumulative = checkpoints[endIdx].cumulativeRewardPerToken + 
                           checkpoints[endIdx].rewardRatePerSec * timeDelta;
        } else {
            endCumulative = checkpoints[endIdx].cumulativeRewardPerToken;
        }
        
        // For start cumulative, if lastClaimTime is after the checkpoint, calculate accordingly
        if (lastClaimTime > checkpoints[startIdx].timestamp) {
            uint256 timeDelta = lastClaimTime - checkpoints[startIdx].timestamp;
            startCumulative = checkpoints[startIdx].cumulativeRewardPerToken + 
                             checkpoints[startIdx].rewardRatePerSec * timeDelta;
        }

        // Calculate pending rewards: amount * (endCumulative - startCumulative) / PRECISION
        if (endCumulative > startCumulative) {
            pending = (userStake.amount * (endCumulative - startCumulative)) / PRECISION;
        }
    }

    /**
     * @notice Binary search to find the checkpoint at or before a given timestamp
     * @param checkpoints Array of checkpoints
     * @param timestamp Target timestamp
     * @return Index of the checkpoint
     */
    function _findCheckpointAtTimestamp(
        Checkpoint[] memory checkpoints,
        uint256 timestamp
    ) internal pure returns (uint256) {
        if (checkpoints.length == 0) {
            return 0;
        }

        uint256 left = 0;
        uint256 right = checkpoints.length - 1;

        // If timestamp is before first checkpoint, return 0
        if (timestamp < checkpoints[0].timestamp) {
            return 0;
        }

        // If timestamp is after last checkpoint, return last index
        if (timestamp >= checkpoints[right].timestamp) {
            return right;
        }

        // Binary search for the last checkpoint with timestamp <= target
        while (left < right) {
            uint256 mid = (left + right + 1) / 2;
            if (checkpoints[mid].timestamp <= timestamp) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }

        return left;
    }

    /**
     * @notice Calculate penalty for early withdrawal
     * @param poolId Pool identifier
     * @param userStake Stake information
     * @param withdrawAmount Amount being withdrawn
     * @return penalty Penalty amount
     */
    function _calculatePenalty(
        uint256 poolId,
        StakeInfo memory userStake,
        uint256 withdrawAmount
    ) internal view returns (uint256 penalty) {
        PoolInfo memory pool = pools[poolId];

        if (pool.lockupSeconds == 0) return 0;

        // Calculate elapsed time since stake start
        uint256 stakeStartTime = userStake.stakeTimestamp;
        uint256 elapsed = block.timestamp - stakeStartTime;

        if (elapsed >= pool.lockupSeconds) return 0;

        // Linear penalty reduction: penaltyBps = initialPenaltyBps * (lockupSeconds - elapsed) / lockupSeconds
        uint256 penaltyBps = (pool.initialPenaltyBps * (pool.lockupSeconds - elapsed)) / pool.lockupSeconds;
        penalty = (withdrawAmount * penaltyBps) / BASIS_POINTS;

        if (penalty > withdrawAmount) {
            penalty = withdrawAmount;
        }
    }

    /**
     * @notice Remove a stake from user's stakes array
     * @param poolId Pool identifier
     * @param user User address
     * @param stakeIndex Index of stake to remove
     */
    function _removeStake(uint256 poolId, address user, uint256 stakeIndex) internal {
        StakeInfo[] storage userStakes = stakes[poolId][user];

        if (userStakes.length == 0) return;
        if (stakeIndex >= userStakes.length) return;

        if (stakeIndex != userStakes.length - 1) {
            userStakes[stakeIndex] = userStakes[userStakes.length - 1];
        }
        userStakes.pop();
    }

    /**
     * @notice Internal function to try transferring rewards from rewardsWallet
     * @param to Recipient address
     * @param amount Amount to transfer
     * @return success True if transfer succeeded, false otherwise
     */
    function _tryTransferRewards(address to, uint256 amount) internal returns (bool success) {
        (bool callSuccess, bytes memory returnData) = address(stakingToken).call(
            abi.encodeWithSelector(
                stakingToken.transferFrom.selector,
                rewardsWallet,
                to,
                amount
            )
        );

        if (!callSuccess) {
            return false;
        }

        if (returnData.length > 0) {
            bool transferSuccess;
            if (returnData.length >= 32) {
                assembly {
                    transferSuccess := mload(add(returnData, 32))
                }
                return transferSuccess;
            }
            return true;
        }

        return true;
    }

    // ========================================================
    //                    View Functions
    // ========================================================

    /// @notice Get pool information
    function getPoolInfo(uint256 poolId) external view validPool(poolId) returns (PoolInfo memory) {
        return pools[poolId];
    }

    /// @notice Get all stakes for a user in a pool with pending rewards
    function getUserStakes(uint256 poolId, address user) 
        external 
        view 
        validPool(poolId) 
        returns (StakeInfoWithRewards[] memory) 
    {
        StakeInfo[] memory userStakes = stakes[poolId][user];
        uint256 stakeCount = userStakes.length;
        StakeInfoWithRewards[] memory stakesWithRewards = new StakeInfoWithRewards[](stakeCount);

        for (uint256 i; i < stakeCount;) {
            StakeInfo memory currentStake = userStakes[i];
            uint256 pendingRewards = _calculatePendingRewardsWithCheckpoints(poolId, currentStake);

            stakesWithRewards[i] = StakeInfoWithRewards({
                amount: currentStake.amount,
                unlockTimestamp: currentStake.unlockTimestamp,
                lastClaimTimestamp: currentStake.lastClaimTimestamp,
                stakeTimestamp: currentStake.stakeTimestamp,
                pendingRewards: pendingRewards,
                totalClaimedRewardsWithPendingRewards: currentStake.totalClaimedRewards + pendingRewards
            });

            unchecked { ++i; }
        }

        return stakesWithRewards;
    }

    /// @notice Get pending rewards for all stakes of a user in a pool
    function getPendingRewards(uint256 poolId, address user) 
        external 
        view 
        validPool(poolId) 
        returns (uint256[] memory) 
    {
        StakeInfo[] memory userStakes = stakes[poolId][user];
        uint256 stakeCount = userStakes.length;
        uint256[] memory pendingRewards = new uint256[](stakeCount);

        for (uint256 i; i < stakeCount;) {
            pendingRewards[i] = _calculatePendingRewardsWithCheckpoints(poolId, userStakes[i]);
            unchecked { ++i; }
        }

        return pendingRewards;
    }

    /// @notice Get total pending rewards for a user across all pools
    function getTotalPendingRewards(address user) external view returns (uint256 totalPending) {
        uint256 poolCount = pools.length;
        for (uint256 poolId; poolId < poolCount;) {
            StakeInfo[] memory userStakes = stakes[poolId][user];
            uint256 stakeCount = userStakes.length;

            for (uint256 i; i < stakeCount;) {
                unchecked {
                    totalPending += _calculatePendingRewardsWithCheckpoints(poolId, userStakes[i]);
                    ++i;
                }
            }
            unchecked { ++poolId; }
        }
    }

    /// @notice Calculate penalty for early withdrawal of entire stake
    function calculateWithdrawPenalty(uint256 poolId, address user, uint256 stakeIndex) 
        external 
        view 
        validPool(poolId) 
        validStake(poolId, user, stakeIndex) 
        returns (uint256) 
    {
        StakeInfo memory userStake = stakes[poolId][user][stakeIndex];
        return block.timestamp >= userStake.unlockTimestamp ? 
            0 : _calculatePenalty(poolId, userStake, userStake.amount);
    }

    /**
     * @notice Calculate future rewards for a hypothetical stake at a given timestamp
     * @param poolId Pool identifier
     * @param amount Amount to stake
     * @param futureTimestamp Future timestamp to calculate rewards for
     * @return futureRewards Expected rewards at the future timestamp
     */
    function calculateFutureRewards(
        uint256 poolId,
        uint256 amount,
        uint256 futureTimestamp
    ) external view validPool(poolId) returns (uint256 futureRewards) {
        if (futureTimestamp <= block.timestamp) {
            return 0;
        }
        PoolInfo memory pool = pools[poolId];
        uint256 timeDelta = futureTimestamp - block.timestamp;
        futureRewards = (amount * pool.rewardRatePerSec * timeDelta) / PRECISION;
    }

    /**
     * @notice Get checkpoints for a pool
     * @param poolId Pool identifier
     * @return Array of checkpoints
     */
    function getPoolCheckpoints(uint256 poolId) external view validPool(poolId) returns (Checkpoint[] memory) {
        return poolCheckpoints[poolId];
    }

    /**
     * @notice Get total number of pools
     * @return Number of pools
     */
    function getPoolCount() external view returns (uint256) {
        return pools.length;
    }

    /**
     * @notice Get number of stakes for a user in a pool
     * @param poolId Pool identifier
     * @param user User address
     * @return Number of stakes
     */
    function getUserStakeCount(uint256 poolId, address user) external view validPool(poolId) returns (uint256) {
        return stakes[poolId][user].length;
    }

    /**
     * @notice Get current penalty wallet address
     * @return Penalty wallet address
     */
    function getPenaltyWallet() external view returns (address) {
        return penaltyWallet;
    }

    /**
     * @notice Get minimum stake amount
     * @return Minimum stake amount
     */
    function getMinStakeAmount() external view returns (uint256) {
        return minStakeAmount;
    }

    /**
     * @notice Get APY limits for a pool
     * @param poolId Pool identifier
     * @return minAPY Minimum APY in basis points
     * @return maxAPY Maximum APY in basis points
     */
    function getAPYLimits(uint256 poolId) external view validPool(poolId) returns (uint256 minAPY, uint256 maxAPY) {
        PoolInfo memory pool = pools[poolId];
        return (pool.minAPY, pool.maxAPY);
    }

    /**
     * @notice Get pool end time
     * @param poolId Pool identifier
     * @return endTime Pool end time (0 = infinite)
     */
    function getPoolEndTime(uint256 poolId) external view validPool(poolId) returns (uint256 endTime) {
        return pools[poolId].endTime;
    }

    /**
     * @notice Get current APY for a pool
     * @param poolId Pool identifier
     * @return apy Annual percentage yield in basis points
     */
    function getCurrentAPY(uint256 poolId) external view validPool(poolId) returns (uint256 apy) {
        return pools[poolId].currentAPY;
    }

    /**
     * @notice Check if a specific stake is matured (lockup period is over)
     * @param poolId Pool identifier
     * @param user User address
     * @param stakeIndex Index of the stake
     * @return isMatured True if the stake is matured, false otherwise
     */
    function isStakeMatured(
        uint256 poolId,
        address user,
        uint256 stakeIndex
    ) external view validPool(poolId) validStake(poolId, user, stakeIndex) returns (bool isMatured) {
        StakeInfo memory userStake = stakes[poolId][user][stakeIndex];
        return block.timestamp >= userStake.unlockTimestamp;
    }

    /**
     * @notice Get total earned rewards (claimed + pending) for a specific stake
     * @param poolId Pool identifier
     * @param user User address
     * @param stakeIndex Index of the stake
     * @return totalEarned Total rewards ever earned for this stake
     */
    function getTotalEarnedForStake(
        uint256 poolId,
        address user,
        uint256 stakeIndex
    ) external view validPool(poolId) validStake(poolId, user, stakeIndex) returns (uint256 totalEarned) {
        StakeInfo memory userStake = stakes[poolId][user][stakeIndex];
        uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStake);
        return userStake.totalClaimedRewards + pending;
    }

    /**
     * @notice Get all-time total rewards earned (claimed + pending) for a user in a pool
     * @param poolId Pool identifier
     * @param user User address
     * @return totalEarned All-time total rewards for the user in the pool
     */
    function getTotalEarnedForUserInPool(
        uint256 poolId,
        address user
    ) external view validPool(poolId) returns (uint256 totalEarned) {
        StakeInfo[] memory userStakes = stakes[poolId][user];
        for (uint256 i = 0; i < userStakes.length; i++) {
            uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStakes[i]);
            totalEarned += userStakes[i].totalClaimedRewards + pending;
        }
    }

    /**
     * @notice Get all-time total rewards earned (claimed + pending) for a user across all pools
     * @param user User address
     * @return totalEarned All-time total rewards for the user across all pools
     */
    function getTotalEarnedForUserInAllPools(address user) external view returns (uint256 totalEarned) {
        uint256 poolCount = pools.length;
        for (uint256 poolId = 0; poolId < poolCount; poolId++) {
            StakeInfo[] memory userStakes = stakes[poolId][user];
            for (uint256 i = 0; i < userStakes.length; i++) {
                uint256 pending = _calculatePendingRewardsWithCheckpoints(poolId, userStakes[i]);
                totalEarned += userStakes[i].totalClaimedRewards + pending;
            }
        }
    }

    /**
     * @notice Get total staked amount for a user across all pools
     * @param user User address
     * @return totalStaked Total staked amount across all pools
     */
    function getTotalStakedByUser(address user) external view returns (uint256 totalStaked) {
        uint256 poolCount = pools.length;
        for (uint256 poolId = 0; poolId < poolCount; poolId++) {
            StakeInfo[] memory userStakes = stakes[poolId][user];
            for (uint256 i = 0; i < userStakes.length; i++) {
                totalStaked += userStakes[i].amount;
            }
        }
    }

    /**
     * @notice Get amount of owed rewards for a user
     * @param user User address
     * @return amount Amount of owed rewards
     */
    ...

// [truncated — 50121 bytes total]

Read Contract

_panel 0x8b4db06b → address
calculateFutureRewards 0x77ff1111 → uint256
calculateWithdrawPenalty 0xa5bedf13 → uint256
getAPYLimits 0x93dfad23 → uint256, uint256
getCurrentAPY 0x7fbf3853 → uint256
getMinStakeAmount 0x527cb1d7 → uint256
getOwedRewards 0xb4b114ed → uint256
getPenaltyWallet 0xbe40e7a9 → address
getPendingRewards 0x85dc0aaf → uint256[]
getPoolCheckpoints 0x203b79b6 → tuple[]
getPoolCount 0x8eec5d70 → uint256
getPoolEndTime 0xa19e2683 → uint256
getPoolInfo 0x2f380b35 → tuple
getTotalEarnedForStake 0x172e7852 → uint256
getTotalEarnedForUserInAllPools 0x85d0b699 → uint256
getTotalEarnedForUserInPool 0xc0f013db → uint256
getTotalPendingRewards 0xa8c478ba → uint256
getTotalStakedByUser 0x0951984d → uint256
getUserMigrationSummary 0x34308561 → uint256, uint256, uint256
getUserStakeCount 0x2cbdfac9 → uint256
getUserStakes 0x14ce783d → tuple[]
isMigrationMode 0xdc690ab3 → bool
isStakeMatured 0xdeb60203 → bool
migrationMode 0x7a01e2bd → bool
minStakeAmount 0xf1887684 → uint256
owedRewards 0x4b517003 → uint256
penaltyWallet 0x8b752677 → address
poolCheckpoints 0xc60b337f → uint256, uint256, uint256, uint256
pools 0xac4afa38 → uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint64, uint16, bool, string
rewardsWallet 0x5b35f9c9 → address
stakes 0xb1427ac1 → uint256, uint256, uint256, uint256, uint256
stakingToken 0x72f702f3 → address

Write Contract 18 functions

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

addPool 0x10f83511
uint64 lockupSeconds
uint256 rewardCap
uint16 initialPenaltyBps
string name
uint256 minAPY
uint256 maxAPY
uint256 endTime
batchClaim 0xf4af0bd0
No parameters
claim 0xc3490263
uint256 poolId
uint256 stakeIndex
claimOwedRewards 0xc2d0a6f1
uint256 amount
disableMigrationMode 0x8dae030b
tuple[] poolConfigs
enableMigrationMode 0xd9d2c332
No parameters
migrateWithdrawAll 0x101527a5
uint256 maxPools
setAPYLimits 0x2c17bbcc
uint256 poolId
uint256 minAPY
uint256 maxAPY
setInitialPenaltyBps 0x97c51bc1
uint256 poolId
uint16 newPenaltyBps
setMinStakeAmount 0xeb4af045
uint256 newMinStake
setPenaltyWallet 0x9d59c134
address newPenaltyWallet
setPoolEndTime 0x5ca73f2b
uint256 poolId
uint256 endTime
setPoolName 0x20c32bfe
uint256 poolId
string newName
setPoolPause 0xc706b316
uint256 poolId
bool isPaused
setRewardCap 0x0717404f
uint256 poolId
uint256 newCap
setRewardsWallet 0xa1980430
address newRewardsWallet
stake 0x7b0472f0
uint256 poolId
uint256 amount
withdraw 0x441a3e70
uint256 poolId
uint256 stakeIndex

Recent Transactions

No transactions found for this address