Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0xD5dDA2e271808A6986d63283072AC7378e926cCB
Balance 0 ETH
Nonce 1
Code Size 19990 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

19990 bytes
0x6080806040526004361015610012575f80fd5b5f3560e01c90816301ffc9a714613a1e5750806306fdde031461397757806307edffc9146138b6578063081812fc1461387a578063095ea7b31461379957806323b872dd1461378357806324d7806c1461372d5780632e1a7d4d146136595780633bb2c7731461339457806342842e0e14613370578063547827d3146130c65780636352211e1461309657806370a082311461304057806370f8f9d91461300e578063715018a614612fa957806376a7d15214612e0c57806379ba509714612d8a5780637f59729f14612cb15780638da5cb5b14612c895780639168ae7214612c4557806395d89b4114612b6757806399627a66146126ec578063a22cb46514612642578063a23c44b1146125c8578063a91195e51461251f578063ae169a5014611961578063b64a7f8c14611900578063b6b55f2514611838578063b88d4fde146117df578063c87b56dd14611774578063d16856ca14611563578063d1af0c7d1461153b578063d1c0b58d1461098d578063d2be97831461063d578063df6fa20e146105b3578063e2ceea44146102b3578063e30c39781461028b578063e985e9c5146102395763f2fde38b146101c9575f80fd5b34610235576020366003190112610235576101e2613ae9565b6101ea614552565b600880546001600160a01b0319166001600160a01b039283169081179091556007549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227005f80a3005b5f80fd5b3461023557604036600319011261023557610252613ae9565b61025a613aff565b9060018060a01b038091165f52600560205260405f2091165f52602052602060ff60405f2054166040519015158152f35b34610235575f366003190112610235576008546040516001600160a01b039091168152602090f35b3461023557602080600319360112610235576001600160401b03600435818111610235576102e5903690600401613cd1565b335f526013835260ff60405f205416801561059f575b61030490613ee9565b6040519261031184613c0e565b5f845260405161032081613bbb565b5f81525f828201525f60408201525f60608201525f60808201525f60a08201525f60c08201525f60e0820152610100925f848301526040519461036286613ba0565b8186528386019687526103918460408801935f8552606089019586528160405193828580945193849201613aa3565b810160108152030190209551805191821161051d576103ba826103b48954613e20565b89613f43565b8490601f831160011461053c576103e892915f9183610531575b50508160011b915f199060031b1c19161790565b85555b60019560018601905190815191600160401b831161051d578590825484845580851061049f575b5001905f52845f205f915b83831061048357845160028a01558551805160038b01558088015160048b0155604081015160058b0155606081015160068b0155608081015160078b015560a081015160088b015560c081015160098b015560e0810151600a8b0155880151600b8a0155005b600487826104938d94518661415f565b0192019201919061041d565b9091506001600160fe1b038082168203610509578416840361050957908691835f52825f209060021b8101908560021b015b8181106104de5750610412565b6004919293506104ff8160035f918281558260018201558260028201550155565b01908792916104d1565b634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b0151905089806103d4565b90601f19831691885f52865f20925f5b88828210610589575050908460019594939210610571575b505050811b0185556103eb565b01515f1960f88460031b161c19169055888080610564565b600185968293968601518155019501930161054c565b506007546001600160a01b031633146102fb565b34610235576020366003190112610235577fcebb02e73e402e0164947d10baf9c730c1f4764e714c7a999fec05b8004f93ed61062c6105f0613ae9565b6105f8614552565b60018060a01b0316805f52601360205260405f209060ff198254168255604051928392606084526001606085019101613e58565b9060208301525f60408301520390a1005b34610235576101008060031936011261023557600435602435916064359160843593335f526020916013835260ff60405f2054168015610979575b61068190613ee9565b8015158061096e575b61069390613f26565b604051956106a087613c0e565b5f8752604051956106db60296866617374747261636b60b81b9889815260106009820152206007810154421090811591610961575b50613f26565b6106e742821015613f26565b8184101580610957575b6106fa90613f26565b6040519361070785613bbb565b8385528585015260443560408501526060840152608083015260a43560a083015260c43560c083015260e43560e08301525f8483015260296040519561074c87613ba0565b60405161075881613c29565b60098152818682015287528487019788526040870192835260608701938452604051908152601060098201522094518051906001600160401b03821161051d576107a6826103b48954613e20565b8490601f83116001146108f4576107d392915f91836105315750508160011b915f199060031b1c19161790565b85555b60019560018601905190815191600160401b831161051d578590825484845580851061088a575b5001905f52845f205f915b83831061086e57845160028a01558551805160038b01558088015160048b0155604081015160058b0155606081015160068b0155608081015160078b015560a081015160088b015560c081015160098b015560e0810151600a8b0155880151600b8a0155005b6004878261087e8d94518661415f565b01920192019190610808565b9091506001600160fe1b038082168203610509578416840361050957908691835f52825f209060021b8101908560021b015b8181106108c957506107fd565b6004919293506108ea8160035f918281558260018201558260028201550155565b01908792916108bc565b90601f19831691885f52865f20925f5b88828210610941575050908460019594939210610929575b505050811b0185556107d6565b01515f1960f88460031b161c1916905588808061091c565b6001859682939686015181550195019301610904565b50808210156106f1565b600391500154158a6106d5565b50613a98811061068a565b506007546001600160a01b03163314610678565b34610235576080366003190112610235576004356001600160401b038111610235576109bd903690600401613cd1565b6064356001600160401b038111610235576109dc903690600401613cd1565b906109e56143f5565b6040516020810190610a0f6020828651610a028187858b01613aa3565b8101038084520182613c5f565b51902090610a1b614124565b8214801561152b575b801561151b575b801561150b575b806114dc575b610a4190613f26565b610a4f600c54602435613fb8565b91610a5b600a546143ad565b9283600a55604051610a6c81613c0e565b5f815233156114c4575f858152600260205260409020546001600160a01b031680611491575b335f52600360205260405f2060018154019055855f52600260205260405f20336001600160601b0360a01b8254161790558533827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef5f80a461147957333b61135e575b50835f52600660205260405f2083516001600160401b03811161051d57610b2681610b208454613e20565b84613f43565b6020601f82116001146112f65781610bb6949392610b58925f916112eb575b508160011b915f199060031b1c19161790565b90555b7ff8e1a15aba9398e019f0b49df1a4fde98ee17ae345cb5f6b5e2c27f5033e8ce76020604051878152a16040516020818651610b9a8183858b01613aa3565b81016014815203019020600160ff19825416179055303361450d565b336001600160a01b03610bc8856143bb565b160361023557335f52601160205260405f208054600d5411156112c15760018101336001600160601b0360a01b8254161790556040516020818751610c108183858c01613aa3565b6010818301528101030190205f955f9042905f80604051610c3081613ba0565b5f81525f60208201525f60408201525f606082015291610c4e614124565b891480156112b1575b1561112a57505060018501545f5b8181106110e9575050604081015195602082015194851515806110dd575b806110d0575b610c9290613f26565b600c54612710600c610ca4838a613fb8565b04049c62278d0090604435826044350204821460443515171561050957610ccf916044350290614358565b99610cd8614124565b03611044575050610cee6044359b602435613fb8565b955b6040519b610cfd8d613bf2565b8b8d528c602435906020015260408d015f905260608d01528460808d01528860a08d01528660c08d01528360e08d0152826101008d0152856101208d0152600301610d4790614096565b6101408c01526002810154600160401b81101561051d57806001610d7492016002840155600283016142c6565b611031578b51815560208c0151600182015560408c0151600282015560608c0151600382015560808c0151600482015560a08c0151600582015560c08c0151600682015560e08c01519b8c516001600160401b03811161051d5760209d610deb82610de26007870154613e20565b60078701613f43565b8e90601f8311600114610f8a576101006101407f4fb35642cffb9448ee528cc66ef68542b12b6484e83150ae9a5b1f080cac44c29f9d9b99969395610f269f9d9b989580610e5591610f4c9c996015975f92610f7f5750508160011b915f199060031b1c19161790565b60078601555b610e6b838201516008870161415f565b610120810151600c86015501518051600d8501556020810151600e8501556040810151600f850155606081015160108501556080810151601185015560a0810151601285015560c0810151601385015560e081015160148501550151910155610ed481546143ad565b90558b5f5260128d5260405f20336001600160601b0360a01b825416179055335f52600e8d5260405f20600160ff198254161790555196604051998a998d610160908c528f81908d01528b0190613ac4565b9260243560408b015260608a015260808901523360a089015287820360c0890152613ac4565b9360e08601526101008501526101208401526101408301520390a15f5f80516020614dca8339815191525d604051908152f35b015190505f806103d4565b90600785015f528f5f20915f5b601f198516811061101957506101407f4fb35642cffb9448ee528cc66ef68542b12b6484e83150ae9a5b1f080cac44c29f9d9b99969395610f269f9d9b989580610f4c9b9860159661010096600194601f19811610611001575b505050811b016007860155610e5b565b01515f1960f88460031b161c191690555f8080610ff1565b91926020600181928685015181550194019201610f97565b634e487b7160e01b5f525f60045260245ffd5b909b6110509082614358565b6001905f905b60443582106110995750509061108e61107461109393602435613fb8565b61108861108084614c07565b602435613fb8565b9061432d565b61433a565b95610cf0565b9091816110a591613fb8565b9183600182116110ba575b5060010190611056565b6110c7906001929461433a565b929050836110b0565b5060608301511515610c89565b50600383511015610c83565b6110f68160018901614146565b505460443514611109575b600101610c65565b9150600161112261111c84838a01614146565b5061400a565b929050611101565b93909498969592999761113e9b929b614302565b036112915750506003810154611155811515613f26565b600682015442101580611283575b61116c90613f26565b6024356008830154111580611273575b61118590613f26565b6111a4600a83015461119d602435600b860154614358565b1115613f26565b6111b060028601614271565b985f5b8a518110156112275760206101406111cb838e613fe2565b5101510151600460296040516866617374747261636b60b81b815260106009820152200154146111fd576001016111b3565b60405162461bcd60e51b8152602060048201526002602482015261194d60f21b6044820152606490fd5b50919395979990929496985060058401549660048501549394600b60296040516866617374747261636b60b81b815260106009820152200161126c6024358254614358565b9055610cf0565b506009820154602435111561117c565b506007820154421115611163565b92946002839597999b92989a9301546112ab811515613f26565b94610cf0565b506112ba6140fb565b8914610c57565b60405162461bcd60e51b8152602060048201526002602482015261653160f01b6044820152606490fd5b90508701518a610b45565b825f5260205f20905f5b601f1984168110611346575091600191610bb695949382601f1981161061132e575b5050811b019055610b5b565b8801515f1960f88460031b161c191690558980611322565b9091602060018192858b015181550193019101611300565b60206113989160405180938192630a85bd0160e11b83523360048401525f6024840152896044840152608060648401526084830190613ac4565b03815f335af15f9181611434575b506113ff573d156113f8573d6113bb81613c80565b906113c96040519283613c5f565b81523d5f602083013e5b805190816113f357604051633250574960e11b8152336004820152602490fd5b602001fd5b60606113d3565b6001600160e01b03191663757a42ff60e11b0161141c5785610af5565b604051633250574960e11b8152336004820152602490fd5b9091506020813d602011611471575b8161145060209383613c5f565b8101031261023557516001600160e01b0319811681036102355790876113a6565b3d9150611443565b6040516339e3563760e11b81525f6004820152602490fd5b5f86815260046020526040902080546001600160a01b0319169055805f52600360205260405f205f198154019055610a92565b604051633250574960e11b81525f6004820152602490fd5b50610a4160ff60405160208185516114f78183858a01613aa3565b810160148152030190205416159050610a38565b50611514614302565b8214610a32565b506115246142df565b8214610a2b565b506115346140fb565b8214610a24565b34610235575f366003190112610235576009546040516001600160a01b039091168152602090f35b346102355760403660031901126102355761157c613ae9565b6001600160401b03906024358281116102355761159d903690600401613cd1565b906115a6614552565b6001600160a01b03908116801561174a57604051906115c482613bd7565b600191828152602093848201918683526040810192848452845f526013875261160060405f2092511515839060ff801983541691151516179055565b858201905198895190811161051d5761161d81610b208454613e20565b87601f82116001146116bd5791611678826116a49b9a9998979695936002957fcebb02e73e402e0164947d10baf9c730c1f4764e714c7a999fec05b8004f93ed9e5f926116b25750508160011b915f199060031b1c19161790565b90555b019151166001600160601b0360a01b825416179055604051948594606086526060860190613ac4565b9284015260408301520390a1005b015190508e806103d4565b601f1982169a835f52895f209b5f5b8181106117355750927fcebb02e73e402e0164947d10baf9c730c1f4764e714c7a999fec05b8004f93ed9c600295938b9a9998979593836116a49f9e9d951061171d575b505050811b01905561167b565b01515f1960f88460031b161c191690558d8080611710565b838301518e559c8a019c928b01928b016116cc565b60405162461bcd60e51b8152602060048201526002602482015261065360f41b6044820152606490fd5b3461023557602036600319011261023557600435611791816143bb565b505f5260066020526117db6117b26117b960405f2060405192838092613e58565b0382613c5f565b5f6040516117c681613c0e565b52604051918291602083526020830190613ac4565b0390f35b34610235576080366003190112610235576117f8613ae9565b50611801613aff565b506064356001600160401b038111610235573660238201121561023557611832903690602481600401359101613c9b565b50613f88565b34610235576020366003190112610235575f80516020614dea83398151915260e0600435335f52601360205260ff60405f20541680156118ec575b61187c90613ee9565b6118846143f5565b61189a611893600c5483613fb8565b303361450d565b60405190815260a06020820152601060a08201526f10dbdb9d1c9858dd0819195c1bdcda5d60821b60c08201524260408201523360608201525f6080820152a15f5f80516020614dca8339815191525d005b506007546001600160a01b03163314611873565b3461023557602036600319011261023557600435335f52601360205260ff60405f205416801561194d575b61193490613ee9565b6103e88111156102355780602091600d55604051908152f35b506007546001600160a01b0316331461192b565b346102355760203660031901126102355761197a6143f5565b335f52601160205260405f206119a96119a060043561199b60028501614271565b6146df565b600283016142c6565b50600781016040516020810191815f8254926119c484613e20565b936001811690811561250157506001146124c2575b506119ed925003601f198101835282613c5f565b5190206119f8614124565b8103611f625750906005820154804210155f14611f4957611a1d62015180914261432d565b0480611f30575b5060038201545b6003611a486002850192835490611a43828211614326565b61432d565b93611a78611a5a866006840154613fb8565b95611a66871515614326565b611a71873330614421565b8454614358565b809355015414611ac0575b50611aaa5f80516020614dea83398151915291604051918291600435903390429085614365565b0390a15b5f5f80516020614dca8339815191525d005b5f805b600283015480821015611f2757611add82600286016142c6565b505460043514611af05750600101611ac3565b915091611b116001611b0585600285016142c6565b500154600c5490613fb8565b916004355f52601260205260018060a01b0360405f20541690611b3381613fcb565b90611b416040519283613c5f565b80825260208201600285015f5260205f205f915b838310611f095750505050611b6d90600435906146df565b506001600160a01b03611b81600435614cf5565b1615611ef05760019360028301545f19810190811161050957611baa611bb591600286016142c6565b5091600285016142c6565b91909161103157808203611dd4575b50506002820154928315611dc057611be25f198501600285016142c6565b949094611031575f85555f60018601555f60028601555f60038601555f60048601555f60058601555f600686015560078501611c1e8154613e20565b9081611d82575b5050611c456008860160035f918281558260018201558260028201550155565b5f600c8601555f600d8601555f6015600e96828882015582600f82015582601082015582601182015582601282015582601382015582601482015501555f190160028401558254908115610509575f80516020614dea8339815191529260e0925f19018555611cb5828230614421565b60096040519260a0908452806020850152830152684e46542076616c756560b81b60c083015242604083015260608201526004356080820152a15415611d3c575b505f80516020614daa83398151915260206040516004358152a15b15610235576004355f90815260126020526040902080546001600160a01b0319169055611aaa611a83565b60205f80516020614d8a833981519152916004355f526012825260018060a01b0360405f20541690815f52825260405f2060ff198154169055604051908152a182611cf6565b5f91601f808211600114611d9b575050555b8780611c25565b91611db984929382845260208420940160051c840160018501613f2d565b5555611d94565b634e487b7160e01b5f52603160045260245ffd5b80548255600181015460018301556002810154600283015560038101546003830155600481015460048301556005810154600583015560068101546006830155611e2460078201600784016145fc565b6008808301908201808203611eb2575b5050600c810154600c830155600d808301908201808203611e57575b5050611bc4565b549055600e8082015490830155600f8082015490830155601080820154908301556011810154601183015560128101546012830155601380820154908301556014808201549083015560158091015491015585808080611e50565b54905560098082015490830155600a8082015490830155611ee9600b60ff81840154169084019060ff801983541691151516179055565b8780611e34565b6024604051637e27328960e01b81526004356004820152fd5b60166020600192611f19856141d9565b815201920192019190611b55565b50509050611d11565b600a830154611f43916004359085614b9a565b82611a24565b5062278d00611f5c60048401544261432d565b04611a2b565b611f6a6140fb565b810361240457506005810154904282116123da57611fc5611fef9162015180611fa15f80516020614dea833981519152954261432d565b04806123c1575b50611fbf60016006830154920154600c5490613fb8565b90614358565b611fd0811515614326565b611fdb813330614421565b604051918291600435903390429085614365565b0390a15f905f5b6002820154808210156123b95761201082600285016142c6565b5054600435146120235750600101611ff6565b9092506120386001611b0585600286016142c6565b506004355f52601260205261204c81613fcb565b9061205a6040519283613c5f565b80825260208201600284015f5260205f205f915b83831061239b575050505061208690600435906146df565b506001600160a01b0361209a600435614cf5565b1615611ef05760019160028201545f198101908111610509576120c36120ce91600285016142c6565b5091600284016142c6565b9190916110315780820361227f575b50506002810154908115611dc0576120fb5f198301600283016142c6565b929092611031575f83555f60018401555f60028401555f60038401555f60048401555f60058401555f6006840155600783016121378154613e20565b9081612241575b505061215e6008840160035f918281558260018201558260028201550155565b5f600c8401555f600d8401555f6015600e94828682015582600f82015582601082015582601182015582601282015582601382015582601482015501555f1901600282015580548015610509575f1901809155156121fb575b505f80516020614daa83398151915260206040516004358152a15b15610235576004355f52601260205260405f206001600160601b0360a01b81541690555b611aae565b60205f80516020614d8a833981519152916004355f526012825260018060a01b0360405f20541690815f52825260405f2060ff198154169055604051908152a1816121b7565b5f91601f80821160011461225a575050555b848061213e565b9161227884929382845260208420940160051c840160018501613f2d565b5555612253565b805482556001810154600183015560028101546002830155600380820154908301556004810154600483015560058101546005830155600681015460068301556122cf60078201600784016145fc565b600880830190820180820361235d575b5050600c810154600c830155600d808301908201808203612302575b50506120dd565b549055600e8082015490830155600f80820154908301556010808201549083015560118101546011830155601281015460128301556013808201549083015560148082015490830155601580910154910155828080806122fb565b54905560098082015490830155600a8082015490830155612394600b60ff81840154169084019060ff801983541691151516179055565b84806122df565b601660206001926123ab856141d9565b81520192019201919061206e565b5050506121d2565b600a8201546123d4916004359084614b9a565b85611fa8565b60405162461bcd60e51b8152602060048201526002602482015261653360f01b6044820152606490fd5b90915061240f6142df565b81036124485750806201518061242c60046121f69401544261432d565b0490612439821515614326565b600c810154916004359161470b565b612450614302565b0361249857806201518061247c600f6121f694015461247181421015614326565b600e8401549061432d565b0490612489821515614326565b600d810154916004359161470b565b60405162461bcd60e51b8152602060048201526002602482015261329960f11b6044820152606490fd5b9150505f528160205f205f905b8382106124e757505060206119ed92820101876119d9565b6020919250806001915483858801015201910183916124cf565b60ff19168752506119ed9380151502830160200191508890506119d9565b3461023557604036600319011261023557612538613ae9565b602435612543614552565b80151590816125bc575b50806125aa575b1561023557600954604080516001600160a01b0393841680825293831660208201527fd3a304bcc272997906dfec1115aad56e609170fe73c0e9a2b2b36420dbbd9f699190a16001600160a01b03191617600955005b506001600160a01b0381161515612554565b6012915011158261254d565b34610235576020366003190112610235576117db6125e4613ae9565b6125ec614196565b5060018060a01b038091165f526011602052612629600260405f206040519361261485613bd7565b81548552600182015416602085015201614271565b6040820152604051918291602083526020830190613cef565b346102355760403660031901126102355761265b613ae9565b6024359081151590818303610235576001600160a01b03169182156126d3576126a590335f52600560205260405f20845f5260205260405f209060ff801983541691151516179055565b6040519081527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3160203392a3005b604051630b61174360e31b815260048101849052602490fd5b3461023557602036600319011261023557612705614552565b61270d6143f5565b6004355f52601260205260018060a01b0360405f2054165f52601160205260405f205f805b600283015480821015612b5e5761274c82600286016142c6565b50546004351461275f5750600101612732565b9150916127746001611b0585600285016142c6565b916004355f52601260205260018060a01b0360405f2054169061279681613fcb565b906127a46040519283613c5f565b80825260208201600285015f5260205f205f915b838310612b4057505050506127d090600435906146df565b506001600160a01b036127e4600435614cf5565b1615611ef05760019360028301545f19810190811161050957611baa61280d91600286016142c6565b91909161103157808203612a24575b50506002820154928315611dc05761283a5f198501600285016142c6565b949094611031575f85555f60018601555f60028601555f60038601555f600486015560055f818701555f6006870155600786016128778154613e20565b806129e4575b50505061289e6008860160035f918281558260018201558260028201550155565b5f600c8601555f600d8601555f6015600e96828882015582600f82015582601082015582601182015582601282015582601382015582601482015501555f190160028401558254908115610509575f80516020614dea8339815191529260e0925f1901855561290e828230614421565b60096040519260a0908452806020850152830152684e46542076616c756560b81b60c083015242604083015260608201526004356080820152a1541561299e575b505f80516020614daa83398151915260206040516004358152a15b15610235576004355f90815260126020526040812080546001600160a01b03191690555f80516020614dca8339815191525d005b60205f80516020614d8a833981519152916004355f526012825260018060a01b0360405f20541690815f52825260405f2060ff198154169055604051908152a18161294f565b5f92601f8083116001146129ff57505050555b86808061287d565b8391612a1d918694958552602085209501901c840160018501613f2d565b55556129f7565b80548255600181015460018301556002810154600283015560038082015490830155600481015460048301556005808201549083015560068082015490830155612a7460078083019084016145fc565b6008808301908201808203612b02575b5050600c810154600c830155600d808301908201808203612aa7575b505061281c565b549055600e8082015490830155600f8082015490830155601080820154908301556011810154601183015560128101546012830155601380820154908301556014808201549083015560158091015491015584808080612aa0565b54905560098082015490830155600a8082015490830155612b39600b60ff81840154169084019060ff801983541691151516179055565b8680612a84565b60166020600192612b50856141d9565b8152019201920191906127b8565b5050905061296a565b34610235575f366003190112610235576040515f60018260015492612b8b84613e20565b92838352602094856001821691825f14612c25575050600114612bca575b50612bb692500383613c5f565b6117db604051928284938452830190613ac4565b84915060015f527fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6905f915b858310612c0d575050612bb6935082010185612ba9565b80548389018501528794508693909201918101612bf6565b60ff191685820152612bb695151560051b8501019250879150612ba99050565b346102355760203660031901126102355760406001600160a01b0380612c69613ae9565b165f526011602052815f2090600182549201541682519182526020820152f35b34610235575f366003190112610235576007546040516001600160a01b039091168152602090f35b34610235576040366003190112610235576004356001600160401b03811161023557612ce1903690600401613cd1565b335f52601360205260ff60405f2054168015612d76575b612d0190613ee9565b612d0d81602435614566565b60405190600183519260208181870195612d28818389613aa3565b810160108152030190200154811015610235576001612d5a6020612d6a94600396604051938492839251928391613aa3565b8101601081520301902001614146565b5001805460ff19169055005b506007546001600160a01b03163314612cf8565b34610235575f366003190112610235576008546001600160a01b033381831603612df4576001600160601b0360a01b8092166008556007549133908316176007553391167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b60405163118cdaa760e01b8152336004820152602490fd5b3461023557602080600319360112610235576004356001600160401b038082116102355736602383011215610235578160040135908111610235576024820191602436918360051b01011161023557612e6481613fcb565b91612e726040519384613c5f565b818352612e7e82613fcb565b601f1901845f5b828110612f93575050505f5b828110612ef9575050506040519082820192808352815180945260408301938160408260051b8601019301915f955b828710612ecd5785850386f35b909192938280612ee9600193603f198a82030186528851613cef565b9601920196019592919092612ec0565b6001906001600160a01b0380612f18612f138488886141b5565b6141c5565b165f52600e875260ff60405f205416612f33575b5001612e91565b80612f42612f138488886141b5565b165f5260118752612f72600260405f2060405193612f5f85613bd7565b8154855286820154168a85015201614271565b6040820152612f818287613fe2565b52612f8c8186613fe2565b5086612f2c565b612f9b614196565b828288010152018590612e85565b34610235575f36600319011261023557612fc1614552565b600880546001600160a01b03199081169091556007805491821690555f906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b34610235576020366003190112610235576004355f526012602052602060018060a01b0360405f205416604051908152f35b34610235576020366003190112610235576001600160a01b03613061613ae9565b16801561307e575f526003602052602060405f2054604051908152f35b6040516322718ad960e21b81525f6004820152602490fd5b346102355760203660031901126102355760206130b46004356143bb565b6040516001600160a01b039091168152f35b34610235576080366003190112610235576001600160401b03600435818111610235576130f7903690600401613cd1565b906024359060443590606435335f526020926013845260ff60405f205416801561335c575b61312590613ee9565b6040518481018751916131428782818c0195610a02818789613aa3565b51902061314d6140fb565b811490811561334b575b5015610235578461319d918315158061333f575b80613334575b80613329575b80613320575b80613314575b61318c90613f26565b604051809381928b51928391613aa3565b8101601081520301902092865190811161051d576131c5816131bf8654613e20565b86613f43565b84601f82116001146132b15781906131f69394959697985f926132a65750508160011b915f199060031b1c19161790565b83555b600193928401925f8581815b61325e575b50501561321357005b6040519561322087613ba0565b86528501526040840152816060840152805490600160401b82101561051d5761324c9282018155614146565b9190916110315761325c9161415f565b005b86548110156132a157856132728289614146565b508a815414613286575b5050810181613205565b9092600292945086908201550155858080929050858a61327c565b61320a565b0151905088806103d4565b601f19821690855f52865f20915f5b8181106132fd57509883600195969798999a106132e5575b505050811b0183556131f9565b01515f1960f88460031b161c191690558780806132d8565b91928860018192868e0151815501940192016132c0565b506101f4851115613183565b5084151561317d565b506064881115613177565b506003881015613171565b5061070884111561316b565b9050613355614124565b1488613157565b506007546001600160a01b0316331461311c565b346102355761337e36613b15565b5050505f60405161338e81613c0e565b52613f88565b34610235575f36600319011261023557600f546133b081613fcb565b906133be6040519283613c5f565b8082526133ca81613fcb565b60209290601f1901835f5b8281106135ed575050506133e882613fcb565b916133f66040519384613c5f565b808352838301600f5f527f8d1108e10bcb7c27dddfc02ed9d693a074039d026cf4ea4240b40f7d581ac802855f925b8484106135c7575085855f5b82518110156134ce578061345f8561344b60019487613fe2565b518160405193828580945193849201613aa3565b810160108152030190206134ad60036040519261347b84613ba0565b60405161348c816117b28185613e58565b8452613499868201614041565b898501526002810154604085015201614096565b60608201526134bc8285613fe2565b526134c78184613fe2565b5001613431565b8184604051918183928301818452825180915260408401918060408360051b8701019401925f905b8382106135035786860387f35b919395509193603f19878203018252838651613529610180825190808652850190613ac4565b908281015191848103848601528380845192838152019301905f905b8082106135825750505090613570600194836040869501516040830152606080910151910190613b4a565b970192019201869594929391936134f6565b9195946080856135b760019496978a516060809180518452602081015160208501526040810151604085015201511515910152565b0196019201889495939291613545565b60019182916040516135dd816117b28189613e58565b8152019201920191908690613425565b6040516135f981613ba0565b606080825280848301525f60408301526040519061361682613bbb565b5f82525f858301525f60408301525f818301525f60808301525f60a08301525f60c08301525f60e08301525f6101008301528201528282860101520184906133d5565b34610235576020366003190112610235575f80516020614dea83398151915260e0600435335f52601360205260ff60405f2054168015613719575b61369d90613ee9565b6136a56143f5565b6136c66136b4600c5483613fb8565b6007546001600160a01b031630614421565b60405190815260a06020820152601160a082015270436f6e747261637420776974686472617760781b60c08201524260408201523360608201525f6080820152a15f5f80516020614dca8339815191525d005b506007546001600160a01b03163314613694565b346102355760203660031901126102355760206001600160a01b0380613751613ae9565b16805f526013835260ff60405f205416918215613775575b50506040519015158152f35b600754161490508280613769565b346102355761379136613b15565b505050613f88565b34610235576040366003190112610235576137b2613ae9565b6024356137be816143bb565b33151580613867575b8061383e575b613826576001600160a01b039283169282918491167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9255f80a45f90815260046020526040902080546001600160a01b0319169091179055005b60405163a9fbf51f60e01b8152336004820152602490fd5b5060018060a01b0381165f52600560205260405f20335f5260205260ff60405f205416156137cd565b506001600160a01b0381163314156137c7565b3461023557602036600319011261023557600435613897816143bb565b505f526004602052602060018060a01b0360405f205416604051908152f35b3461023557602036600319011261023557600435335f52601360205260ff60405f2054168015613963575b6138ea90613ee9565b80151580613958575b6138fc90613f26565b6002604051601060286766726565666c6f7760c01b9283815282600882015220916139278354613e20565b601f8111613938575b500181550155005b61395290845f52601f60205f20910160051c810190613f2d565b85613930565b506102bc81106138f3565b506007546001600160a01b031633146138e1565b34610235575f366003190112610235576040515f8054908261399883613e20565b91828252602093600190856001821691825f14612c255750506001146139c55750612bb692500383613c5f565b5f808052859250907f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5635b858310613a06575050612bb6935082010185612ba9565b805483890185015287945086939092019181016139ef565b34610235576020366003190112610235576004359063ffffffff60e01b821680920361023557602091632483248360e11b8114908115613a60575b5015158152f35b6380ac58cd60e01b811491508115613a92575b8115613a81575b5083613a59565b6301ffc9a760e01b14905083613a7a565b635b5e139f60e01b81149150613a73565b5f5b838110613ab45750505f910152565b8181015183820152602001613aa5565b90602091613add81518092818552858086019101613aa3565b601f01601f1916010190565b600435906001600160a01b038216820361023557565b602435906001600160a01b038216820361023557565b6060906003190112610235576001600160a01b0390600435828116810361023557916024359081168103610235579060443590565b805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e083015261010080910151910152565b608081019081106001600160401b0382111761051d57604052565b61012081019081106001600160401b0382111761051d57604052565b606081019081106001600160401b0382111761051d57604052565b61016081019081106001600160401b0382111761051d57604052565b602081019081106001600160401b0382111761051d57604052565b604081019081106001600160401b0382111761051d57604052565b60a081019081106001600160401b0382111761051d57604052565b90601f801991011681019081106001600160401b0382111761051d57604052565b6001600160401b03811161051d57601f01601f191660200190565b929192613ca782613c80565b91613cb56040519384613c5f565b829481845281830111610235578281602093845f960137010152565b9080601f8301121561023557816020613cec93359101613c9b565b90565b9060609060608101908351815260209060018060a01b038286015116828201526040809501519460606040830152855180945260809460808301918460808760051b8601019801965f945b878610613d4d5750505050505050505090565b9091929394959697988780600192607f19858203018952613e0d8d51916101a0610140613dc36102c08651855287870151888601528c8701518d8601528d80880151908601528b8701518c86015260a0808801519086015260c0808801519086015260e090808289015192870152850190613ac4565b94613df761010080830151908601906060809180518452602081015160208501526040810151604085015201511515910152565b6101208101516101808501520151910190613b4a565b9b01960196019497969593929190613d3a565b90600182811c92168015613e4e575b6020831014613e3a57565b634e487b7160e01b5f52602260045260245ffd5b91607f1691613e2f565b80545f9392613e6682613e20565b918282526020936001916001811690815f14613eca5750600114613e8c575b5050505050565b90939495505f92919252835f2092845f945b838610613eb657505050500101905f80808080613e85565b805485870183015294019385908201613e9e565b60ff19168685015250505090151560051b010191505f80808080613e85565b15613ef057565b60405162461bcd60e51b815260206004820152600e60248201526d24b73b30b634b21031b0b63632b960911b6044820152606490fd5b1561249857565b818110613f38575050565b5f8155600101613f2d565b9190601f8111613f5257505050565b613f7c925f5260205f20906020601f840160051c83019310613f7e575b601f0160051c0190613f2d565b565b9091508190613f6f565b60405162461bcd60e51b8152602060048201526008602482015267111a5cd8589b195960c21b6044820152606490fd5b8181029291811591840414171561050957565b6001600160401b03811161051d5760051b60200190565b8051821015613ff65760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b9060405161401781613ba0565b606060ff600383958054855260018101546020860152600281015460408601520154161515910152565b90815461404d81613fcb565b9261405b6040519485613c5f565b8184525f90815260208082208186015b848410614079575050505050565b6004836001926140888561400a565b81520192019301929061406b565b906040516140a381613bbb565b610100600882948054845260018101546020850152600281015460408501526003810154606085015260048101546080850152600581015460a0850152600681015460c0850152600781015460e08501520154910152565b60405160208101906718dbdb5c1bdd5b9960c21b82526008815261411e81613c29565b51902090565b6040516020810190666d6f6e74686c7960c81b82526007815261411e81613c29565b8054821015613ff6575f5260205f209060021b01905f90565b60036060613f7c938051845560208101516001850155604081015160028501550151151591019060ff801983541691151516179055565b604051906141a382613bd7565b60606040835f81525f60208201520152565b9190811015613ff65760051b0190565b356001600160a01b03811681036102355790565b906040516141e681613bf2565b61014061426c600d83958054855260018101546020860152600281015460408601526003810154606086015260048101546080860152600581015460a0860152600681015460c0860152604051614244816117b28160078601613e58565b60e08601526142556008820161400a565b610100860152600c81015461012086015201614096565b910152565b90815461427d81613fcb565b9261428b6040519485613c5f565b8184525f90815260208082208186015b8484106142a9575050505050565b6016836001926142b8856141d9565b81520192019301929061429b565b8054821015613ff6575f52601660205f20910201905f90565b60405160208101906766726565666c6f7760c01b82526008815261411e81613c29565b60405160208101906866617374747261636b60b81b82526009815261411e81613c29565b156123da57565b9190820391821161050957565b8115614344570490565b634e487b7160e01b5f52601260045260245ffd5b9190820180921161050957565b9092608092959493825260a06020830152600c60a08301526b52657761726420636c61696d60a01b60c083015260e0820195604083015260018060a01b031660608201520152565b5f1981146105095760010190565b5f818152600260205260409020546001600160a01b03169081156143dd575090565b60249060405190637e27328960e01b82526004820152fd5b5f80516020614dca833981519152805c61440f576001905d565b604051633ee5aeb560e01b8152600490fd5b90613f7c9260018060a01b03806009541693604051602081019560205f8563095ea7b360e01b95868b5216988960248601528760448601526044855261446685613ba0565b84519082855af15f513d826144f1575b5050156144ba575b505050806009541692604051946323b872dd60e01b602087015260248601521660448401526064830152606482526144b582613c44565b614c90565b6144b56144e9936040519060208201528860248201525f6044820152604481526144e381613ba0565b82614c90565b5f808061447e565b9091506145055750803b15155b5f80614476565b6001146144fe565b6009546040516323b872dd60e01b60208201526001600160a01b0392831660248201529282166044840152606480840194909452928252613f7c92166144b582613c44565b6007546001600160a01b03163303612df457565b9091602061457d6040519485815193849201613aa3565b8301916010835261459a6001856020829788970301902001614041565b5f945b6145cb5760405162461bcd60e51b8152602060048201526002602482015261329960f11b6044820152606490fd5b80518510156145f757816145df8683613fe2565b5151146145f057838095019461459d565b5090915050565b612498565b908082146146db5761460e8154613e20565b906001600160401b03821161051d576146318261462b8554613e20565b85613f43565b5f90601f831160011461466d5761465e92915f91836146625750508160011b915f199060031b1c19161790565b9055565b015490505f806103d4565b90601f198316915f5260209160205f2090855f5260205f20935f905b8282106146c25750509084600195949392106146aa575b505050811b019055565b01545f1960f88460031b161c191690555f80806146a0565b8495819295850154815560018091019601940190614689565b5050565b905f5b825181101561249857816146f68285613fe2565b515114614705576001016146e2565b91505090565b92614746906237b1d061473f600c9461473a600c5461473a6001809b0154936147348584613fb8565b97613fb8565b613fb8565b0490614358565b90614752821515614326565b61475d823330614421565b335f52601190602091808352604095865f209260029060028501915f94845f905b6147cf575b505050505050905015610235575f80516020614dea8339815191529360126147ca92855f5252805f206001600160601b0360a01b8154169055519283923390429085614365565b0390a1565b845480821015614b94578b6147e483886142c6565b5054146147f4575085018561477e565b96509193969294906148158261480a858b6142c6565b500154875490613fb8565b508a5f528b8b601298898c5261483661482d82613fcb565b93519384613c5f565b8083525f8b81528c8120868e8087015b858510614b6f5750505050505061485c916146df565b506001600160a01b0394856148708d614cf5565b1615614b575782988054945f1995868101908111614b445761489561489d91846142c6565b5091836142c6565b91909161103157808203614a32575b505080548015611dc0578501916148c383836142c6565b999099611031575f8092818c5581888d01558b01558160038b01558c60049683888d01558b8460066005928284820155015560078d01916149048354613e20565b91826149ee575b505050505061492e60088b0160035f918281558260018201558260028201550155565b8901555f600d8901555f6015600e99828b82015582600f8201558260108201558286820155828c82015582601382015582601482015501555583549182156149de575050019081905585929190156149a5575b50505f80516020614daa83398151915291508651868152a1805f8080808080614783565b5f80516020614d8a83398151915293885f528352885f20541690815f528252875f2060ff1981541690558751908152a15f828180614981565b634e487b7160e01b5f525260245ffd5b8694601f90818511600114614a0e575050505050555b8c5f80808061490b565b91859391614a2b93889697875286209601901c8501908501613f2d565b5555614a04565b805482558581015486830155838101548483015560038082015490830155600480820154908301556005808201549083015560068082015490830155614a7e60078083019084016145fc565b6008808301908201808203614b06575b5050898101548a830155600d808301908201808203614aaf575b50506148ac565b549055600e8082015490830155600f80820154908301556010808201549083015584810154858301558a8101548b83015560138082015490830155601480820154908301556015809101549101555f808080614aa8565b54905560098082015490830155600a8082015490830155614b3d600b60ff81840154169084019060ff801983541691151516179055565b5f80614a8e565b84634e487b7160e01b5f5260045260245ffd5b8c51637e27328960e01b8152600481018d9052602490fd5b8394959650614b80601693946141d9565b8152019201920190918f93928e8891614846565b50614783565b6110886001614bd85f80516020614dea833981519152966237b1d061473f614bde9761473a61473a98600c549788910154998a936147348584613fb8565b92613fb8565b614be9811515614326565b614bf4813330614421565b6147ca6040519283923390429085614365565b8015614c8b578080600114614c8457600214614c7e576001908161013382101682600b83101617614c7657906002815b808211614c4e575050815f19048111610509570290565b9092805f1904811161050957818416614c6d575b800292811c90614c37565b80920291614c62565b600291500a90565b50600490565b5050600190565b505f90565b905f602091828151910182855af115614cea575f513d614ce157506001600160a01b0381163b155b614cbf5750565b604051635274afe760e01b81526001600160a01b039091166004820152602490fd5b60011415614cb8565b6040513d5f823e3d90fd5b5f818152600260205260409020546001600160a01b03169081614d56575b5f81815260026020526040812080546001600160a01b0319169055827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8280a490565b5f81815260046020526040902080546001600160a01b0319169055815f52600360205260405f205f198154019055614d1356fee93c8c37870a27cc5ee6ed71634b6eb1ded9a7c274bcd716e8f41d5fa5c1ec8349e4a47f54415e1ec96736a0c2a04f34ae0e8907770b365365c8d0e3a813f8b09b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00e720d61db15941cd5b3c730f4884a87b12c154902075bc4c1f7fc929c7378a4ea164736f6c6343000818000a

Verified Source Code Partial Match

Compiler: v0.8.24+commit.e11b9ed9 EVM: cancun Optimization: Yes (200 runs)
SPENFT.sol 765 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";

/** 
@title SPENFT
@notice ERC721 contract for minting and staking NFTs
*/
contract SPENFT is ERC721URIStorage, Ownable2Step, ReentrancyGuardTransient {
  using SafeERC20 for IERC20;
  IERC20 public rewardsToken;
  uint private _tokenIds;

  /// @notice standard USDT decimals(change allowed)
  uint DECIMALS = 6;
  uint BASE = 10 ** DECIMALS;
  uint8 constant private PERCENTAGE_DECIMALS = 4;
  uint constant private PERCENTAGE_BASE = 10 ** PERCENTAGE_DECIMALS;
  uint16 constant private daysInYear = 365;
  uint8 constant private monthsInYear = 12;
  /// @notice max addresses array length allowed fot getAllStakers function
  uint private maxStakedToken = 50000;

  /// @notice plan names converted to bytes
  bytes32 constant private monthlyBytes = keccak256(abi.encodePacked("monthly"));
  bytes32 constant private compoundBytes = keccak256(abi.encodePacked("compound"));
  bytes32 constant private freeflowBytes = keccak256(abi.encodePacked("freeflow"));
  bytes32 constant private fasttrackBytes = keccak256(abi.encodePacked("fasttrack"));
  
  mapping(address => bool) isStaker;
  /// @notice plan names string
  string[] private planNames = ["compound", "monthly", "freeflow", "fasttrack"];

  /// @notice all active staking plans
  mapping(string => StakingPlan) private stakingPlans;

  /// @notice all stakers storage
  mapping(address => Staker) public stakers;
  /// @notice NFT ID to staker address
  mapping(uint => address) public tokenIdToStaker;

  /// @notice all admins storage
  mapping(address => Admin) private admins;

  /// @notice all used NFT URIs storage
  mapping(string => bool) private _usedTokenURIs;

  /** 
  @title Staker info
  @notice Stores information about staker and staked tokens
  */
  struct Staker {
    uint stakedCount;
    address account;
    StakedToken[] stakedTokens;
  }

  /** 
  @title Staked toke info
  @notice Stores information about staked NFT and selected plan configuration
  */
  struct StakedToken {
    uint stakedTokenId;
    uint price;
    uint claimedRewards;
    uint totalRewards;
    uint startDate;
    uint endDate;
    uint tokensPerReward;
    string planName;
    Period period;
    uint percentage;
    FTConfig FTConfig;
  }

  /** 
  @title Staking period
  @notice Stores information about staking period
  */
  struct Period {
    uint month;
    uint percentage;
    uint extraDaysPercentage;
    bool isActive;
  }

  /** 
  @title FastTrack configuration
  @notice Stores information about active FastTrack configuration
  */
  struct FTConfig {
    uint percentage;
    uint startDate;
    uint endDate;
    uint saleStartDate;
    uint saleEndDate;
    uint userMin;
    uint userMax;
    uint targetAmount;
    uint fundraised;
  }

  /** 
  @title Staking Plan
  @notice Stores full information about staking plan configuration
  */
  struct StakingPlan {
    string name;
    Period[] periods;
    uint percentage;
    FTConfig FTConfig;
  }

  /** 
  @title Admin
  @notice Stores information about contract administrators
  */
  struct Admin {
    bool isActive;
    string name;
    address account;
  }

  /// @notice Emits when ERC-20 transfers
  /// @param amount transaction amount
  /// @param action name of action Claim/Deposit/Contract Deposit
  /// @param date transaction date
  /// @param user user address
  /// @param tokenId related to transaction NFT ID
  event Transaction (
    uint amount, string action, uint date, address user, uint tokenId
  );
  
  /// @notice Emits when new NFT staked
  /// @param tokenId NFT ID
  /// @param tokenURI NFT Json URI
  /// @param amount NFT price
  /// @param date date of staking start
  /// @param endDate date of staking end
  /// @param user user address  
  /// @param interest type of staking plan 
  /// @param month staking plan duration
  /// @param percentage staking plan percentage
  /// @param tokensPerReward tokens per reward amount
  /// @param extraDaysPercentage staking plan percentage for extra holding days
  event TokenStaked (
    uint tokenId,
    string tokenURI,
    uint amount,
    uint date,
    uint endDate,
    address user,
    string interest,
    uint month,
    uint percentage,
    uint tokensPerReward,
    uint extraDaysPercentage
  );

  /// @notice Emits when rewards token change
  /// @param newToken new token address
  /// @param oldToken old token address
  event RewardsTokenChange (
    address newToken,
    address oldToken
  );

  /// @notice Emits when staked token removed
  /// @param tokenId NFT ID
  event StakedTokenRemoved (
    uint tokenId
  );

  /// @notice Emits when staker has no active staking plans
  /// @param staker staker address
  event StakerPlansFinished (
    address staker
  );
  
  /// @notice Emits when we activate or disable admin
  /// @param name staker address
  /// @param account admin address
  /// @param isActive admin status
  event AdminChange (
    string name,
    address account,
    bool isActive
  );

  modifier onlyAdmin() {
    require(admins[msg.sender].isActive || owner() == msg.sender, "Invalid caller");
    _;
  }

  constructor(address _rewardsToken) ERC721("Stage Point NFT", "SPENFT") Ownable(msg.sender) {
    require(_rewardsToken != address(0), "e0");
    rewardsToken = IERC20(_rewardsToken);
  }

  /// @notice Checks if NFT URI exists
  /// @param tokenURI NFT URI
  function tokenURIExists(string memory tokenURI) private view returns (bool) {
    return _usedTokenURIs[tokenURI];
  }

  /// @notice Stakes new NFT
  /// @param tokenURI NFT URI
  /// @param _tokenId NFT ID
  /// @param price NFT price
  /// @param depositTerm staking plan duration(monthly/compound)
  /// @param interest staking plan name
  /// @param interestBytes encoded staking plan name
  function stakeToken(
    string memory tokenURI,
    uint _tokenId,
    uint price,
    uint depositTerm,
    string memory interest,
    bytes32 interestBytes
  ) private returns (bool) {
    require(ownerOf(_tokenId) == msg.sender);

    Staker storage staker = stakers[msg.sender];
    require(staker.stakedCount < maxStakedToken, "e1");
    staker.account = msg.sender;
    StakingPlan storage plan = stakingPlans[interest];
    uint rewardsCount = 0;
    uint endDate = 0;
    uint startDate = block.timestamp;
    uint tokensPerReward = 0;
    uint planPercentage = 0;
    uint extraDaysPercentage = 0;
    uint monthlyInterestRate = 0;
    Period memory period = Period(0, 0, 0, false);

    if (interestBytes == monthlyBytes || interestBytes == compoundBytes) {
      for (uint i = 0; i < plan.periods.length; i++) {
        if (plan.periods[i].month == depositTerm) {
          period = plan.periods[i];
        }
      }
      extraDaysPercentage = period.extraDaysPercentage;
      planPercentage = period.percentage;

      require(planPercentage > 0 && period.month >= 3 && period.isActive, "e2");

      monthlyInterestRate = (planPercentage * BASE) / monthsInYear / PERCENTAGE_BASE;

      endDate = endDate + depositTerm * 30 days;

      if (interestBytes == monthlyBytes) {
        rewardsCount = depositTerm;
        tokensPerReward = price * monthlyInterestRate;
      } else {
        uint monthlyRate = BASE + monthlyInterestRate;
        uint compounded = 1;

        for (uint i = 0; i < depositTerm; i++){
          compounded *= monthlyRate;
          if (i > 1) {
            compounded = compounded / BASE;
          }
        }

        tokensPerReward = ((price * compounded) - (price * (BASE ** 2))) / BASE;
      }
    } else if (interestBytes == fasttrackBytes) {
      require(plan.FTConfig.percentage > 0, "e2");
      require(block.timestamp >= plan.FTConfig.saleStartDate  && block.timestamp <= plan.FTConfig.saleEndDate, "e2");
      require(plan.FTConfig.userMin <= price && price <= plan.FTConfig.userMax, "e2");
      require(plan.FTConfig.targetAmount >= plan.FTConfig.fundraised + price, "e2");
      checkActiveFT(staker.stakedTokens);
      endDate = plan.FTConfig.endDate;
      startDate = plan.FTConfig.startDate;
      planPercentage = plan.FTConfig.percentage;
      stakingPlans['fasttrack'].FTConfig.fundraised += price;
    } else {
      require(plan.percentage > 0, "e2");
      planPercentage = plan.percentage;
    }

    staker.stakedTokens.push(StakedToken(
      _tokenId,
      price,
      0,
      rewardsCount,
      startDate,
      endDate,
      tokensPerReward,
      interest,
      period,
      planPercentage,
      plan.FTConfig
    ));

    staker.stakedCount++;

    tokenIdToStaker[_tokenId] = msg.sender;
    addStakerAddress();

    emit TokenStaked(
      _tokenId,
      tokenURI,
      price,
      startDate,
      endDate,
      msg.sender,
      interest,
      period.month,
      planPercentage,
      tokensPerReward,
      extraDaysPercentage
    );

    return true;
  }

  /// @notice Mints new NFT and stakes it
  /// @param tokenURI NFT URI
  /// @param price NFT price
  /// @param depositTerm staking plan duration(monthly/compound)
  /// @param interest staking plan name
  function mintToken(
    string memory tokenURI,
    uint price,
    uint depositTerm,
    string memory interest
  ) external nonReentrant returns (uint) {
    bytes32 interestBytes = keccak256(abi.encodePacked(interest));

    require(
      (interestBytes == monthlyBytes ||
      interestBytes == compoundBytes ||
      interestBytes == freeflowBytes ||
      interestBytes == fasttrackBytes) && 
      !tokenURIExists(tokenURI),
      "e2"
    );
    uint decimalsPrice = price * BASE;

    _tokenIds ++;

    uint newTokenId = _tokenIds;
    _safeMint(msg.sender, newTokenId);
    _setTokenURI(newTokenId, tokenURI);
    _usedTokenURIs[tokenURI] = true;


    transferUSDT(msg.sender, address(this), decimalsPrice, false);
    require(stakeToken(tokenURI, newTokenId, price, depositTerm, interest, interestBytes));
    return newTokenId;
  }

  /// @notice Disables NFT transfer
  function transferFrom(address, address, uint) public virtual override (ERC721, IERC721) {
    revert("Disabled");
  }

  /// @notice Disables NFT transfer
  function safeTransferFrom(address, address, uint, bytes memory) public virtual override (ERC721, IERC721) {
    revert("Disabled");
  }

  /// @notice Transfer ERC-20 rewards tokens
  /// @param from tokens owner
  /// @param _to tokens spender
  /// @param _amount transfer amount(multiplied by BASE)
  /// @param allow if we transfer from contract we need to allow transfer(need to be passed as true)
  function transferUSDT(address from, address _to, uint _amount, bool allow) internal {
    if (allow) {
      rewardsToken.forceApprove(from, _amount);
    }
    rewardsToken.safeTransferFrom(from, _to, _amount);
  }

  /// @notice Create new FreeFlow plan or prepare new update
  /// @param percentage new FreeFlow plan percentage
  function createFreeFlowPlan(uint percentage) external onlyAdmin {
    require(percentage > 0 && percentage < 700, "e2");
    StakingPlan storage stakingPlan = stakingPlans["freeflow"];
    stakingPlan.name = "freeflow";
    stakingPlan.percentage = percentage;
  }

  /// @notice Create new standard plan(Monthly/Compound)
  /// @param variant plan type(compound/monthly)
  /// @param month plan duration
  /// @param percentage plan percentage
  /// @param extraDaysPercentage plan percentage for extra days holding
  function createStandardPlan(
    string memory variant, uint month, uint percentage, uint extraDaysPercentage
  ) external onlyAdmin {
    bytes32 variantBytes = keccak256(abi.encodePacked(variant));
    require(variantBytes == compoundBytes || variantBytes == monthlyBytes);
    require(percentage > 0 && percentage <= 1800 && month >= 3 && month <= 100 && extraDaysPercentage > 0 && extraDaysPercentage <= 500, "e2");

    StakingPlan storage plan = stakingPlans[variant];
    plan.name = variant;
    bool updateFlag = false;
    
    for (uint i = 0; i < plan.periods.length; i++) {
      Period storage period = plan.periods[i];
      if (period.month == month) {
        period.percentage = percentage;
        period.extraDaysPercentage = extraDaysPercentage;
        updateFlag = true;
      }
    }

    if (!updateFlag) {
      plan.periods.push(Period(month, percentage, extraDaysPercentage, true));
    }
  }

  /// @notice Create new FastTrack plan
  /// @dev If we have active active FastTrack plan we need to disable it at first
  /// @param percentage plan percentage
  /// @param startDate staking start date
  /// @param endDate staking end date
  /// @param saleStartDate sale start date
  /// @param saleEndDate sale end date
  /// @param userMin minimal NFT price
  /// @param userMax maximum NFT price
  /// @param targetAmount plan target amount
  function createFastTrackPlan(
    uint percentage, uint startDate, uint endDate, uint saleStartDate, uint saleEndDate, uint userMin, uint userMax, uint targetAmount
  ) external onlyAdmin {
    require(percentage > 0 && percentage < 15000, "e2");
    Period[] memory periods = new Period[](0);
    StakingPlan storage planData = stakingPlans["fasttrack"];
    require(block.timestamp >= planData.FTConfig.saleEndDate || planData.FTConfig.percentage == 0, "e2");
    require(saleStartDate >= block.timestamp, "e2");
    require(startDate >= saleEndDate && saleEndDate >= saleStartDate, "e2");
    stakingPlans["fasttrack"] = StakingPlan(
      "fasttrack",
      periods,
      percentage,
      FTConfig(
        percentage,
        startDate,
        endDate,
        saleStartDate,
        saleEndDate,
        userMin,
        userMax,
        targetAmount,
        0
      )
    );
  }

  /// @notice Get all staking plans
  /// @return StakingPlan information about staking plans
  function getStakingPlans() external view returns (StakingPlan[] memory) {
    StakingPlan[] memory plans = new StakingPlan[](planNames.length);
    string[] memory names = planNames;

    for (uint i = 0; i < names.length; i++) {
      plans[i] = stakingPlans[names[i]];
    }

    return plans;
  }

  /// @notice Deactivate staking plan(FreeFlow/FastTrack)
  /// @param name plan name(freeflow/fasttrack)
  function deactivateStakingPlan(string memory name) external onlyAdmin {
    Period[] memory periods = new Period[](0);
    stakingPlans[name] = StakingPlan(
      name,
      periods,
      0,
      FTConfig(0, 0, 0, 0, 0, 0, 0, 0, 0)
    );
  }

  /// @notice Deactivate staking plan(Compound/Monthly)
  /// @param name plan name(compound/monthly)
  function deactivateStandardPlan(string memory name, uint month) external onlyAdmin {
    uint index = findPlanIndex(month, name);
    require(index < stakingPlans[name].periods.length);
    stakingPlans[name].periods[index].isActive = false;
  }

  /// @notice Claim staking rewards
  /// @dev If user staking plan has available rewards we count and pay extra days profit, transfer rewards and then if needed we burn user NFT
  /// @param _tokenId staked NFT
  function claimReward(uint _tokenId) external nonReentrant {
    Staker storage staker = stakers[msg.sender];
    uint tokenArrayId = checkTokenStaked(staker.stakedTokens, _tokenId);
    StakedToken storage tokenInfo = staker.stakedTokens[tokenArrayId];
    uint _amount = 0;
    bytes32 interestBytes = keccak256(abi.encodePacked(tokenInfo.planName));

    if (interestBytes == monthlyBytes) {
      uint rewardsCounter = 0;
      if (block.timestamp >= tokenInfo.endDate) {
        uint extraDaysCount = (block.timestamp - tokenInfo.endDate) / 1 days;
        if (extraDaysCount > 0) {
          paySimpleInterest(tokenInfo, extraDaysCount, _tokenId, tokenInfo.period.extraDaysPercentage, false, true);
        }
        rewardsCounter = tokenInfo.totalRewards;
      } else {
        rewardsCounter = (block.timestamp - tokenInfo.startDate) / 30 days;
      }

      require(rewardsCounter > tokenInfo.claimedRewards, "e3");
      uint unclaimedRewards = rewardsCounter - tokenInfo.claimedRewards;

      _amount = tokenInfo.tokensPerReward * unclaimedRewards;

      require(_amount > 0, "e3");

      transferUSDT(address(this), msg.sender, _amount, true);

      tokenInfo.claimedRewards = tokenInfo.claimedRewards + unclaimedRewards;

      if (tokenInfo.totalRewards == tokenInfo.claimedRewards) {
        removeStakedToken(staker, _tokenId, true);
      }
      emit Transaction(_amount, "Reward claim", block.timestamp, msg.sender, _tokenId);
    } else if (interestBytes == compoundBytes) {
      if (block.timestamp >= tokenInfo.endDate) {
        uint extraDaysCount = (block.timestamp - tokenInfo.endDate) / 1 days;
        if (extraDaysCount > 0) {
          paySimpleInterest(tokenInfo, extraDaysCount, _tokenId, tokenInfo.period.extraDaysPercentage, false, true);
        }
      } else {
        revert("e3");
      }
      _amount = tokenInfo.tokensPerReward + tokenInfo.price * BASE;
      require(_amount > 0, "e3");
      transferUSDT(address(this), msg.sender, _amount, true);
      emit Transaction(_amount, "Reward claim", block.timestamp, msg.sender, _tokenId);
      removeStakedToken(staker, _tokenId, false);
    } else if (interestBytes == freeflowBytes) {
      uint daysCount = (block.timestamp - tokenInfo.startDate) / 1 days;
      require(daysCount > 0, "e3");
      paySimpleInterest(tokenInfo, daysCount, _tokenId, tokenInfo.percentage, true, false);
    } else if (interestBytes == fasttrackBytes) {
      require(block.timestamp >= tokenInfo.FTConfig.endDate, "e3");
      uint daysCount = (tokenInfo.FTConfig.endDate - tokenInfo.FTConfig.startDate) / 1 days;
      require(daysCount > 0, "e3");
      paySimpleInterest(tokenInfo, daysCount, _tokenId, tokenInfo.FTConfig.percentage , true, false);
    } else {
      revert("e2");
    }
  }

  /// @notice Calculate and pay plan simple interest
  /// @dev used to calculate and pay simple interest rewards. For full NFT price(FreeFlow/FastTrack) and only for extra rewards(Compound/Monthly)
  /// @param tokenInfo information about staked NFT
  /// @param daysCount staking duration days count
  /// @param _tokenId NFT ID
  /// @param percentage staking plan percentage
  /// @param needToBurn if token need to be burned after rewards transfer(FreeFlow/FastTrack we close staking plan)
  /// @param isExtra if payment type is extra days reward
  function paySimpleInterest(
    StakedToken storage tokenInfo,
    uint daysCount,
    uint _tokenId,
    uint percentage,
    bool needToBurn,
    bool isExtra
  ) private {
    uint _amount = ( BASE *  tokenInfo.price ) + (percentage * daysCount * BASE) * tokenInfo.price / (daysInYear * PERCENTAGE_BASE);

    if (isExtra) {
      _amount -= tokenInfo.price * BASE;
    }

    require(_amount > 0, "e3");

    transferUSDT(address(this), msg.sender, _amount, true);
    if (needToBurn) {
      removeStakedToken(stakers[msg.sender], _tokenId, false);
    }
    emit Transaction(_amount, "Reward claim", block.timestamp, msg.sender, _tokenId);
  }

  /// @notice Close staking plan and burn NFT
  /// @param staker information about staker
  /// @param _tokenId staked NFT ID
  /// @param needToTransfer we can transfer initial NFT price
  function removeStakedToken(Staker storage staker, uint _tokenId, bool needToTransfer) private {
    StakedToken[] storage stakedTokens = staker.stakedTokens;
    bool removedFlag = false;
    for (uint i = 0; i < stakedTokens.length; i++) {
      if (stakedTokens[i].stakedTokenId == _tokenId) {
        uint tokenPrice = stakedTokens[i].price * BASE;
        address tokenOwner = tokenIdToStaker[_tokenId];
  
        burnToken(stakedTokens, _tokenId);
        removedFlag = true;
        stakedTokens[i] = stakedTokens[stakedTokens.length - 1];
        stakedTokens.pop();
        staker.stakedCount--;
        if (needToTransfer) {
          transferUSDT(address(this), tokenOwner, tokenPrice, true);
          emit Transaction(tokenPrice, "NFT value", block.timestamp, tokenOwner, _tokenId);
        }
        if (staker.stakedCount == 0) {
          removeStakerAddress(tokenIdToStaker[_tokenId]);
        }
        emit StakedTokenRemoved(_tokenId);
        break;
      }
    }
    require(removedFlag);
    tokenIdToStaker[_tokenId] = address(0);
  }

  /// @notice Find Plan period info
  /// @param _item plan duration
  /// @param variant staking plan name(compound/monthly)
  function findPlanIndex(uint _item, string memory variant) private view returns (uint) {
    Period[] memory periods = stakingPlans[variant].periods;
    for (uint i = 0; i < periods.length; i++) {
      if (periods[i].month == _item) {
        return i;
      }
    }
    revert("e2");
  }

  /// @notice Add new administrator
  /// @param account administrator address
  /// @param adminName administrator name
  function addAdmin(address account, string memory adminName) external onlyOwner {
    require(account != address(0), "e0");
    admins[account] = Admin({ isActive: true, name: adminName, account: account });
    emit AdminChange(adminName, account, true);
  }

  /// @notice Deactivate administrator
  /// @param account administrator address
  function deactivateAdmin(address account) external onlyOwner {
    Admin storage admin = admins[account];
    admin.isActive = false;
    emit AdminChange(admin.name, account, false);
  }

  /// @notice Check admin
  /// @param account user address
  function isAdmin(address account) external view returns(bool) {
    return admins[account].isActive || owner() == account;
  }

  /// @notice Add staker address
  /// @dev we mark staker as active till he has active staked NFT
  function addStakerAddress() private {
    isStaker[msg.sender] = true;
  }

  /// @notice Remove staker address
  /// @dev we mark staker as inactive when all plans finished
  function removeStakerAddress(address staker) private {
    isStaker[staker] = false;
    emit StakerPlansFinished(staker);
  }

  /// @notice Get info about stakers
  /// @dev added stakersAddresses length limit
  function getAllStakers(address[] calldata stakersAddresses) external view returns (Staker[] memory) {
    Staker[] memory allStakers = new Staker[](stakersAddresses.length);

    for (uint i = 0; i < stakersAddresses.length; i++) {
      if (isStaker[stakersAddresses[i]]) {
        Staker memory staker = stakers[stakersAddresses[i]];
        allStakers[i] = staker;
      }
    }

    return allStakers;
  }

  /// @notice Get info about staker
  /// @param user staker address
  function getStaker(address user) external view returns (Staker memory stakerInfo) {
    Staker memory staker = stakers[user];
    return staker;
  }

  /// @notice Check if NFT staked
  /// @param stakedArray array of all user staked tokens
  /// @param _tokeId staked NFT ID
  function checkTokenStaked(StakedToken[] memory stakedArray, uint _tokeId) internal pure returns (uint) {
    for (uint i = 0; i < stakedArray.length; i++) {
      if (stakedArray[i].stakedTokenId == _tokeId) {
        return i;
      }
    }
    revert("e2");
  }

  /// @notice Check if user has active FastTrack 
  /// @param stakedArray array of all user staked tokens
  function checkActiveFT(StakedToken[] memory stakedArray) private view {
    for (uint i = 0; i < stakedArray.length; i++) {
      if (stakedArray[i].FTConfig.startDate == stakingPlans['fasttrack'].FTConfig.startDate) {
        revert("e4");
      }
    }
  }

  /// @notice Burn NFT
  /// @param stakedArray array of all user staked tokens
  /// @param tokenId NFT ID which need to be burned
  function burnToken(StakedToken[] memory stakedArray, uint tokenId) private {
    checkTokenStaked(stakedArray, tokenId);
    _burn(tokenId);
  }

  /// @notice Close user staking and burn NFT
  /// @dev we allow owner to burn staking plan in this case we return NFT initial price
  /// @param _tokenId NFT ID which need to be burned
  function burnStakingPlan(uint _tokenId) external onlyOwner nonReentrant {
    removeStakedToken(stakers[tokenIdToStaker[_tokenId]], _tokenId, true);
  }

  /// @notice Deposit rewards tokens
  /// @param amount ERC-20 tokens amount
  function deposit(uint amount) external onlyAdmin nonReentrant {
    uint decimalsPrice = amount * BASE;
    transferUSDT(msg.sender, address(this), decimalsPrice, false);
    uint time = block.timestamp;
    emit Transaction(amount, "Contract deposit", time, msg.sender, 0);
  }

  /// @notice Withdraw rewards tokens
  /// @dev can be transferred only to Owner address
  /// @param _amount ERC-20 tokens amount
  function withdraw(uint _amount) external onlyAdmin nonReentrant {
    uint decimalsPrice = _amount * BASE;
    transferUSDT(address(this), address(owner()), decimalsPrice, true);
    uint time = block.timestamp;
    emit Transaction(_amount, "Contract withdraw", time, msg.sender, 0);
  }

  /// @notice Change rewards token
  /// @dev switch between USDT/USDC
  /// @param contractAddress new ERC-20 contract address
  /// @param _decimals new ERC-20 decimals
  function changeRewardsToken(address contractAddress, uint _decimals) external onlyOwner {
    require(_decimals > 0 && _decimals <= 18 && contractAddress != address(0));
    emit RewardsTokenChange(contractAddress, address(rewardsToken));
    rewardsToken = IERC20(contractAddress);
  }

  /// @notice Change stakers array max length
  /// @dev we can change max staked tokens per user
  /// @param max new ERC-20 contract address
  function changeMaxStakedToken(uint max) external onlyAdmin returns(uint) {
    require(max > 1000);
    maxStakedToken = max;
    return maxStakedToken;
  }
}
ERC721URIStorage.sol 58 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC721/extensions/ERC721URIStorage.sol)

pragma solidity ^0.8.20;

import {ERC721} from "../ERC721.sol";
import {IERC721Metadata} from "./IERC721Metadata.sol";
import {Strings} from "../../../utils/Strings.sol";
import {IERC4906} from "../../../interfaces/IERC4906.sol";
import {IERC165} from "../../../interfaces/IERC165.sol";

/**
 * @dev ERC-721 token with storage based token URI management.
 */
abstract contract ERC721URIStorage is IERC4906, ERC721 {
    using Strings for uint256;

    // Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only
    // defines events and does not include any external function.
    bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);

    // Optional mapping for token URIs
    mapping(uint256 tokenId => string) private _tokenURIs;

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
        return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IERC721Metadata
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireOwned(tokenId);

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = _baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via string.concat).
        if (bytes(_tokenURI).length > 0) {
            return string.concat(base, _tokenURI);
        }

        return super.tokenURI(tokenId);
    }

    /**
     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
     *
     * Emits {IERC4906-MetadataUpdate}.
     */
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        _tokenURIs[tokenId] = _tokenURI;
        emit MetadataUpdate(tokenId);
    }
}
Ownable2Step.sol 67 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}
ERC721.sol 430 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    mapping(uint256 tokenId => address) private _owners;

    mapping(address owner => uint256) private _balances;

    mapping(uint256 tokenId => address) private _tokenApprovals;

    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IERC721
    function balanceOf(address owner) public view virtual returns (uint256) {
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return _balances[owner];
    }

    /// @inheritdoc IERC721
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /// @inheritdoc IERC721Metadata
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /// @inheritdoc IERC721Metadata
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /// @inheritdoc IERC721Metadata
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /// @inheritdoc IERC721
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /// @inheritdoc IERC721
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /// @inheritdoc IERC721
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /// @inheritdoc IERC721
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /// @inheritdoc IERC721
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if:
     * - `spender` does not have approval from `owner` for `tokenId`.
     * - `spender` does not have approval to manage all of `owner`'s assets.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        unchecked {
            _balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                _balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                _balances[to] += 1;
            }
        }

        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC-721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        _tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }
}
IERC721.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}
SafeERC20.sol 212 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
ReentrancyGuardTransient.sol 61 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

import {TransientSlot} from "./TransientSlot.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

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

    /**
     * @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, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @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 REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

import {IERC721} from "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}
Strings.sol 490 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(add(buffer, 0x20), length)
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}
IERC4906.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4906.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";
import {IERC721} from "./IERC721.sol";

/// @title ERC-721 Metadata Update Extension
interface IERC4906 is IERC165, IERC721 {
    /// @dev This event emits when the metadata of a token is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFT.
    event MetadataUpdate(uint256 _tokenId);

    /// @dev This event emits when the metadata of a range of tokens is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFTs.
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";
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);
    }
}
ERC721Utils.sol 50 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC721/utils/ERC721Utils.sol)

pragma solidity ^0.8.20;

import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";

/**
 * @dev Library that provide common ERC-721 utility functions.
 *
 * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
 *
 * _Available since v5.1._
 */
library ERC721Utils {
    /**
     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC721Received(
        address operator,
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    // Token rejected
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC721Receiver implementer
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }
}
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;
    }
}
ERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
TransientSlot.sol 183 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}
Math.sol 749 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @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;
    }
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}
SignedMath.sol 68 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}
IERC721.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "../token/ERC721/IERC721.sol";
IERC721Receiver.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

Read Contract

balanceOf 0x70a08231 → uint256
getAllStakers 0x76a7d152 → tuple[]
getApproved 0x081812fc → address
getStaker 0xa23c44b1 → tuple
getStakingPlans 0x3bb2c773 → tuple[]
isAdmin 0x24d7806c → bool
isApprovedForAll 0xe985e9c5 → bool
name 0x06fdde03 → string
owner 0x8da5cb5b → address
ownerOf 0x6352211e → address
pendingOwner 0xe30c3978 → address
rewardsToken 0xd1af0c7d → address
stakers 0x9168ae72 → uint256, address
supportsInterface 0x01ffc9a7 → bool
symbol 0x95d89b41 → string
tokenIdToStaker 0x70f8f9d9 → address
tokenURI 0xc87b56dd → string

Write Contract 22 functions

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

acceptOwnership 0x79ba5097
No parameters
addAdmin 0xd16856ca
address account
string adminName
approve 0x095ea7b3
address to
uint256 tokenId
burnStakingPlan 0x99627a66
uint256 _tokenId
changeMaxStakedToken 0xb64a7f8c
uint256 max
returns: uint256
changeRewardsToken 0xa91195e5
address contractAddress
uint256 _decimals
claimReward 0xae169a50
uint256 _tokenId
createFastTrackPlan 0xd2be9783
uint256 percentage
uint256 startDate
uint256 endDate
uint256 saleStartDate
uint256 saleEndDate
uint256 userMin
uint256 userMax
uint256 targetAmount
createFreeFlowPlan 0x07edffc9
uint256 percentage
createStandardPlan 0x547827d3
string variant
uint256 month
uint256 percentage
uint256 extraDaysPercentage
deactivateAdmin 0xdf6fa20e
address account
deactivateStakingPlan 0xe2ceea44
string name
deactivateStandardPlan 0x7f59729f
string name
uint256 month
deposit 0xb6b55f25
uint256 amount
mintToken 0xd1c0b58d
string tokenURI
uint256 price
uint256 depositTerm
string interest
returns: uint256
renounceOwnership 0x715018a6
No parameters
safeTransferFrom 0x42842e0e
address from
address to
uint256 tokenId
safeTransferFrom 0xb88d4fde
address
address
uint256
bytes
setApprovalForAll 0xa22cb465
address operator
bool approved
transferFrom 0x23b872dd
address
address
uint256
transferOwnership 0xf2fde38b
address newOwner
withdraw 0x2e1a7d4d
uint256 _amount

Recent Transactions

No transactions found for this address